-
Notifications
You must be signed in to change notification settings - Fork 101
Expand file tree
/
Copy pathVTKPolyDataWriterInterface.cpp
More file actions
1436 lines (1288 loc) · 56.6 KB
/
VTKPolyDataWriterInterface.cpp
File metadata and controls
1436 lines (1288 loc) · 56.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* ------------------------------------------------------------------------------------------------------------
* SPDX-License-Identifier: LGPL-2.1-only
*
* Copyright (c) 2016-2024 Lawrence Livermore National Security LLC
* Copyright (c) 2018-2024 TotalEnergies
* Copyright (c) 2018-2024 The Board of Trustees of the Leland Stanford Junior University
* Copyright (c) 2023-2024 Chevron
* Copyright (c) 2019- GEOS/GEOSX Contributors
* All rights reserved
*
* See top level LICENSE, COPYRIGHT, CONTRIBUTORS, NOTICE, and ACKNOWLEDGEMENTS files for details.
* ------------------------------------------------------------------------------------------------------------
*/
// Source includes
#include "VTKPolyDataWriterInterface.hpp"
#include "common/logger/Logger.hpp"
#include "common/TypeDispatch.hpp"
#include "dataRepository/Group.hpp"
#include "mesh/DomainPartition.hpp"
#include "fileIO/Outputs/OutputUtilities.hpp"
// TPL includes
#include <vtkCellArray.h>
#include <vtkCellData.h>
#include <vtkDoubleArray.h>
#include <vtkPassThrough.h>
#include <vtkPointData.h>
#include <vtkPoints.h>
#include <vtkSmartPointer.h>
#include <vtkThreshold.h>
#include <vtkUnstructuredGrid.h>
#include <vtkXMLUnstructuredGridWriter.h>
#include <vtkAggregateDataSetFilter.h>
// System includes
#include <numeric>
#include <unordered_set>
#include "mesh/generators/VTKUtilities.hpp"
namespace geos
{
using namespace dataRepository;
namespace vtk
{
VTKPolyDataWriterInterface::VTKPolyDataWriterInterface( string name ):
m_outputDir( "." ),
m_outputName( std::move( name ) ),
m_pvd( m_outputName + ".pvd" ),
m_writeGhostCells( false ),
m_plotLevel( PlotLevel::LEVEL_1 ),
m_requireFieldRegistrationCheck( true ),
m_previousCycle( -1 ),
m_outputMode( VTKOutputMode::BINARY ),
m_outputRegionType( VTKRegionTypes::ALL ),
m_writeFaceElementsAs3D( false )
{}
static int
toVTKCellType( ElementType const elementType, localIndex const numNodes )
{
switch( elementType )
{
case ElementType::Vertex: return VTK_VERTEX;
case ElementType::Line: return VTK_LINE;
case ElementType::Triangle: return VTK_TRIANGLE;
case ElementType::Quadrilateral: return VTK_QUAD;
case ElementType::Polygon: return VTK_POLYGON;
case ElementType::Tetrahedron: return VTK_TETRA;
case ElementType::Pyramid: return VTK_PYRAMID;
case ElementType::Wedge: return VTK_WEDGE;
case ElementType::Hexahedron:
switch( numNodes )
{
case 8:
return VTK_HEXAHEDRON;
case 27:
return VTK_QUADRATIC_HEXAHEDRON;
default:
return VTK_HEXAHEDRON;
}
case ElementType::Prism5: return VTK_PENTAGONAL_PRISM;
case ElementType::Prism6: return VTK_HEXAGONAL_PRISM;
case ElementType::Prism7: return VTK_POLYHEDRON;
case ElementType::Prism8: return VTK_POLYHEDRON;
case ElementType::Prism9: return VTK_POLYHEDRON;
case ElementType::Prism10: return VTK_POLYHEDRON;
case ElementType::Prism11: return VTK_POLYHEDRON;
case ElementType::Polyhedron: return VTK_POLYHEDRON;
}
return VTK_EMPTY_CELL;
}
static int
toVTKCellType( ParticleType const particleType )
{
switch( particleType )
{
case ParticleType::SinglePoint: return VTK_HEXAHEDRON;
case ParticleType::CPDI: return VTK_HEXAHEDRON;
case ParticleType::CPDI2: return VTK_HEXAHEDRON;
case ParticleType::CPTI: return VTK_TETRA;
}
return VTK_EMPTY_CELL;
}
static stdVector< int >
getVtkToGeosxNodeOrdering( ParticleType const particleType )
{
switch( particleType )
{
case ParticleType::SinglePoint: return { 0, 1, 3, 2, 4, 5, 7, 6 };
case ParticleType::CPDI: return { 0, 1, 3, 2, 4, 5, 7, 6 };
case ParticleType::CPDI2: return { 0, 1, 3, 2, 4, 5, 7, 6 };
case ParticleType::CPTI: return { 0, 1, 2, 3 };
}
return {};
}
/**
* @brief Provide the local list of nodes or face streams for the corresponding VTK element
*
* @param elementType geos element type
* @return list of nodes or face streams
*
* For geos element with existing standard VTK element the corresponding list of nodes is provided.
* For Prism7+, the geos element is converted to VTK_POLYHEDRON. The vtkUnstructuredGrid
* stores polyhedron cells as face streams of the following format:
* [numberOfCellFaces,
* (numberOfPointsOfFace0, pointId0, pointId1, ... ),
* (numberOfPointsOfFace1, pointId0, pointId1, ... ),
* ...]
* We use the same format except that the number of faces and the number of nodes per faces
* are provided as negative values. This convention provides a simple way to isolate the local
* nodes for mapping purpose while keeping a face streams data structure. The negative values are
* converted to positives when generating the VTK_POLYHEDRON. Check getVtkCells() for more details.
*/
static stdVector< int > getVtkConnectivity( ElementType const elementType, localIndex const numNodes )
{
switch( elementType )
{
case ElementType::Vertex: return { 0 };
case ElementType::Line: return { 0, 1 };
case ElementType::Triangle: return { 0, 1, 2 };
case ElementType::Quadrilateral: return { 0, 1, 2, 3 };
case ElementType::Polygon: return { }; // TODO
case ElementType::Tetrahedron: return { 0, 1, 2, 3 };
case ElementType::Pyramid: return { 0, 1, 3, 2, 4 };
case ElementType::Wedge: return { 0, 4, 2, 1, 5, 3 };
case ElementType::Hexahedron:
switch( numNodes )
{
case 8:
return { 0, 1, 3, 2, 4, 5, 7, 6 };
break;
case 27:
// Numbering convention changed between VTK writer 1.0 and 2.2, see
// https://discourse.julialang.org/t/writevtk-node-numbering-for-27-node-lagrange-hexahedron/93698/8
// GEOS uses 1.0 API
return { 0, 2, 8, 6, 18, 20, 26, 24, 1, 5, 7, 3, 19, 23, 25, 21, 9, 11, 17, 15, 12, 14, 10, 16, 4, 22, 17 };
break;
default:
return { }; // TODO
}
case ElementType::Prism5: return { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
case ElementType::Prism6: return { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
case ElementType::Prism7: return {-9,
-7, 0, 1, 2, 3, 4, 5, 6,
-7, 7, 8, 9, 10, 11, 12, 13,
-4, 0, 1, 8, 7,
-4, 1, 2, 9, 8,
-4, 2, 3, 10, 9,
-4, 3, 4, 11, 10,
-4, 4, 5, 12, 11,
-4, 5, 6, 13, 12,
-4, 6, 0, 7, 13 };
case ElementType::Prism8: return {-10,
-8, 0, 1, 2, 3, 4, 5, 6, 7,
-8, 8, 9, 10, 11, 12, 13, 14, 15,
-4, 0, 1, 9, 8,
-4, 1, 2, 10, 9,
-4, 2, 3, 11, 10,
-4, 3, 4, 12, 11,
-4, 4, 5, 13, 12,
-4, 5, 6, 14, 13,
-4, 6, 7, 15, 14,
-4, 7, 0, 8, 15 };
case ElementType::Prism9: return {-11,
-9, 0, 1, 2, 3, 4, 5, 6, 7, 8,
-9, 9, 10, 11, 12, 13, 14, 15, 16, 17,
-4, 0, 1, 10, 9,
-4, 1, 2, 11, 10,
-4, 2, 3, 12, 11,
-4, 3, 4, 13, 12,
-4, 4, 5, 14, 13,
-4, 5, 6, 15, 14,
-4, 6, 7, 16, 15,
-4, 7, 8, 17, 16,
-4, 8, 0, 9, 17 };
case ElementType::Prism10: return {-12,
-10, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
-10, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
-4, 0, 1, 11, 10,
-4, 1, 2, 12, 11,
-4, 2, 3, 13, 12,
-4, 3, 4, 14, 13,
-4, 4, 5, 15, 14,
-4, 5, 6, 16, 15,
-4, 6, 7, 17, 16,
-4, 7, 8, 18, 17,
-4, 8, 9, 19, 18,
-4, 9, 0, 10, 19 };
case ElementType::Prism11: return {-13,
-11, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
-11, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21,
-4, 0, 1, 12, 11,
-4, 1, 2, 13, 12,
-4, 2, 3, 14, 13,
-4, 3, 4, 15, 14,
-4, 4, 5, 16, 15,
-4, 5, 6, 17, 16,
-4, 6, 7, 18, 17,
-4, 7, 8, 19, 18,
-4, 8, 9, 20, 19,
-4, 9, 10, 21, 20,
-4, 10, 0, 11, 21 };
case ElementType::Polyhedron: return { }; // TODO
}
return {};
}
/**
* @brief Gets the vertices coordinates as a VTK Object for @p nodeManager
* @param[in] nodeManager the NodeManager associated with the domain being written
* @return a VTK object storing all nodes of the mesh
*/
static vtkSmartPointer< vtkPoints >
getVtkPoints( NodeManager const & nodeManager,
arrayView1d< localIndex const > const & nodeIndices )
{
localIndex const numNodes = LvArray::integerConversion< localIndex >( nodeIndices.size() );
auto points = vtkSmartPointer< vtkPoints >::New();
points->SetNumberOfPoints( numNodes );
auto const coord = nodeManager.referencePosition().toViewConst();
forAll< parallelHostPolicy >( numNodes, [=, pts = points.GetPointer()]( localIndex const k )
{
localIndex const v = nodeIndices[k];
pts->SetPoint( k, coord[v][0], coord[v][1], coord[v][2] );
} );
return points;
}
/**
* @brief Gets the vertex coordinates as a VTK Object for @p particleManager
* @param[in] particleManager the ParticleManager associated with the domain being written
* @return a VTK object storing all particle centers/corners of the mesh
*/
static vtkSmartPointer< vtkPoints >
getVtkPoints( ParticleRegion const & particleRegion ) // TODO: Loop over the subregions owned by this region and operate on them directly
{
// Particles are plotted as polyhedron with the geometry determined by the particle
// type. CPDI particles are parallelepiped (8 corners and 6 faces).
// TODO: add support for CPTI (tet) and single point (cube or sphere) geometries
localIndex const numCornersPerParticle = 8; // Each CPDI particle has 8 corners. TODO: add support for other particle types.
localIndex const numCorners = numCornersPerParticle * particleRegion.getNumberOfParticles();
auto points = vtkSmartPointer< vtkPoints >::New();
points->SetNumberOfPoints( numCorners );
array2d< real64 > const coord = particleRegion.getParticleCorners();
forAll< parallelHostPolicy >( numCorners, [=, pts = points.GetPointer()]( localIndex const k )
{
pts->SetPoint( k, coord[k][0], coord[k][1], coord[k][2] );
} );
return points;
}
struct ElementData
{
stdVector< int > cellTypes;
vtkSmartPointer< vtkCellArray > cells;
vtkSmartPointer< vtkPoints > points;
};
/**
* @brief Gets the cell connectivities and the vertices coordinates as VTK objects for a specific WellElementSubRegion.
* @param[in] subRegion the WellElementSubRegion to be output
* @param[in] nodeManager the NodeManager associated with the DomainPartition being written.
* @return a pair containing a VTKPoints (with the information on the vertices and their coordinates)
* and a VTKCellArray (with the cell connectivities).
*/
static ElementData
getWell( WellElementSubRegion const & subRegion,
NodeManager const & nodeManager )
{
// some notes about WellElementSubRegion:
// - if the well represented by this subRegion is not on this rank, esr.size() = 0
// - otherwise, esr.size() is equal to the number of well elements of the well on this rank
// Each well element has two nodes, shared with the previous and next well elements, respectively
auto points = vtkSmartPointer< vtkPoints >::New();
// if esr.size() == 0, we set the number of points and cells to zero
// if not, we set the number of points to esr.size()+1 and the number of cells to esr.size()
localIndex const numPoints = subRegion.size() > 0 ? subRegion.size() + 1 : 0;
points->SetNumberOfPoints( numPoints );
auto cellsArray = vtkSmartPointer< vtkCellArray >::New();
localIndex const numberOfNodesPerElement = subRegion.numNodesPerElement();
//deprecated
//cellsArray->SetNumberOfCells( subRegion.size() );
cellsArray->AllocateExact( subRegion.size(), numberOfNodesPerElement*subRegion.size() );
GEOS_ERROR_IF_NE( numberOfNodesPerElement, 2 );
stdVector< vtkIdType > connectivity( numberOfNodesPerElement );
arrayView2d< real64 const, nodes::REFERENCE_POSITION_USD > const referencePosition = nodeManager.referencePosition();
// note that if esr.size() == 0, we don't have any point or cell to add below and we just return
for( localIndex edge = 0; edge < subRegion.size(); edge++ )
{
localIndex const firstPoint = subRegion.nodeList()[edge][0];
auto point = referencePosition[firstPoint];
points->SetPoint( edge, point[0], point[1], point[2] );
connectivity[0] = edge;
connectivity[1] = edge + 1; // We can do that because of the pattern in which the wells are stored
cellsArray->InsertNextCell( numberOfNodesPerElement, connectivity.data() );
}
if( subRegion.size() > 0 )
{
localIndex const lastPoint = subRegion.nodeList()[subRegion.size() - 1][1];
auto point = referencePosition[lastPoint];
points->SetPoint( subRegion.size(), point[0], point[1], point[2] );
}
stdVector< int > cellTypes( subRegion.size(), VTK_LINE );
return { cellTypes, cellsArray, points };
}
/**
* @brief Gets the cell connectivities and the vertices coordinates as VTK objects for a specific FaceElementSubRegion.
* @param[in] subRegion the FaceElementSubRegion to be output
* @param[in] nodeManager the NodeManager associated with the DomainPartition being written.
* @param[in] faceManager the faceManager associated with the DomainPartition being written.
* @return a pair containing a VTKPoints (with the information on the vertices and their coordinates)
* and a VTKCellArray (with the cell connectivities).
*/
static ElementData
getSurface( FaceElementSubRegion const & subRegion,
NodeManager const & nodeManager,
FaceManager const & faceManager,
bool const writeFaceElementsAs3D )
{
// Get unique node set composing the surface
auto & elemToFaces = subRegion.faceList();
auto & elemToNodes = subRegion.nodeList();
auto & faceToNodes = faceManager.nodeList();
auto cellArray = vtkSmartPointer< vtkCellArray >::New();
//deprecated
//cellArray->SetNumberOfCells( subRegion.size() );
cellArray->AllocateEstimate( subRegion.size(), subRegion.size() * subRegion.numNodesPerElement() );
stdVector< int > cellTypes;
cellTypes.reserve( subRegion.size() );
std::unordered_map< localIndex, localIndex > geos2VTKIndexing;
geos2VTKIndexing.reserve( subRegion.size() * subRegion.numNodesPerElement() );
localIndex nodeIndexInVTK = 0;
// FaceElementSubRegion being heterogeneous, the size of the connectivity vector may vary for each element.
// In order not to allocate a new vector every time, we combine the usage of `clear` and `push_back`.
stdVector< vtkIdType > connectivity;
for( localIndex ei = 0; ei < subRegion.size(); ei++ )
{
// we use the nodes of face 0
auto const & nodes = !writeFaceElementsAs3D ? faceToNodes[elemToFaces( ei, 0 )] : elemToNodes[ei];
auto const numNodes = nodes.size();
ElementType const elementType = subRegion.getElementType( ei );
stdVector< int > vtkOrdering;
if( elementType == ElementType::Polygon || writeFaceElementsAs3D )
{
vtkOrdering.resize( numNodes );
std::iota( vtkOrdering.begin(), vtkOrdering.end(), 0 );
}
else
{
vtkOrdering = getVtkConnectivity( elementType, numNodes );
}
connectivity.clear();
for( int const & ordering : vtkOrdering )
{
auto const & VTKIndexPos = geos2VTKIndexing.find( nodes[ordering] );
if( VTKIndexPos == geos2VTKIndexing.end() )
{
/// If the node is not found in the geos2VTKIndexing map:
/// 1. we assign the current value of nodeIndexInVTK to this node in the map (geos2VTKIndexing[nodes[ordering]] =
/// nodeIndexInVTK++).
/// 2. we increment nodeIndexInVTK to ensure the next new node gets a unique index.
/// 3. we add this new VTK node index to the connectivity vector (connectivity.push_back).
connectivity.push_back( geos2VTKIndexing[nodes[ordering]] = nodeIndexInVTK++ );
}
else
{
connectivity.push_back( VTKIndexPos->second );
}
}
cellArray->InsertNextCell( vtkOrdering.size(), connectivity.data() );
cellTypes.emplace_back( toVTKCellType( elementType, numNodes ) );
}
auto points = vtkSmartPointer< vtkPoints >::New();
points->SetNumberOfPoints( geos2VTKIndexing.size() );
arrayView2d< real64 const, nodes::REFERENCE_POSITION_USD > const referencePosition = nodeManager.referencePosition();
for( auto nodeIndex: geos2VTKIndexing )
{
auto point = referencePosition[nodeIndex.first];
points->SetPoint( nodeIndex.second, point[0], point[1], point[2] );
}
return { cellTypes, cellArray, points };
}
/**
* @brief Gets the cell connectivities and the vertices coordinates as VTK objects for a specific
* EmbeddedSurafaceSubRegion.
* @param[in] subRegion the EmbeddedSurfaceSubRegion to be output
* @param[in] nodeManager the NodeManager associated with the DomainPartition being written.
* @return a pair containing a VTKPoints (with the information on the vertices and their coordinates)
* and a VTKCellArray (with the cell connectivities).
*/
static ElementData
getEmbeddedSurface( EmbeddedSurfaceSubRegion const & subRegion,
EmbeddedSurfaceNodeManager const & nodeManager )
{
auto cellsArray = vtkSmartPointer< vtkCellArray >::New();
auto points = vtkSmartPointer< vtkPoints >::New();
localIndex const numNodes = nodeManager.size();
auto const intersectionPoints = nodeManager.referencePosition();
points->SetNumberOfPoints( numNodes );
for( localIndex pointIndex = 0; pointIndex < numNodes; ++pointIndex )
{
auto const pointCoords = intersectionPoints[pointIndex];
points->SetPoint( pointIndex, pointCoords[0], pointCoords[1], pointCoords[2] );
}
auto const toNodesMap = subRegion.nodeList().toViewConst();
stdVector< vtkIdType > connectivity( 10 );
for( localIndex cellIndex = 0; cellIndex < subRegion.size(); ++cellIndex )
{
auto const nodes = toNodesMap[cellIndex];
connectivity.resize( nodes.size() );
for( localIndex i = 0; i < nodes.size(); ++i )
{
connectivity[i] = nodes[i];
}
cellsArray->InsertNextCell( nodes.size(), connectivity.data() );
}
stdVector< int > cellTypes( subRegion.size(), VTK_POLYGON );
return { cellTypes, cellsArray, points };
}
struct CellData
{
stdVector< int > cellTypes;
vtkSmartPointer< vtkCellArray > cells;
array1d< localIndex > nodes;
};
/**
* @brief Gets the cell connectivities as a VTK object for the CellElementRegion @p region
* @param[in] region the CellElementRegion to be written
* @param[in] numNodes number of local nodes
* @return a struct consisting of:
* - a list of types for each cell,
* - a VTK object containing the connectivity information
* - a list of relevant node indices in order in which they must be stored
*/
static CellData
getVtkCells( CellElementRegion const & region,
localIndex const numNodes )
{
localIndex const numElems = region.getNumberOfElements< CellElementSubRegion >();
if( numElems == 0 )
{
return { {}, vtkSmartPointer< vtkCellArray >::New(), {} };
}
// 1. Mark (in parallel) relevant nodes
stdVector< localIndex > newNodeIndices( numNodes ); // temporary use as a marker array
region.forElementSubRegions< CellElementSubRegion >( [&]( CellElementSubRegion const & subRegion )
{
auto const nodeList = subRegion.nodeList().toViewConst();
forAll< parallelHostPolicy >( subRegion.size(), [&, nodeList]( localIndex const cellIdx )
{
auto const nodes = nodeList[cellIdx];
for( localIndex i = 0; i < nodes.size(); ++i )
{
// use atomic write to avoid technical UB
RAJA::atomicExchange< parallelHostAtomic >( &newNodeIndices[nodes[i]], 1 );
}
} );
} );
// 2. Assign new node IDs (serial step)
array1d< localIndex > relevantNodes;
relevantNodes.reserve( numNodes );
localIndex newNodeIdx = 0;
for( localIndex nodeIdx = 0; nodeIdx < numNodes; ++nodeIdx )
{
if( newNodeIndices[nodeIdx] > 0 )
{
relevantNodes.emplace_back( nodeIdx );
newNodeIndices[nodeIdx] = newNodeIdx++;
}
}
// 3. Write connectivity using new node IDs
localIndex const numConns = [&]
{
localIndex numConn = 0;
region.forElementSubRegions< CellElementSubRegion >( [&]( CellElementSubRegion const & subRegion )
{
numConn += subRegion.size() * getVtkConnectivity( subRegion.getElementType(), subRegion.nodeList().size( 1 ) ).size();
} );
return numConn;
}();
stdVector< int > cellTypes;
cellTypes.reserve( numElems );
auto const offsets = vtkSmartPointer< vtkIdTypeArray >::New();
offsets->SetNumberOfTuples( numElems + 1 );
auto const connectivity = vtkSmartPointer< vtkIdTypeArray >::New();
connectivity->SetNumberOfTuples( numConns );
// 4. Write connectivity using new node IDs
localIndex elemOffset = 0;
localIndex connOffset = 0;
region.forElementSubRegions< CellElementSubRegion >( [&]( CellElementSubRegion const & subRegion )
{
auto const nodeList = subRegion.nodeList().toViewConst();
auto subRegionNumNodes = nodeList.size( 1 );
cellTypes.insert( cellTypes.end(), subRegion.size(), toVTKCellType( subRegion.getElementType(), subRegionNumNodes ) );
stdVector< int > const vtkOrdering = getVtkConnectivity( subRegion.getElementType(), subRegionNumNodes );
localIndex const numVtkData = vtkOrdering.size();
// For all geos element, the corresponding VTK data are copied in "connectivity".
// Local nodes are mapped to global indices. Any negative value in "vtkOrdering"
// corresponds to the number of faces or the number of nodes per faces, and they
// are copied as positive values.
// Here we privilege code simplicity. This can be more efficient (less tests) if the code is
// specialized for each type of subregion.
// This is not a time sensitive part of the code. Can be optimized later if needed.
forAll< parallelHostPolicy >( subRegion.size(), [&]( localIndex const c )
{
localIndex const elemConnOffset = connOffset + c * numVtkData;
auto const nodes = nodeList[c];
for( localIndex i = 0; i < numVtkData; ++i )
{
if( vtkOrdering[i] < 0 )
{
connectivity->SetTypedComponent( elemConnOffset + i, 0, -vtkOrdering[i] );
}
else
{
connectivity->SetTypedComponent( elemConnOffset + i, 0, newNodeIndices[nodes[vtkOrdering[i]]] );
}
}
offsets->SetTypedComponent( elemOffset + c, 0, elemConnOffset );
} );
elemOffset += subRegion.size();
connOffset += subRegion.size() * numVtkData;
} );
offsets->SetTypedComponent( elemOffset, 0, connOffset );
auto cellsArray = vtkSmartPointer< vtkCellArray >::New();
cellsArray->SetData( offsets, connectivity );
return { std::move( cellTypes ), cellsArray, std::move( relevantNodes ) };
}
using ParticleData = std::pair< stdVector< int >, vtkSmartPointer< vtkCellArray > >;
/**
* @brief Gets the cell connectivities as a VTK object for the ParticleRegion @p region
* @param[in] region the ParticleRegion to be written
* @return a standard pair consisting of:
* - a list of types for each cell,
* - a VTK object containing the connectivity information
*/
static ParticleData
getVtkCells( ParticleRegion const & region )
{
vtkSmartPointer< vtkCellArray > cellsArray = vtkCellArray::New();
//deprecated
//cellsArray->SetNumberOfCells( region.getNumberOfParticles< ParticleRegion >() );
cellsArray->AllocateExact( region.getNumberOfParticles< ParticleRegion >(), region.getNumberOfParticles< ParticleRegion >() );
stdVector< int > cellType;
cellType.reserve( region.getNumberOfParticles< ParticleRegion >() );
vtkIdType nodeIndex = 0;
region.forParticleSubRegions< ParticleSubRegion >( [&]( ParticleSubRegion const & subRegion )
{
stdVector< int > vtkOrdering = getVtkToGeosxNodeOrdering( subRegion.getParticleType() );
stdVector< vtkIdType > connectivity( vtkOrdering.size() );
int vtkCellType = toVTKCellType( subRegion.getParticleType() );
for( localIndex c = 0; c < subRegion.size(); c++ )
{
for( std::size_t i = 0; i < connectivity.size(); i++ )
{
connectivity[i] = vtkOrdering.size()*nodeIndex + vtkOrdering[i];
}
nodeIndex++;
cellType.push_back( vtkCellType );
cellsArray->InsertNextCell( vtkOrdering.size(), connectivity.data() );
}
} );
return std::make_pair( cellType, cellsArray );
}
/**
* @brief Writes timestamp information required by VisIt
* @param[in] ug the VTK unstructured grid.
* @param[in] time the current time-step
*/
static void
writeTimestamp( vtkUnstructuredGrid * ug,
real64 const time )
{
auto t = vtkSmartPointer< vtkDoubleArray >::New();
t->SetName( "TIME" );
t->SetNumberOfTuples( 1 );
t->SetTuple1( 0, time );
ug->GetFieldData()->AddArray( t );
}
/**
* @brief Writes a field from @p wrapper.
* @param[in] wrapper a wrapper around the field to be written
* @param[in] offset the cell index offset at which to start writing data (in case of multiple subregions)
* @param[in,out] data a VTK data container, must be a vtkAOSDataArrayTemplate of the correct value type
*/
static void
writeField( WrapperBase const & wrapper,
localIndex const offset,
vtkDataArray * data )
{
types::dispatch( types::ListofTypeList< types::StandardArrays >{}, [&]( auto tupleOfTypes )
{
using ArrayType = camp::first< decltype( tupleOfTypes ) >;
using T = typename ArrayType::ValueType;
vtkAOSDataArrayTemplate< T > * typedData = vtkAOSDataArrayTemplate< T >::FastDownCast( data );
auto const sourceArray = Wrapper< ArrayType >::cast( wrapper ).reference().toViewConst();
forAll< parallelHostPolicy >( sourceArray.size( 0 ), [sourceArray, offset, typedData]( localIndex const i )
{
LvArray::forValuesInSlice( sourceArray[i], [&, compIndex = 0]( T const & value ) mutable
{
typedData->SetTypedComponent( offset + i, compIndex++, value );
} );
} );
}, wrapper );
}
/**
* @brief Writes a field from @p wrapper using an index list.
* @param[in] wrapper a wrapper around the field to be written
* @param[in] indices a list of indices into @p wrapper that will be written
* @param[in] offset the cell index offset at which to start writing data (in case of multiple subregions)
* @param[in,out] data a VTK data container, must be a vtkAOSDataArrayTemplate of the correct value type
*/
static void
writeField( WrapperBase const & wrapper,
arrayView1d< localIndex const > const & indices,
localIndex const offset,
vtkDataArray * data )
{
types::dispatch( types::ListofTypeList< types::StandardArrays >{}, [&]( auto tupleOfTypes )
{
using ArrayType = camp::first< decltype( tupleOfTypes ) >;
using T = typename ArrayType::ValueType;
vtkAOSDataArrayTemplate< T > * typedData = vtkAOSDataArrayTemplate< T >::FastDownCast( data );
auto const sourceArray = Wrapper< ArrayType >::cast( wrapper ).reference().toViewConst();
forAll< parallelHostPolicy >( indices.size(), [=]( localIndex const i )
{
LvArray::forValuesInSlice( sourceArray[indices[i]], [&, compIndex = 0]( T const & value ) mutable
{
typedData->SetTypedComponent( offset + i, compIndex++, value );
} );
} );
}, wrapper );
}
/**
* @brief Build/expand a list of strings used as default component labels on demand.
* @param size number of labels requested
* @return a span over range of strings (stored permanently in memory)
*/
static Span< string const >
getDefaultLabels( localIndex const size )
{
static stdVector< string > labels;
localIndex oldSize = LvArray::integerConversion< localIndex >( labels.size() );
std::generate_n( std::back_inserter( labels ), size - oldSize, [&] { return std::to_string( oldSize++ ); } );
return { labels.begin(), labels.begin() + size };
}
/**
* @brief Checks consistency of user-provided per-dimension labels (must match the size of array).
* @param wrapper the array wrapper
* @param dim dimension index to check
*/
template< typename T, int NDIM, typename PERM >
void checkLabels( Wrapper< Array< T, NDIM, PERM > > const & wrapper, int const dim )
{
GEOS_ERROR_IF_NE_MSG( LvArray::integerConversion< localIndex >( wrapper.getDimLabels( dim ).size() ),
wrapper.reference().size( dim ),
"VTK writer: component names are set, but don't match the array size.\n"
"This is likely a bug in physics module (solver or constitutive model)." );
}
/**
* @brief Get a list of component labels for a particular dimension of an array.
* @param wrapper array wrapper
* @param dim dimension index
* @return a span over range of strings representing labels
*/
template< typename T, int NDIM, typename PERM >
static Span< string const >
getDimLabels( Wrapper< Array< T, NDIM, PERM > > const & wrapper,
int const dim )
{
Span< string const > const labels = wrapper.getDimLabels( dim );
if( labels.empty() )
{
return getDefaultLabels( wrapper.reference().size( dim ) );
}
checkLabels( wrapper, dim );
return labels;
}
/**
* @brief Build a multidimensional component name out of distinct dimension-wise labels.
* @tparam Ts types of indices
* @tparam Is dummy template argument required for positional expansion of the pack
* @param dimLabels per-dimension component labels
* @param indices per-dimension component indices
* @return combined component name
*/
template< typename ... Ts, integer ... Is >
static string
makeComponentName( stdVector< string >(&dimLabels)[sizeof...( Ts )],
std::integer_sequence< integer, Is... >,
Ts const & ... indices )
{
return stringutilities::concat( '/', dimLabels[Is][indices] ... );
}
/**
* @brief Specialized component metadata handler for 1D arrays.
* @param data VTK typed data array
*/
template< typename T, typename PERM >
static void
setComponentMetadata( Wrapper< Array< T, 1, PERM > > const &,
vtkAOSDataArrayTemplate< T > * data )
{
data->SetNumberOfComponents( 1 );
}
/**
* @brief Specialized component metadata handler for 2D arrays.
* @param wrapper GEOSX typed wrapper over source array
* @param data VTK typed data array
*
* This exists because we want to keep default VTK handling for unlabeled components
* (i.e. X/Y/Z for 1-3 components, numeric indices for higher) for the time being.
* This function can be removed if we force each physics package to always set its labels.
*/
template< typename T, typename PERM >
static void
setComponentMetadata( Wrapper< Array< T, 2, PERM > > const & wrapper,
vtkAOSDataArrayTemplate< T > * data )
{
auto const view = wrapper.referenceAsView();
data->SetNumberOfComponents( view.size( 1 ) );
Span< string const > const labels = wrapper.getDimLabels( 1 );
if( !labels.empty() )
{
checkLabels( wrapper, 1 );
for( localIndex i = 0; i < view.size( 1 ); ++i )
{
data->SetComponentName( i, labels[i].c_str() );
}
}
}
/**
* @brief Produces a temporary array slice from a view that can be looped over.
* @param view the source view
* @return a fake slice that does not point to real data but has correct dims/strides.
* @note The slice is only valid as long as the @p view is in scope.
* Values in the slice may be uninitialized and should not be used.
*/
template< typename T, int NDIM, int USD >
static ArraySlice< T const, NDIM - 1, USD - 1 >
makeTemporarySlice( ArrayView< T const, NDIM, USD > const & view )
{
// The following works in all compilers, but technically invokes undefined behavior:
// return ArraySlice< T, NDIM - 1, USD - 1 >( nullptr, view.dims() + 1, view.strides() + 1 );
localIndex const numComp = LvArray::indexing::multiplyAll< NDIM - 1 >( view.dims() + 1 );
static array1d< T > arr;
arr.template resizeWithoutInitializationOrDestruction<>( numComp );
return ArraySlice< T const, NDIM - 1, USD - 1 >( arr.data(), view.dims() + 1, view.strides() + 1 );
}
/**
* @brief Generic component metadata handler for multidimensional arrays.
* @param wrapper GEOSX typed wrapper over source array
* @param data VTK typed data array
*/
template< typename T, int NDIM, typename PERM >
static void
setComponentMetadata( Wrapper< Array< T, NDIM, PERM > > const & wrapper,
vtkAOSDataArrayTemplate< T > * data )
{
data->SetNumberOfComponents( wrapper.numArrayComp() );
stdVector< string > labels[NDIM-1];
for( integer dim = 1; dim < NDIM; ++dim )
{
Span< string const > dimLabels = getDimLabels( wrapper, dim );
labels[dim-1].assign( dimLabels.begin(), dimLabels.end() );
}
auto const view = wrapper.referenceAsView();
auto const slice = view.size( 0 ) > 0 ? view[0] : makeTemporarySlice( view );
integer compIndex = 0;
LvArray::forValuesInSliceWithIndices( slice, [&]( T const &, auto const ... indices )
{
using idx_seq = std::make_integer_sequence< integer, sizeof...(indices) >;
data->SetComponentName( compIndex++, makeComponentName( labels, idx_seq{}, indices ... ).c_str() );
} );
}
template< class SUBREGION = Group >
static void
writeElementField( Group const & subRegions,
string const & field,
vtkCellData * cellData )
{
// instantiate vtk array of the correct type
vtkSmartPointer< vtkDataArray > data;
localIndex numElements = 0;
bool first = true;
int numDims = 0;
subRegions.forSubGroups< SUBREGION >( [&]( SUBREGION const & subRegion )
{
numElements += subRegion.size();
WrapperBase const & wrapper = subRegion.getWrapperBase( field );
if( first )
{
types::dispatch( types::ListofTypeList< types::StandardArrays >{}, [&]( auto tupleOfTypes )
{
using ArrayType = camp::first< decltype( tupleOfTypes ) >;
using T = typename ArrayType::ValueType;
auto typedData = vtkAOSDataArrayTemplate< T >::New();
data.TakeReference( typedData );
setComponentMetadata( Wrapper< ArrayType >::cast( wrapper ), typedData );
}, wrapper );
first = false;
numDims = wrapper.numArrayDims();
}
else
{
// Sanity check
GEOS_ERROR_IF_NE_MSG( wrapper.numArrayDims(), numDims,
"VTK writer: sanity check failed for " << field << " (inconsistent array dimensions)" );
GEOS_ERROR_IF_NE_MSG( wrapper.numArrayComp(), data->GetNumberOfComponents(),
"VTK writer: sanity check failed for " << field << " (inconsistent array sizes)" );
}
} );
data->SetNumberOfTuples( numElements );
data->SetName( field.c_str() );
// write each subregion in turn, keeping track of element offset
localIndex offset = 0;
subRegions.forSubGroups< SUBREGION >( [&]( SUBREGION const & subRegion )
{
WrapperBase const & wrapper = subRegion.getWrapperBase( field );
writeField( wrapper, offset, data.GetPointer() );
offset += subRegion.size();
} );
cellData->AddArray( data );
}
void VTKPolyDataWriterInterface::writeParticleFields( ParticleRegionBase const & region,
vtkCellData * cellData ) const
{
std::unordered_set< string > materialFields;
conduit::Node fakeRoot;
Group materialData( "materialData", fakeRoot );
region.forParticleSubRegions( [&]( ParticleSubRegionBase const & subRegion )
{
// Register a dummy group for each subregion
Group & subReg = materialData.registerGroup( subRegion.getName() );
subReg.resize( subRegion.size() );
// Collect a list of plotted constitutive fields and create wrappers containing averaged data
subRegion.getConstitutiveModels().forSubGroups( [&]( Group const & material )
{
material.forWrappers( [&]( WrapperBase const & wrapper )
{
string const fieldName = constitutive::ConstitutiveBase::makeFieldName( material.getName(), wrapper.getName() );
if( outputUtilities::isFieldPlotEnabled( wrapper.getPlotLevel(), m_plotLevel, fieldName, m_fieldNames, m_onlyPlotSpecifiedFieldNames ) )
{
subReg.registerWrapper( wrapper.averageOverSecondDim( fieldName, subReg ) );
materialFields.insert( fieldName );
}
} );
} );
} );
// Write averaged material data
for( string const & field : materialFields )
{
writeElementField( materialData, field, cellData );
}
// Collect a list of regular fields (filter out material field wrappers)
// TODO: this can be removed if we stop hanging constitutive wrappers on the mesh
std::unordered_set< string > regularFields;
region.forParticleSubRegions( [&]( ParticleSubRegionBase const & subRegion )
{
for( auto const & wrapperIter : subRegion.wrappers() )
{
if( isFieldPlotEnabled( *wrapperIter.second ) && materialFields.count( wrapperIter.first ) == 0 )
{
regularFields.insert( wrapperIter.first );
}
}
} );
// Write regular fields
for( string const & field : regularFields )
{
writeElementField( region.getGroup( ParticleRegionBase::viewKeyStruct::particleSubRegions() ), field, cellData );
}
}
void VTKPolyDataWriterInterface::writeNodeFields( NodeManager const & nodeManager,
arrayView1d< localIndex const > const & nodeIndices,
vtkPointData * pointData ) const
{
for( auto const & wrapperIter : nodeManager.wrappers() )
{
auto const & wrapper = *wrapperIter.second;
if( isFieldPlotEnabled( wrapper ) )
{
vtkSmartPointer< vtkDataArray > data;
types::dispatch( types::ListofTypeList< types::StandardArrays >{}, [&]( auto tupleOfTypes )
{
using ArrayType = camp::first< decltype( tupleOfTypes ) >;
using T = typename ArrayType::ValueType;
auto typedData = vtkAOSDataArrayTemplate< T >::New();
data.TakeReference( typedData );
setComponentMetadata( Wrapper< ArrayType >::cast( wrapper ), typedData );
}, wrapper );
data->SetNumberOfTuples( nodeIndices.size() );
data->SetName( wrapper.getName().c_str() );
writeField( wrapper, nodeIndices, 0, data.GetPointer() );
pointData->AddArray( data );
}
}
}
void VTKPolyDataWriterInterface::writeElementFields( ElementRegionBase const & region,
vtkCellData * cellData ) const
{
std::unordered_set< string > materialFields;
conduit::Node fakeRoot;