forked from fmihpc/vlsv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vlsv2silo.cpp
2190 lines (1957 loc) · 92.2 KB
/
vlsv2silo.cpp
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
/** This file is part of VLSV file format.
*
* Copyright 2011-2013 Finnish Meteorological Institute
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <cstdlib>
#include <iostream>
#include <stdint.h>
#include <cmath>
#include <list>
#include <silo.h>
#include <sstream>
#include <dirent.h>
#include <vector>
#include <map>
#include <unordered_map>
#include <iomanip>
#include <cstring>
#ifdef PROFILE
#include <profile.hpp>
int convertQuadMeshTotalID;
//int quadMeshID;
//int quadVariablesID;
//int quadMeshReadID;
#endif
#include "vlsv_reader.h"
using namespace std;
// When making option lists SILO seems to only store a pointer to
// variable giving the option's value. The pointers must be valid
// when data is written to file. Thus, we need to define some global
// variables here that store values put in option lists.
static int timestep = 0;
static float time_float = 0.0;
static double time_double = 0.0;
static string label_x = "x-coordinate"; /**< Default name for x-coordinate.*/
static string label_y = "y-coordinate"; /**< Default name for y-coordinate.*/
static string label_z = "z-coordinate"; /**< Default name for z-coordinate.*/
static string units_x = "m"; /**< Default unit for x-coordinate.*/
static string units_y = "m"; /**< Default unit for y-coordinate.*/
static string units_z = "m"; /**< Default unit for z-coordinate.*/
static float bbox[6]; // Simulation domain bounding box (x_min,y_min,z_min,dx,dy,dz) parameters
static int maxHash = 2097152-1; // =2^21, the (i,j,k) indices are packed into a 64-bit integer (3*21=63).
static DBfile* fileptr = NULL; // Pointer to file opened by SILO
static set<string> directories; /**< List of directories created to output SILO file. If one tries to
* create a directory more than once, SILO will throw errors to the
* console. Similarly attempting to cd into a non-existing directory
* throws errors to console. In order to avoid these errors, currently
* existing directories are stored in this set.*/
struct CurveData {
string xlabel;
string ylabel;
string xunit;
string yunit;
map<double,double> data;
CurveData();
};
CurveData::CurveData(): xlabel(""),ylabel(""),xunit(""),yunit("") { }
static map<string,CurveData> curves; /**< Container for all curve data stored to VLSV file(s).
* map<double,double> is for sorting data by ascending x values.*/
/** Convert an integer value written to a char array to int64_t. If the integer value
* in char array is uint64_t the conversion to int64_t may lead to unexpected results.
* @param ptr Pointer to char array containing an integer value.
* @param dataType Is the integer value signed or unsigned?
* @param dataSize Byte size of the stored integer value.
* @return Stored value converted to int64_t.*/
int64_t convInt(const char* ptr,const vlsv::datatype::type& dataType,const uint64_t& dataSize) {
switch (dataType) {
// Convert signed integer to int64_t:
case (vlsv::datatype::INT):
switch(dataSize) {
case (sizeof(int8_t)):
return *reinterpret_cast<const int8_t*>(ptr);
break;
case (sizeof(int16_t)):
return *reinterpret_cast<const int16_t*>(ptr);
break;
case (sizeof(int32_t)):
return *reinterpret_cast<const int32_t*>(ptr);
break;
case (sizeof(int64_t)):
return *reinterpret_cast<const int64_t*>(ptr);
break;
default:
cerr << "ERROR Unsupported signed integer datatype passed to convInt!" << endl;
exit(1);
break;
}
break;
// Convert unsigned integer to int64_t:
case (vlsv::datatype::UINT):
switch(dataSize) {
case (sizeof(uint8_t)):
return *reinterpret_cast<const uint8_t*>(ptr);
break;
case (sizeof(uint16_t)):
return *reinterpret_cast<const uint16_t*>(ptr);
break;
case (sizeof(uint32_t)):
return *reinterpret_cast<const uint32_t*>(ptr);
break;
case (sizeof(uint64_t)):
return *reinterpret_cast<const uint64_t*>(ptr);
break;
default:
cerr << "ERROR Unsupported unsigned integer datatype passed to convInt!" << endl;
exit(1);
break;
}
break;
// Unknown
default:
cerr << "ERROR Unsupported datatype passed to convInt!" << endl;
exit(1);
break;
}
}
/** Convert an integer value written to a char array to uint64_t. If the integer value
* in char array is signed, the conversion to uint64_t may lead to unexpected results.
* @param ptr Pointer to char array containing an integer value.
* @param dataType Is the integer value signed or unsigned?
* @param dataSize Byte size of the stored integer value.
* @return Stored value converted to uint64_t.*/
uint64_t convUInt(const char* ptr,const vlsv::datatype::type& dataType,const uint64_t& dataSize) {
switch (dataType) {
// Convert signed integer to uint64_t:
case (vlsv::datatype::INT):
switch (dataSize) {
case sizeof(int8_t):
return *reinterpret_cast<const int8_t*>(ptr);
break;
case sizeof(int16_t):
return *reinterpret_cast<const int16_t*>(ptr);
break;
case sizeof(int32_t):
return *reinterpret_cast<const int32_t*>(ptr);
break;
case sizeof(int64_t):
return *reinterpret_cast<const int64_t*>(ptr);
break;
default:
cerr << "ERROR Unsupported signed integer datatype passed to convUInt!" << endl;
exit(1);
break;
}
break;
// Convert unsigned integer to uint64_t:
case (vlsv::datatype::UINT):
switch (dataSize) {
case sizeof(uint8_t):
return *reinterpret_cast<const uint8_t*>(ptr);
break;
case sizeof(uint16_t):
return *reinterpret_cast<const uint16_t*>(ptr);
break;
case sizeof(uint32_t):
return *reinterpret_cast<const uint32_t*>(ptr);
break;
case sizeof(uint64_t):
return *reinterpret_cast<const uint64_t*>(ptr);
break;
default:
cerr << "ERROR Unsupported unsigned integer datatype passed to convUInt!" << endl;
exit(1);
break;
}
break;
// Unsupported datatype:
default:
cerr << "ERROR: Unsupported datatype passed to convUInt!" << endl;
exit(1);
break;
}
}
/** Get a SILO datatype corresponding to given VLSV datatype.
* @param dataType Datatype. Either signed or unsigned integer, or floating point value.
* @param dataSize Byte size of datatype.
* @return Corresponding SILO datatype or -1 if conversion was not possible.*/
int SiloType(const vlsv::datatype::type& dataType,const uint64_t& dataSize) {
switch (dataType) {
case vlsv::datatype::UNKNOWN:
return -1;
break;
case vlsv::datatype::INT:
if (dataSize == 2) return DB_SHORT;
else if (dataSize == 4) return DB_INT;
else if (dataSize == 8) return DB_LONG;
else return -1;
break;
case vlsv::datatype::UINT:
if (dataSize == 2) return DB_SHORT;
else if (dataSize == 4) return DB_INT;
else if (dataSize == 8) return DB_LONG;
else return -1;
break;
case vlsv::datatype::FLOAT:
if (dataSize == 4) return DB_FLOAT;
else if (dataSize == 8) return DB_DOUBLE;
else return -1;
break;
}
return -1;
}
const float EPS = 1.0e-6;
// ************************************************ //
// ***** FUNCTIONS RELATED TO MESH_QUAD_MULTI ***** //
// ************************************************ //
/** Struct for storing (i,j,k) indices of nodes in the mesh. This
* struct is, in practice, used to eliminate duplicate nodes from the
* mesh pieces written to SILO file.*/
struct NodeIndices {
int32_t i; /**< i-index of the node.*/
int32_t j; /**< j-index of the node.*/
int32_t k; /**< k-index of the node.*/
/** Constructor.
* @param i i-index of the node.
* @param j j-index of the node.
* @param k k-index of the node.*/
NodeIndices(int32_t i,int32_t j,int32_t k): i(i),j(j),k(k) { }
};
/** Comparator object for struct NodeIndices, required for being
* able to store NodeIndices to unordered_map.*/
struct NodesAreEqual {
/** Compare given NodeIndices objects for equality. Objects
* are equal if their (i,j,k) indices are equal.
* @param first First NodeIndices object to compare.
* @param second Second NodeIndices object to compare.
* @return If true, given objects are equal.*/
bool operator()(const NodeIndices& first,const NodeIndices& second) const {
if (first.i != second.i) return false;
if (first.j != second.j) return false;
if (first.k != second.k) return false;
return true;
}
};
/** Hash function implementation for object NodeIndices, required for
* being able to store NodeIndices to unordered_map.*/
struct NodeHash {
/** Calculate hash value for given NodeIndices object.
* @param Node NodeIndices object whose hash value is to be calculated.
* @return Calculated hash value.*/
uint64_t operator()(const NodeIndices& node) const {
uint64_t result = 0;
uint64_t tmp = node.i % maxHash;
result = (result | tmp);
tmp = node.j % maxHash;
result = (result | (tmp << 21));
tmp = node.k % maxHash;
result = (result | (tmp << 42));
return result;
}
};
template<typename T>
void insertNodeCrds(T i,T j,T k,vector<float>& xcrds,vector<float>& ycrds,vector<float>& zcrds) {
xcrds.push_back(bbox[0] + i*bbox[3]);
ycrds.push_back(bbox[1] + j*bbox[4]);
zcrds.push_back(bbox[2] + k*bbox[5]);
}
/** Iterate over all cells (local + ghosts) in the given multimesh piece, and eliminate
* duplicate nodes from the resulting node list. Additionally, unique (x,y,z) coordinate
* tuples are written to given vectors.
* @param amount Number of cells (local + ghosts) in the multimesh piece.
* @param vectorSize Size of data vector in VLSV file (should be three).
* @param ptrMesh Pointer to array containing (i,j,k) index tuples that were read from VLSV file.
* @param zoneList Vector in which the node list is written.
* @param xcrds Vector in which x-coordinates of unique nodes are written.
* @param xcrds Vector in which y-coordinates of unique nodes are written.
* @param xcrds Vector in which z-coordinates of unique nodes are written.*/
template<typename T>
void eliminateDuplicateNodes(uint64_t amount,uint64_t vectorSize,T* ptrMesh,vector<int>& zoneList,
vector<float>& xcrds,vector<float>& ycrds,vector<float>& zcrds) {
zoneList.clear();
xcrds.clear();
ycrds.clear();
zcrds.clear();
uint32_t counter = 0;
unordered_map<NodeIndices,int,NodeHash,NodesAreEqual> nodeIndices;
pair<unordered_map<NodeIndices,int,NodeHash,NodesAreEqual>::iterator,bool> result;
// Iterate over all cells and attempt to insert the eight nodes associated with
// it to unordered_map nodeIndices. If the insertion succeeds, the node and its coordinates
// is also inserted to vectors zoneList,xcrds,ycrds,and zcrds. In practice this eliminates
// duplicate nodes.
for (uint64_t cell=0; cell<amount; ++cell) {
result = nodeIndices.insert(make_pair(NodeIndices(ptrMesh[0]+0,ptrMesh[1]+1,ptrMesh[2]+0),counter));
if (result.second == true) {insertNodeCrds(ptrMesh[0]+0,ptrMesh[1]+1,ptrMesh[2]+0,xcrds,ycrds,zcrds); ++counter;}
zoneList.push_back(result.first->second);
result = nodeIndices.insert(make_pair(NodeIndices(ptrMesh[0]+0,ptrMesh[1]+0,ptrMesh[2]+0),counter));
if (result.second == true) {insertNodeCrds(ptrMesh[0]+0,ptrMesh[1]+0,ptrMesh[2]+0,xcrds,ycrds,zcrds); ++counter;}
zoneList.push_back(result.first->second);
result = nodeIndices.insert(make_pair(NodeIndices(ptrMesh[0]+1,ptrMesh[1]+0,ptrMesh[2]+0),counter));
if (result.second == true) {insertNodeCrds(ptrMesh[0]+1,ptrMesh[1]+0,ptrMesh[2]+0,xcrds,ycrds,zcrds); ++counter;}
zoneList.push_back(result.first->second);
result = nodeIndices.insert(make_pair(NodeIndices(ptrMesh[0]+1,ptrMesh[1]+1,ptrMesh[2]+0),counter));
if (result.second == true) {insertNodeCrds(ptrMesh[0]+1,ptrMesh[1]+1,ptrMesh[2]+0,xcrds,ycrds,zcrds); ++counter;}
zoneList.push_back(result.first->second);
result = nodeIndices.insert(make_pair(NodeIndices(ptrMesh[0]+0,ptrMesh[1]+1,ptrMesh[2]+1),counter));
if (result.second == true) {insertNodeCrds(ptrMesh[0]+0,ptrMesh[1]+1,ptrMesh[2]+1,xcrds,ycrds,zcrds); ++counter;}
zoneList.push_back(result.first->second);
result = nodeIndices.insert(make_pair(NodeIndices(ptrMesh[0]+0,ptrMesh[1]+0,ptrMesh[2]+1),counter));
if (result.second == true) {insertNodeCrds(ptrMesh[0]+0,ptrMesh[1]+0,ptrMesh[2]+1,xcrds,ycrds,zcrds); ++counter;}
zoneList.push_back(result.first->second);
result = nodeIndices.insert(make_pair(NodeIndices(ptrMesh[0]+1,ptrMesh[1]+0,ptrMesh[2]+1),counter));
if (result.second == true) {insertNodeCrds(ptrMesh[0]+1,ptrMesh[1]+0,ptrMesh[2]+1,xcrds,ycrds,zcrds); ++counter;}
zoneList.push_back(result.first->second);
result = nodeIndices.insert(make_pair(NodeIndices(ptrMesh[0]+1,ptrMesh[1]+1,ptrMesh[2]+1),counter));
if (result.second == true) {insertNodeCrds(ptrMesh[0]+1,ptrMesh[1]+1,ptrMesh[2]+1,xcrds,ycrds,zcrds); ++counter;}
zoneList.push_back(result.first->second);
ptrMesh += vectorSize;
}
}
// ****************************************** //
// ***** FUNCTIONS RELATED TO MESH_QUAD ***** //
// ****************************************** //
template<typename REAL> struct NodeCrd {
REAL x;
REAL y;
REAL z;
NodeCrd(const REAL& x,const REAL& y,const REAL& z): x(x),y(y),z(z) { }
NodeCrd(char* x0,char* y0,char* z0,
char* dx,char* dy,char* dz) {
// Calculate node coordinates:
x = *reinterpret_cast<REAL*>(x0) + *reinterpret_cast<REAL*>(dx);
y = *reinterpret_cast<REAL*>(y0) + *reinterpret_cast<REAL*>(dy);
z = *reinterpret_cast<REAL*>(z0) + *reinterpret_cast<REAL*>(dz);
// Flush very small coordinate values to zero:
if (fabs(x) < EPS) x = 0.0;
if (fabs(y) < EPS) y = 0.0;
if (fabs(z) < EPS) z = 0.0;
}
void xcopy(char* target,REAL scaling=1.0) const {
const REAL tmp = x*scaling;
const char* ptr = reinterpret_cast<const char*>(&tmp);
for (unsigned int i=0; i<sizeof(REAL); ++i) target[i] = ptr[i];
}
void ycopy(char* target,REAL scaling=1.0) const {
const REAL tmp = y*scaling;
const char* ptr = reinterpret_cast<const char*>(&tmp);
for (unsigned int i=0; i<sizeof(REAL); ++i) target[i] = ptr[i];
}
void zcopy(char* target,REAL scaling=1.0) const {
const REAL tmp = z*scaling;
const char* ptr = reinterpret_cast<const char*>(&tmp);
for (unsigned int i=0; i<sizeof(REAL); ++i) target[i] = ptr[i];
}
bool comp(const NodeCrd<REAL>& n) const {
REAL EPS1,EPS2,EPS;
EPS1 = 1.0e-6 * fabs(x);
EPS2 = 1.0e-6 * fabs(n.x);
if (x == 0.0) EPS1 = 1.0e-7;
if (n.x == 0.0) EPS2 = 1.0e-7;
EPS = max(EPS1,EPS2);
if (fabs(x - n.x) > EPS) return false;
EPS1 = 1.0e-6 * fabs(y);
EPS2 = 1.0e-6 * fabs(n.y);
if (y == 0.0) EPS1 = 1.0e-7;
if (n.y == 0.0) EPS2 = 1.0e-7;
EPS = max(EPS1,EPS2);
if (fabs(y - n.y) > EPS) return false;
EPS1 = 1.0e-6 * fabs(z);
EPS2 = 1.0e-6 * fabs(n.z);
if (z == 0.0) EPS1 = 1.0e-7;
if (n.z == 0.0) EPS2 = 1.0e-7;
EPS = max(EPS1,EPS2);
if (fabs(z - n.z) > EPS) return false;
return true;
}
};
struct NodeComp {
bool operator()(const NodeCrd<double>& a,const NodeCrd<double>& b) const {
if (a.comp(b) == true) return false;
double EPS = 0.5e-5 * (fabs(a.z) + fabs(b.z));
if (a.z > b.z + EPS) return false;
if (a.z < b.z - EPS) return true;
EPS = 0.5e-5 * (fabs(a.y) + fabs(b.y));
if (a.y > b.y + EPS) return false;
if (a.y < b.y - EPS) return true;
EPS = 0.5e-5 * (fabs(a.x) + fabs(b.x));
if (a.x > b.x + EPS) return false;
if (a.x < b.x - EPS) return true;
return false;
}
bool operator()(const NodeCrd<float>& a,const NodeCrd<float>& b) const {
if (a.comp(b) == true) return false;
float EPS = 0.5e-5 * (fabs(a.z) + fabs(b.z));
if (a.z > b.z + EPS) return false;
if (a.z < b.z - EPS) return true;
EPS = 0.5e-5 * (fabs(a.y) + fabs(b.y));
if (a.y > b.y + EPS) return false;
if (a.y < b.y - EPS) return true;
EPS = 0.5e-5 * (fabs(a.x) + fabs(b.x));
if (a.x > b.x + EPS) return false;
if (a.x < b.x - EPS) return true;
return false;
}
bool operator()(const NodeCrd<long double>& a,const NodeCrd<long double>& b) const {
if (a.comp(b) == true) return false;
float EPS = 0.5e-5 * (fabs(a.z) + fabs(b.z));
if (a.z > b.z + EPS) return false;
if (a.z < b.z - EPS) return true;
EPS = 0.5e-5 * (fabs(a.y) + fabs(b.y));
if (a.y > b.y + EPS) return false;
if (a.y < b.y - EPS) return true;
EPS = 0.5e-5 * (fabs(a.x) + fabs(b.x));
if (a.x > b.x + EPS) return false;
if (a.x < b.x - EPS) return true;
return false;
}
};
// ****************************************** //
// ***** MISCELLANEOUS HELPER FUNCTIONS ***** //
// ****************************************** //
/** Create a SILO option list. By default simulation time and time step are inserted to
* the returned option list, as well as memory for extra options to be added later.
* @param vlsvReader VLSV reader, used for reading input file.
* @param N_extra How many additional options are needed.
* @param insertTimes If true, simulation time and time step are inserted to the option list.
* @return Pointer to created option list or a NULL pointer.*/
DBoptlist* getOptionList(vlsv::Reader& vlsvReader,const int& N_extra=0,const bool& insertTimes=true) {
DBoptlist* optlist = NULL;
if (insertTimes == false) {
if (N_extra > 0) optlist = DBMakeOptlist(N_extra);
return optlist;
}
list<pair<string,string> > attribs;
uint64_t arraySize,vectorSize,dataSize;
vlsv::datatype::type dataType;
// Check if time value has been given in the file. If not, then return
// immediately with an empty list:
int N_options = N_extra;
set<string> parameterNames;
if (vlsvReader.getUniqueAttributeValues("PARAMETER","name",parameterNames) == false) {
if (N_options == 0) return NULL;
return DBMakeOptlist(N_options);
}
if (parameterNames.find("time") != parameterNames.end()) ++N_options;
if (parameterNames.find("timestep") != parameterNames.end()) ++N_options;
if (N_options == 0) return NULL;
optlist = DBMakeOptlist(N_options);
// Read time value from file:
if (parameterNames.find("time") != parameterNames.end()) {
attribs.push_back(make_pair("name","time"));
vlsvReader.getArrayInfo("PARAMETER",attribs,arraySize,vectorSize,dataType,dataSize);
char* valbuffer = new char[arraySize*vectorSize*dataSize];
vlsvReader.readArray("PARAMETER",attribs,0,arraySize,valbuffer);
// Write time to SILO file either as float or double,
// depending on the format given in the file:
if (dataSize == sizeof(float)) {
time_float = *reinterpret_cast<float*>(valbuffer);
DBAddOption(optlist,DBOPT_TIME,&time_float);
} else if (dataSize == sizeof(double)) {
time_double = *reinterpret_cast<double*>(valbuffer);
DBAddOption(optlist,DBOPT_DTIME,&time_double);
} else if (dataSize == sizeof(long double)) {
time_double = *reinterpret_cast<long double*>(valbuffer);
DBAddOption(optlist,DBOPT_DTIME,&time_double);
} else {
cerr << "TIME given in unknown datatype, aborting" << endl; exit(1);
}
delete [] valbuffer; valbuffer = NULL;
}
if (parameterNames.find("timestep") != parameterNames.end()) {
attribs.clear();
attribs.push_back(make_pair("name","timestep"));
vlsvReader.getArrayInfo("PARAMETER",attribs,arraySize,vectorSize,dataType,dataSize);
char* valbuffer = new char[arraySize*vectorSize*dataSize];
vlsvReader.readArray("PARAMETER",attribs,0,arraySize,valbuffer);
if (dataType == vlsv::datatype::INT) timestep = convInt(valbuffer,dataType,dataSize);
else if (dataType == vlsv::datatype::UINT) timestep = convUInt(valbuffer,dataType,dataSize);
else {
cerr << "timestep given in unsupported datatype!" << endl;
}
DBAddOption(optlist,DBOPT_CYCLE,×tep);
delete [] valbuffer; valbuffer = NULL;
}
return optlist;
}
/** Parse coordinate names and units from given XML tag attribute list, and
* add them to SILO option list. Note that the option list must have space for
* six options.
* @param optlist Option list where coordinate names and units are added.
* @parma attribsOut Map containing XML tag attributes.*/
void parseCoordinateNames(DBoptlist* optlist,map<string,string>& attribsOut) {
// Default values for coordinate names & units:
label_x = "x-coordinate";
label_y = "y-coordinate";
label_z = "z-coordinate";
units_x = "m";
units_y = "m";
units_z = "m";
// Coordinate names & units in XML tag overwrite the default ones:
if (attribsOut.find("xlabel") != attribsOut.end()) label_x = attribsOut["xlabel"];
if (attribsOut.find("ylabel") != attribsOut.end()) label_y = attribsOut["ylabel"];
if (attribsOut.find("zlabel") != attribsOut.end()) label_z = attribsOut["zlabel"];
if (attribsOut.find("xunit") != attribsOut.end()) units_x = attribsOut["xunit"];
if (attribsOut.find("yunit") != attribsOut.end()) units_y = attribsOut["yunit"];
if (attribsOut.find("zunit") != attribsOut.end()) units_z = attribsOut["zunit"];
// Add coordinate names & units to option list:
DBAddOption(optlist,DBOPT_XLABEL,const_cast<char*>(label_x.c_str()));
DBAddOption(optlist,DBOPT_YLABEL,const_cast<char*>(label_y.c_str()));
DBAddOption(optlist,DBOPT_ZLABEL,const_cast<char*>(label_z.c_str()));
DBAddOption(optlist,DBOPT_XUNITS,const_cast<char*>(units_x.c_str()));
DBAddOption(optlist,DBOPT_YUNITS,const_cast<char*>(units_y.c_str()));
DBAddOption(optlist,DBOPT_ZUNITS,const_cast<char*>(units_z.c_str()));
}
/** Create a directory to output SILO file for the given variable.
* @param vlsvReader VLSV reader used to read input file.
* @param meshName Name of the mesh, same as the name of resulting multimesh.
* @param varName Name of the variable.
* @param outputDir Variable in which the name of the output directory is copied.*/
void createVariableDirectory(vlsv::Reader& vlsvReader,const string& meshName,const string& varName,string& outputDir) {
// By default variables are written to root directory:
outputDir = "/";
// Search for XML attribute "dir" for the given variable. If it is defined,
// create a subdirectory with a same name as the attribute value. Otherwise exit:
list<pair<string,string> > attributes;
attributes.push_back(make_pair("mesh",meshName));
attributes.push_back(make_pair("name",varName));
map<string,string> arrayAttributes;
if (vlsvReader.getArrayAttributes("VARIABLE",attributes,arrayAttributes) == false) return;
map<string,string>::const_iterator it = arrayAttributes.find("dir");
if (it == arrayAttributes.end()) return;
const string& dir = it->second;
set<string>::const_iterator dirExists = directories.find(dir);
if (dirExists == directories.end()) {
string tmp;
string s = dir;
string current = "";
size_t pos = s.find('/');
while (pos != string::npos) {
tmp = s.substr(0,pos);
if (pos != 0) current = current + '/' + tmp;
// This exception will make this work correctly if the
// first character in directory name is '/':
if (tmp.size() == 0) {
s = s.substr(pos+1);
pos = s.find('/');
continue;
}
// If current directory does not exist, insert it:
if (directories.find(current) == directories.end()) {
directories.insert(current);
DBMkDir(fileptr,const_cast<char*>(current.c_str()));
}
s = s.substr(pos+1);
pos = s.find('/');
}
tmp = s.substr(0,pos);
if (tmp.size() > 0) current = current + '/' + tmp;
// If directory name was given without a trailing '/', e.g. "/dir1/dir2",
// this if inserts the final directory:
if (tmp.size() > 0) {
if (directories.find(current) == directories.end()) {
directories.insert(current);
DBMkDir(fileptr,const_cast<char*>(current.c_str()));
}
}
outputDir = current;
} else {
// Variable directory already exists, just copy its name:
outputDir = *dirExists;
}
}
/** Write a multimesh variable from VLSV file to output SILO file.
* @param vlsvReader VLSV reader used to read the input file.
* @param meshName Name of the mesh, not mesh piece. Multimesh consists of one or more mesh pieces
* each having a unique name.
* @param varName Name of the variable.
* @param meshDir Directory in the SILO file where the variable data is written.
* @param meshNumber Which mesh piece variable data is to be converted.
* @param variableOffsets Array containing offsets to variable data in VLSV file for each mesh piece.
* @param N_cells Total number of cells in given mesh piece (local + ghosts).
* @param N_ghosts Number of ghost cells in given mesh piece.
* @param ghostLocalIDs For each ghost cell, index to variable data in mesh piece containing the data.
* @param ghostDomains For each ghost cell, number of mesh piece containing the data.
* @param fullName Variable in which the full name of the converted multimesh variable is copied (does not include filename).
* @return If true, variable was converted successfully.*/
bool convertMultimeshVariable(vlsv::Reader& vlsvReader,const string& meshName,const string& varName,const string& meshDir,
int meshNumber,unsigned int* variableOffsets,uint64_t N_cells,uint64_t N_ghosts,
unsigned int* ghostLocalIDs,unsigned int* ghostDomains,string& fullName) {
bool success = true;
fullName = "";
// Writing a unstructured grid variable is a rather straightforward process. The
// only complication here is that some of the variables are actually vectors, i.e.
// vectorSize > 1 (vectorSize == 1 for scalars). Format in which vectors are stored in VLSV
// differ from format in which they are written to SILO files.
vlsv::datatype::type dataType;
uint64_t arraySize,vectorSize,dataSize;
list<pair<string,string> > attributes;
attributes.push_back(make_pair("mesh",meshName));
attributes.push_back(make_pair("name",varName));
if (vlsvReader.getArrayInfo("VARIABLE",attributes,arraySize,vectorSize,dataType,dataSize) == false) {
// This will exit if this variable does not belong to given mesh
return false;
}
// Check that variable is a scalar or 3D vector:
if (vectorSize != 1 && vectorSize != 3) return false;
// Read variable data. We do not actually need to care if
// the data is given as floats, doubles, or long doubles. We
// just need to tell SILO what kind of data the buffer contains.
// Here we read all data local to this domain (N_cells-N_ghosts cells):
char* buffer = new char[arraySize*vectorSize*dataSize];
if (vlsvReader.readArray("VARIABLE",attributes,0,arraySize,buffer) == false) {
success = false;
delete [] buffer; buffer = NULL;
return success;
}
// Vector variables need to be copied to temporary arrays before
// writing to SILO file:
char** components = new char*[vectorSize];
for (uint64_t i=0; i<vectorSize; ++i) components[i] = new char[N_cells*dataSize];
// Copy vector variables from local cells:
for (uint64_t block=0; block<N_cells-N_ghosts; ++block) {
const uint64_t compOffset = block*dataSize;
const uint64_t localOffset = (variableOffsets[meshNumber] + block)*vectorSize*dataSize;
for (uint64_t j=0; j<vectorSize; ++j) {
const uint64_t bufferOffset = localOffset + j*dataSize;
for (uint64_t i=0; i<dataSize; ++i) {
components[j][compOffset+i] = buffer[bufferOffset + i];
}
}
}
// Copy vector variables from ghost cells:
const uint64_t ghostOffset = N_cells-N_ghosts;
for (uint64_t block=0; block<N_ghosts; ++block) {
// Offset to components[j] where ghost cell value is stored:
const uint64_t compOffset = (ghostOffset+block)*dataSize;
// Offset to neighbour domain cell where ghost cell value is read:
const uint64_t nbrOffset = (variableOffsets[ghostDomains[block]] + ghostLocalIDs[block])*vectorSize*dataSize;
// Copy data:
for (uint64_t j=0; j<vectorSize; ++j) {
const uint64_t bufferOffset = nbrOffset + j*dataSize;
for (uint64_t i=0; i<dataSize; ++i) {
components[j][compOffset+i] = buffer[bufferOffset + i];
}
}
}
delete [] buffer; buffer = NULL;
// SILO requires one variable name per (vector) component, but we only have one.
// That is, for electric field SILO would like to get "Ex","Ey", and "Ez", but we
// only have "E" in VLSV file. Use the VLSV variable name for all components:
vector<string> varNames(vectorSize);
vector<char*> varNamePtrs(vectorSize);
for (uint64_t i=0; i<vectorSize; ++i) {
stringstream ss;
ss << varName << (i+1);
varNames[i] = ss.str();
varNamePtrs[i] = const_cast<char*>(varNames[i].c_str());
}
// Create a subdirectory to SILO file if array tag contains attribute "dir":
map<string,string> arrayAttributes;
const string rootDir = "/" + meshDir;
fullName = rootDir + '/';
if (vlsvReader.getArrayAttributes("VARIABLE",attributes,arrayAttributes) == true) {
map<string,string>::const_iterator it = arrayAttributes.find("dir");
if (it != arrayAttributes.end()) {
const string& dir = it->second;
// If dir is not yet in SILO file, create it. The directories
// need to be created one level at a time:
if (directories.find(dir) == directories.end()) {
string tmp;
string s = dir;
string current = '/' + meshDir;
size_t pos = s.find('/');
while (pos != string::npos) {
tmp = s.substr(0,pos);
if (pos != 0) {
current = current + '/' + tmp;
}
// This exception will make this work correctly if the
// first character in directory name is '/':
if (tmp.size() == 0) {
s = s.substr(pos+1);
pos = s.find('/');
continue;
}
// If current directory does not exist, insert it:
if (directories.find(current) == directories.end()) {
directories.insert(current);
if (DBMkDir(fileptr,const_cast<char*>(current.c_str())) < 0) {
cerr << "ERROR failed to create dir '" << current << "'" << endl;
}
}
s = s.substr(pos+1);
pos = s.find('/');
}
tmp = s.substr(0,pos);
if (tmp.size() > 0) current = current + '/' + tmp;
// If directory name was given without a trailing '/', e.g. "/dir1/dir2",
// this if-statement inserts the final directory:
if (tmp.size() > 0) {
if (directories.find(current) == directories.end()) {
directories.insert(current);
if (DBMkDir(fileptr,const_cast<char*>(current.c_str())) < 0) {
cerr << "ERROR failed to create dir '" << current << "'" << endl;
}
}
}
}
// cd into dir:
const string dirName = rootDir + dir;
if (DBSetDir(fileptr,const_cast<char*>(dirName.c_str())) < 0) {
cerr << "ERROR failed to cd into dir '" << dirName << "'" << endl;
}
fullName = dirName + '/';
}
}
fullName += varName;
// Make an option list. If physical units of the quantity were given
// in tag attributes, write units to SILO:
unsigned int N_options = 0;
if (arrayAttributes.find("unit") != arrayAttributes.end()) ++N_options;
DBoptlist* optlist = getOptionList(vlsvReader,N_options);
if (arrayAttributes.find("unit") != arrayAttributes.end()) {
DBAddOption(optlist,DBOPT_UNITS,const_cast<char*>(arrayAttributes["unit"].c_str()));
}
// Write the unstructured mesh variable to SILO:
const string fullMeshName = '/' + meshDir + '/' + meshDir;
if (DBPutUcdvar(fileptr,varName.c_str(),fullMeshName.c_str(),vectorSize,&(varNamePtrs[0]),components,N_cells,NULL,0,
SiloType(dataType,dataSize),DB_ZONECENT,optlist) < 0) success = false;
if (optlist != NULL) DBFreeOptlist(optlist);
// Deallocate memory:
for (uint64_t i=0; i<vectorSize; ++i) {delete [] components[i]; components[i] = NULL;}
delete [] components; components = NULL;
// cd back into root dir:
if (DBSetDir(fileptr,const_cast<char*>(rootDir.c_str())) < 0) {
cerr << "Failed to return to root dir in SILO!" << endl;
success = false;
}
return success;
}
bool convertMeshVariable(vlsv::Reader& vlsvReader,const string& meshName,const string& varName) {
bool success = true;
// Writing a unstructured grid variable is a rather straightforward process. The
// only compilation here is that some of the variables are actually vectors, i.e.
// vectorSize > 1 (vectorSize == 1 for scalars). Format in which vectors are stored in VLSV
// differ from format in which they are written to SILO files.
vlsv::datatype::type dataType;
uint64_t arraySize,vectorSize,dataSize;
list<pair<string,string> > attributes;
attributes.push_back(make_pair("mesh",meshName));
attributes.push_back(make_pair("name",varName));
if (vlsvReader.getArrayInfo("VARIABLE",attributes,arraySize,vectorSize,dataType,dataSize) == false) {
return false;
}
// Read variable data. We do not actually need to care if
// the data is given as floats, doubles, or long doubles. We
// just need to tell SILO what kind of data the buffer contains:
char* buffer = new char[arraySize*vectorSize*dataSize];
if (vlsvReader.readArray("VARIABLE",attributes,0,arraySize,buffer) == false) success = false;
if (success == false) {
delete [] buffer;
return success;
}
// Vector variables need to be copied to temporary arrays before
// writing to SILO file:
char** components = new char*[vectorSize];
for (uint64_t i=0; i<vectorSize; ++i) {
components[i] = new char[arraySize*dataSize];
for (uint64_t j=0; j<arraySize; ++j) for (uint64_t k=0; k<dataSize; ++k)
components[i][j*dataSize+k] = buffer[j*vectorSize*dataSize + i*dataSize + k];
}
// SILO requires one variable name per (vector) component, but we only have one.
// That is, for electric field SILO would like to get "Ex","Ey", and "Ez", but we
// only have "E" in VLSV file. Use the VLSV variable name for all components.
vector<string> varNames(vectorSize);
vector<char*> varNamePtrs(vectorSize);
for (uint64_t i=0; i<vectorSize; ++i) {
stringstream ss;
ss << varName << (i+1);
varNames[i] = ss.str();
varNamePtrs[i] = const_cast<char*>(varNames[i].c_str());
}
// Create a subdirectory to SILO file if array tag contains attribute "dir":
map<string,string> arrayAttributes;
const string rootDir = "/";
if (vlsvReader.getArrayAttributes("VARIABLE",attributes,arrayAttributes) == true) {
map<string,string>::const_iterator it = arrayAttributes.find("dir");
if (it != arrayAttributes.end()) {
const string& dir = it->second;
// If dir is not yet in SILO file, create it. The directories
// need to be created one level at a time:
if (directories.find(dir) == directories.end()) {
string tmp;
string s = dir;
string current = "";
size_t pos = s.find('/');
while (pos != string::npos) {
tmp = s.substr(0,pos);
if (pos != 0) current = current + '/' + tmp;
// This exception will make this work correctly if the
// first character in directory name is '/':
if (tmp.size() == 0) {
s = s.substr(pos+1);
pos = s.find('/');
continue;
}
// If current directory does not exist, insert it:
if (directories.find(current) == directories.end()) {
directories.insert(current);
DBMkDir(fileptr,const_cast<char*>(current.c_str()));
}
s = s.substr(pos+1);
pos = s.find('/');
}
tmp = s.substr(0,pos);
if (tmp.size() > 0) current = current + '/' + tmp;
// If directory name was given without a trailing '/', e.g. "/dir1/dir2",
// this if inserts the final directory:
if (tmp.size() > 0) {
if (directories.find(current) == directories.end()) {
directories.insert(current);
DBMkDir(fileptr,const_cast<char*>(current.c_str()));
}
}
}
// cd into dir:
DBSetDir(fileptr,const_cast<char*>(dir.c_str()));
}
}
// Make an option list. If physical units of the quantity were given
// in tag attributes, write units to SILO:
unsigned int N_options = 0;
if (arrayAttributes.find("unit") != arrayAttributes.end()) ++N_options;
DBoptlist* optlist = getOptionList(vlsvReader,N_options);
if (arrayAttributes.find("unit") != arrayAttributes.end()) {
DBAddOption(optlist,DBOPT_UNITS,const_cast<char*>(arrayAttributes["unit"].c_str()));
}
// Mesh name must have full path name so that VisIt will find them:
const string mesh = "/" + meshName;
// Write the unstructured mesh variable to SILO:
if (DBPutUcdvar(fileptr,varName.c_str(),mesh.c_str(),vectorSize,&(varNamePtrs[0]),components,arraySize,NULL,0,
SiloType(dataType,dataSize),DB_ZONECENT,optlist) < 0) success = false;
if (optlist != NULL) DBFreeOptlist(optlist);
for (uint64_t i=0; i<vectorSize; ++i) {delete [] components[i]; components[i] = NULL;}
delete [] components; components = NULL;
delete [] buffer; buffer = NULL;
// cd back into root dir:
if (DBSetDir(fileptr,const_cast<char*>(rootDir.c_str())) < 0) {
cerr << "Failed to return to root dir in SILO!" << endl;
success = false;
}
return success;
}
bool convertPointMesh(vlsv::Reader& vlsvReader,const string& meshName) {
bool success = true;
//cerr << "Converting point mesh '" << meshName << "'" << endl;
// Fetch mesh coordinate array info and do sanity check on values:
list<pair<string,string> > attributes;
attributes.push_back(make_pair("name",meshName));
uint64_t arraySize,vectorSize,dataSize;
vlsv::datatype::type dataType;
if (vlsvReader.getArrayInfo("MESH",attributes,arraySize,vectorSize,dataType,dataSize) == false) {
cerr << "Array MESH info could not be obtained!" << endl;
return false;
}
if (dataType != vlsv::datatype::FLOAT) {
cerr << "Mesh coordinates are not floating point values!" << endl;
return false; // Coordinates must be floating point values
}
if (dataSize != sizeof(float) && (dataSize != sizeof(double) && dataSize != sizeof(long double))) {
cerr << "Mesh coordinates have unsupported floating point byte size!" << endl;
cerr << "\t byte size obtained: " << dataSize << endl;
return false;
}
if (vectorSize < 1 || vectorSize > 3) {
cerr << "Mesh dimensionality must be between 1 and 3!" << endl;
return false;
}
if (arraySize == 0 || vectorSize == 0 || dataSize == 0) return true;
// Read array XML attributes:
map<string,string> attribsOut;
if (vlsvReader.getArrayAttributes("MESH",attributes,attribsOut) == false) {
cerr << "\t\tERROR: Failed to obtain XML tags of MESH array!" << endl;
}
// If XML tag has attribute 'meshinfo', read mesh information from that mesh instead of this point mesh:
if (attribsOut.find("meshinfo") != attribsOut.end()) {
list<pair<string,string> > tmp;
const string meshInfoName = attribsOut["meshinfo"];