-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathHDFCFUtil.cc
More file actions
4077 lines (3337 loc) · 164 KB
/
HDFCFUtil.cc
File metadata and controls
4077 lines (3337 loc) · 164 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
#include "config.h"
#include "config_hdf.h"
#include "HDFCFUtil.h"
#include <BESDebug.h>
#include <BESLog.h>
#include <math.h>
#include"dodsutil.h"
#include"HDFSPArray_RealField.h"
#include"HDFSPArrayMissField.h"
#include"HDFEOS2GeoCFProj.h"
#include"HDFEOS2GeoCF1D.h"
#include <libdap/debug.h>
#define SIGNED_BYTE_TO_INT32 1
// HDF datatype headers for both the default and the CF options
#include "HDFByte.h"
#include "HDFInt16.h"
#include "HDFUInt16.h"
#include "HDFInt32.h"
#include "HDFUInt32.h"
#include "HDFFloat32.h"
#include "HDFFloat64.h"
#include "HDFStr.h"
#include "HDF4RequestHandler.h"
//
using namespace std;
using namespace libdap;
#define ERR_LOC1(x) #x
#define ERR_LOC2(x) ERR_LOC1(x)
#define ERR_LOC __FILE__ " : " ERR_LOC2(__LINE__)
// Check the BES key.
// This function will check a BES key specified at the file h4.conf.in.
// If the key's value is either true or yes. The handler claims to find
// a key and will do some operations. Otherwise, will do different operations.
// For example, One may find a line H4.EnableCF=true at h4.conf.in.
// That means, the HDF4 handler will handle the HDF4 files by following CF conventions.
#if 0
bool
HDFCFUtil::check_beskeys(const string& key) {
bool found = false;
string doset ="";
const string dosettrue ="true";
const string dosetyes = "yes";
TheBESKeys::TheKeys()->get_value( key, doset, found ) ;
if( true == found ) {
doset = BESUtil::lowercase( doset ) ;
if( dosettrue == doset || dosetyes == doset )
return true;
}
return false;
}
#endif
/**
* Copied from stack overflow because valgrind finds the code
* below (Split) overruns memory, generating errors. jhrg 6/22/15
*/
static void
split_helper(vector<string> &tokens, const string &text, const char sep)
{
string::size_type start = 0, end = 0;
while ((end = text.find(sep, start)) != string::npos) {
tokens.push_back(text.substr(start, end - start));
start = end + 1;
}
tokens.push_back(text.substr(start));
}
// From a string separated by a separator to a list of string,
// for example, split "ab,c" to {"ab","c"}
void
HDFCFUtil::Split(const char *s, int len, char sep, std::vector<std::string> &names)
{
names.clear();
split_helper(names, string(s, len), sep);
#if 0
// Replaced with the above since valgrind reports errors
// with this code. jhrg 6/22/15
for (int i = 0, j = 0; j <= len; ++j) {
if ((j == len && len) || s[j] == sep) {
string elem(s + i, j - i);
names.push_back(elem);
i = j + 1;
continue;
}
}
#endif
}
// Assume sz is Null terminated string.
void
HDFCFUtil::Split(const char *sz, char sep, std::vector<std::string> &names)
{
names.clear();
// Split() was showing up in some valgrind runs as having an off-by-one
// error. I added this help track it down.
DBG(std::cerr << "HDFCFUtil::Split: sz: <" << sz << ">, sep: <" << sep << ">" << std::endl);
split_helper(names, string(sz), sep);
#if 0
// Replaced with a direct call to the new helper code.
// jhrg 6/22/15
Split(sz, (int)strlen(sz), sep, names);
#endif
}
#if 0
// From a string separated by a separator to a list of string,
// for example, split "ab,c" to {"ab","c"}
void
HDFCFUtil::Split(const char *s, int len, char sep, std::vector<std::string> &names)
{
names.clear();
for (int i = 0, j = 0; j <= len; ++j) {
if ((j == len && len) || s[j] == sep) {
string elem(s + i, j - i);
names.push_back(elem);
i = j + 1;
continue;
}
}
}
// Assume sz is Null terminated string.
void
HDFCFUtil::Split(const char *sz, char sep, std::vector<std::string> &names)
{
Split(sz, (int)strlen(sz), sep, names);
}
#endif
// This is a safer way to insert and update a c++ map value.
// Otherwise, the local testsuite at The HDF Group will fail for HDF-EOS2 data
// under iMac machine platform.
// The implementation replaces the element even if the key exists.
// This function is equivalent to map[key]=value
bool
HDFCFUtil::insert_map(std::map<std::string,std::string>& m, string key, string val)
{
pair<map<string,string>::iterator, bool> ret;
ret = m.insert(make_pair(key, val));
if(ret.second == false){
m.erase(key);
ret = m.insert(make_pair(key, val));
if(ret.second == false){
BESDEBUG("h4","insert_map():insertion failed on Key=" << key << " Val=" << val << endl);
}
}
return ret.second;
}
// Obtain CF string
string
HDFCFUtil::get_CF_string(string s)
{
if(""==s)
return s;
string insertString(1,'_');
// Always start with _ if the first character is not a letter
if (true == isdigit(s[0]))
s.insert(0,insertString);
// New name conventions drop the first '/' from the path.
if ('/' ==s[0])
s.erase(0,1);
for(unsigned int i=0; i < s.length(); i++)
if((false == isalnum(s[i])) && (s[i]!='_'))
s[i]='_';
return s;
}
// Obtain the unique name for the clashed names and save it to set namelist.
// This is a recursive call. A unique name list is represented as a set.
// If we find that a name already exists in the nameset, we will add a number
// at the end of the name to form a new name. If the new name still exists
// in the nameset, we will increase the index number and check again until
// a unique name is generated.
void
HDFCFUtil::gen_unique_name(string &str,set<string>& namelist, int&clash_index) {
pair<set<string>::iterator,bool> ret;
string newstr = "";
stringstream sclash_index;
sclash_index << clash_index;
newstr = str + sclash_index.str();
ret = namelist.insert(newstr);
if (false == ret.second) {
clash_index++;
gen_unique_name(str,namelist,clash_index);
}
else
str = newstr;
}
// General routine to handle the name clashing
// The input parameters include:
// name vector -> newobjnamelist(The name vector is changed to a unique name list
// a pre-allocated object name set ->objnameset(can be used to determine if a name exists)
void
HDFCFUtil::Handle_NameClashing(vector<string>&newobjnamelist,set<string>&objnameset) {
pair<set<string>::iterator,bool> setret;
set<string>::iterator iss;
vector<string> clashnamelist;
vector<string>::iterator ivs;
// clash index to original index mapping
map<int,int> cl_to_ol;
int ol_index = 0;
int cl_index = 0;
vector<string>::const_iterator irv;
for (irv = newobjnamelist.begin(); irv != newobjnamelist.end(); ++irv) {
setret = objnameset.insert(*irv);
if (false == setret.second ) {
clashnamelist.insert(clashnamelist.end(),(*irv));
cl_to_ol[cl_index] = ol_index;
cl_index++;
}
ol_index++;
}
// Now change the clashed elements to unique elements,
// Generate the set which has the same size as the original vector.
for (ivs=clashnamelist.begin(); ivs!=clashnamelist.end(); ivs++) {
int clash_index = 1;
string temp_clashname = *ivs +'_';
HDFCFUtil::gen_unique_name(temp_clashname,objnameset,clash_index);
*ivs = temp_clashname;
}
// Now go back to the original vector, make it unique.
for (unsigned int i =0; i <clashnamelist.size(); i++)
newobjnamelist[cl_to_ol[i]] = clashnamelist[i];
}
// General routine to handle the name clashing
// The input parameter just includes:
// name vector -> newobjnamelist(The name vector is changed to a unique name list
void
HDFCFUtil::Handle_NameClashing(vector<string>&newobjnamelist) {
set<string> objnameset;
Handle_NameClashing(newobjnamelist,objnameset);
}
// Borrowed codes from ncdas.cc in netcdf_handle4 module.
string
HDFCFUtil::print_attr(int32 type, int loc, void *vals)
{
ostringstream rep;
union {
char *cp;
unsigned char *ucp;
short *sp;
unsigned short *usp;
int32 /*nclong*/ *lp;
unsigned int *ui;
float *fp;
double *dp;
} gp;
switch (type) {
// Mapping both DFNT_UINT8 and DFNT_INT8 to unsigned char
// may cause overflow. Documented at jira ticket HFRHANDLER-169.
case DFNT_UINT8:
{
unsigned char uc;
gp.ucp = (unsigned char *) vals;
uc = *(gp.ucp+loc);
rep << (int)uc;
return rep.str();
}
case DFNT_INT8:
{
char c;
gp.cp = (char *) vals;
c = *(gp.cp+loc);
rep << (int)c;
return rep.str();
}
case DFNT_UCHAR:
case DFNT_CHAR:
{
// Use the customized escattr function. Don't escape \n,\t and \r. KY 2013-10-14
return escattr(static_cast<const char*>(vals));
}
case DFNT_INT16:
{
gp.sp = (short *) vals;
rep << *(gp.sp+loc);
return rep.str();
}
case DFNT_UINT16:
{
gp.usp = (unsigned short *) vals;
rep << *(gp.usp+loc);
return rep.str();
}
case DFNT_INT32:
{
gp.lp = (int32 *) vals;
rep << *(gp.lp+loc);
return rep.str();
}
case DFNT_UINT32:
{
gp.ui = (unsigned int *) vals;
rep << *(gp.ui+loc);
return rep.str();
}
case DFNT_FLOAT:
{
float attr_val = *(float*)vals;
bool is_a_fin = isfinite(attr_val);
gp.fp = (float *) vals;
rep << showpoint;
// setprecision seeme to cause the one-bit error when
// converting from float to string. Watch whether this
// is an isue.
rep << setprecision(10);
rep << *(gp.fp+loc);
string tmp_rep_str = rep.str();
if (tmp_rep_str.find('.') == string::npos
&& tmp_rep_str.find('e') == string::npos
&& tmp_rep_str.find('E') == string::npos) {
if(true == is_a_fin)
rep << ".";
}
return rep.str();
}
case DFNT_DOUBLE:
{
double attr_val = *(double*)vals;
bool is_a_fin = isfinite(attr_val);
gp.dp = (double *) vals;
rep << std::showpoint;
rep << std::setprecision(17);
rep << *(gp.dp+loc);
string tmp_rep_str = rep.str();
if (tmp_rep_str.find('.') == string::npos
&& tmp_rep_str.find('e') == string::npos
&& tmp_rep_str.find('E') == string::npos) {
if(true == is_a_fin)
rep << ".";
}
return rep.str();
}
default:
return string("UNKNOWN");
}
}
// Print datatype in string. This is used to generate DAS.
string
HDFCFUtil::print_type(int32 type)
{
// I expanded the list based on libdap/AttrTable.h.
static const char UNKNOWN[]="Unknown";
static const char BYTE[]="Byte";
static const char INT16[]="Int16";
static const char UINT16[]="UInt16";
static const char INT32[]="Int32";
static const char UINT32[]="UInt32";
static const char FLOAT32[]="Float32";
static const char FLOAT64[]="Float64";
static const char STRING[]="String";
// I got different cases from hntdefs.h.
switch (type) {
case DFNT_CHAR:
return STRING;
case DFNT_UCHAR8:
return STRING;
case DFNT_UINT8:
return BYTE;
case DFNT_INT8:
// ADD the macro
{
#ifndef SIGNED_BYTE_TO_INT32
return BYTE;
#else
return INT32;
#endif
}
case DFNT_UINT16:
return UINT16;
case DFNT_INT16:
return INT16;
case DFNT_INT32:
return INT32;
case DFNT_UINT32:
return UINT32;
case DFNT_FLOAT:
return FLOAT32;
case DFNT_DOUBLE:
return FLOAT64;
default:
return UNKNOWN;
}
}
// Obtain HDF4 datatype size.
short
HDFCFUtil::obtain_type_size(int32 type)
{
// .
switch (type) {
case DFNT_CHAR:
return sizeof(char);
case DFNT_UCHAR8:
return sizeof(unsigned char);
case DFNT_UINT8:
return sizeof(unsigned char);
case DFNT_INT8:
// ADD the macro
{
#ifndef SIGNED_BYTE_TO_INT32
return sizeof(char);
#else
return sizeof(int);
#endif
}
case DFNT_UINT16:
return sizeof(unsigned short);
case DFNT_INT16:
return sizeof(short);
case DFNT_INT32:
return sizeof(int);
case DFNT_UINT32:
return sizeof(unsigned int);
case DFNT_FLOAT:
return sizeof(float);
case DFNT_DOUBLE:
return sizeof(double);
default:
return -1;
}
}
// Subset of latitude and longitude to follow the parameters from the DAP expression constraint
// Somehow this function doesn't work. Now it is not used. Still keep it here for the future investigation.
template < typename T >
void HDFCFUtil::LatLon2DSubset (T * outlatlon,
int majordim,
int minordim,
T * latlon,
int32 * offset,
int32 * count,
int32 * step)
{
// float64 templatlon[majordim][minordim];
#if 0
// --std=c++11 on OSX causes 'typeof' to fail. This is a GNU gcc-specific
// keyword. jhrg 3/28/19
T (*templatlonptr)[majordim][minordim] = (typeof templatlonptr) latlon;
#endif
T (*templatlonptr)[majordim][minordim] = (T *) latlon;
int i, j, k;
// do subsetting
// Find the correct index
int dim0count = count[0];
int dim1count = count[1];
int dim0index[dim0count], dim1index[dim1count];
for (i = 0; i < count[0]; i++) // count[0] is the least changing dimension
dim0index[i] = offset[0] + i * step[0];
for (j = 0; j < count[1]; j++)
dim1index[j] = offset[1] + j * step[1];
// Now assign the subsetting data
k = 0;
for (i = 0; i < count[0]; i++) {
for (j = 0; j < count[1]; j++) {
outlatlon[k] = (*templatlonptr)[dim0index[i]][dim1index[j]];
k++;
}
}
}
// CF requires the _FillValue attribute datatype is the same as the corresponding field datatype.
// For some NASA files, this is not true.
// So we need to check if the _FillValue's datatype is the same as the attribute's.
// If not, we need to correct them.
void HDFCFUtil::correct_fvalue_type(AttrTable *at,int32 dtype) {
AttrTable::Attr_iter it = at->attr_begin();
bool find_fvalue = false;
while (it!=at->attr_end() && false==find_fvalue) {
if (at->get_name(it) =="_FillValue")
{
find_fvalue = true;
string fillvalue ="";
string fillvalue_type ="";
if((*at->get_attr_vector(it)).size() !=1)
throw InternalErr(__FILE__,__LINE__,"The number of _FillValue must be 1.");
fillvalue = (*at->get_attr_vector(it)->begin());
fillvalue_type = at->get_type(it);
string var_type = HDFCFUtil::print_type(dtype);
if(fillvalue_type != var_type){
at->del_attr("_FillValue");
if (fillvalue_type == "String") {
// String fillvalue is always represented as /+octal numbers when its type is forced to
// change to string(check HFRHANDLER-223). So we have to retrieve it back.
if(fillvalue.size() >1) {
long int fillvalue_int = 0;
vector<char> fillvalue_temp(fillvalue.size());
char *pEnd;
fillvalue_int = strtol((fillvalue.substr(1)).c_str(),&pEnd,8);
stringstream convert_str;
convert_str << fillvalue_int;
at->append_attr("_FillValue",var_type,convert_str.str());
}
else {
// If somehow the fillvalue type is DFNT_CHAR or DFNT_UCHAR, and the size is 1,
// that means the fillvalue type is wrongly defined, we treat as a 8-bit integer number.
// Note, the code will only assume the value ranges from 0 to 128.(JIRA HFRHANDLER-248).
// KY 2014-04-24
short fillvalue_int = fillvalue.at(0);
stringstream convert_str;
convert_str << fillvalue_int;
if(fillvalue_int <0 || fillvalue_int >128)
throw InternalErr(__FILE__,__LINE__,
"If the fillvalue is a char type, the value must be between 0 and 128.");
at->append_attr("_FillValue",var_type,convert_str.str());
}
}
else
at->append_attr("_FillValue",var_type,fillvalue);
}
}
it++;
}
}
// CF requires the scale_factor and add_offset attribute datatypes must be the same as the corresponding field datatype.
// For some NASA files, this is not true.
// So we need to check if the _FillValue's datatype is the same as the attribute's.
// If not, we need to correct them.
void HDFCFUtil::correct_scale_offset_type(AttrTable *at) {
AttrTable::Attr_iter it = at->attr_begin();
bool find_scale = false;
bool find_offset = false;
// Declare scale_factor,add_offset, fillvalue and valid_range type in string format.
string scale_factor_type;
string add_offset_type;
string scale_factor_value;
string add_offset_value;
while (it!=at->attr_end() &&((find_scale!=true) ||(find_offset!=true))) {
if (at->get_name(it) =="scale_factor")
{
find_scale = true;
scale_factor_value = (*at->get_attr_vector(it)->begin());
scale_factor_type = at->get_type(it);
}
if(at->get_name(it)=="add_offset")
{
find_offset = true;
add_offset_value = (*at->get_attr_vector(it)->begin());
add_offset_type = at->get_type(it);
}
it++;
}
// Change offset type to the scale type
if((true==find_scale) && (true==find_offset)) {
if(scale_factor_type != add_offset_type) {
at->del_attr("add_offset");
at->append_attr("add_offset",scale_factor_type,add_offset_value);
}
}
}
#ifdef USE_HDFEOS2_LIB
// For MODIS (confirmed by level 1B) products, values between 65500(MIN_NON_SCALE_SPECIAL_VALUE)
// and 65535(MAX_NON_SCALE_SPECIAL_VALUE) are treated as
// special values. These values represent non-physical data values caused by various failures.
// For example, 65533 represents "when Detector is saturated".
bool HDFCFUtil::is_special_value(int32 dtype, float fillvalue, float realvalue) {
bool ret_value = false;
if (DFNT_UINT16 == dtype) {
int fillvalue_int = (int)fillvalue;
if (MAX_NON_SCALE_SPECIAL_VALUE == fillvalue_int) {
int realvalue_int = (int)realvalue;
if (realvalue_int <= MAX_NON_SCALE_SPECIAL_VALUE && realvalue_int >=MIN_NON_SCALE_SPECIAL_VALUE)
ret_value = true;
}
}
return ret_value;
}
// Check if the MODIS file has dimension map and return the number of dimension maps
// Note: This routine is only applied to a MODIS geo-location file when the corresponding
// MODIS swath uses dimension maps and has the MODIS geo-location file under the same
// file directory. This is also restricted by turning on H4.EnableCheckMODISGeoFile to be true(file h4.conf.in).
// By default, this key is turned off. Also this function is only used once in one service. So it won't
// affect performance. KY 2014-02-18
int HDFCFUtil::check_geofile_dimmap(const string & geofilename) {
int32 fileid = SWopen(const_cast<char*>(geofilename.c_str()),DFACC_READ);
if (fileid < 0)
return -1;
string swathname = "MODIS_Swath_Type_GEO";
int32 datasetid = SWattach(fileid,const_cast<char*>(swathname.c_str()));
if (datasetid < 0) {
SWclose(fileid);
return -1;
}
int32 nummaps = 0;
int32 bufsize;
// Obtain number of dimension maps and the buffer size.
if ((nummaps = SWnentries(datasetid, HDFE_NENTMAP, &bufsize)) == -1) {
SWdetach(datasetid);
SWclose(fileid);
return -1;
}
SWdetach(datasetid);
SWclose(fileid);
return nummaps;
}
// Check if we need to change the datatype for MODIS fields. The datatype needs to be changed
// mainly because of non-CF scale and offset rules. To avoid violating CF conventions, we apply
// the non-CF MODIS scale and offset rule to MODIS data. So the final data type may be different
// than the original one due to this operation. For example, the original datatype may be int16.
// After applying the scale/offset rule, the datatype may become float32.
// The following are useful notes about MODIS SCALE OFFSET HANDLING
// Note: MODIS Scale and offset handling needs to re-organized. But it may take big efforts.
// Instead, I remove the global variable mtype, and _das; move the old calculate_dtype code
// back to HDFEOS2.cc. The code is a little better organized. If possible, we may think to overhaul
// the handling of MODIS scale-offset part. KY 2012-6-19
//
bool HDFCFUtil::change_data_type(DAS & das, SOType scaletype, const string &new_field_name)
{
AttrTable *at = das.get_table(new_field_name);
// The following codes do these:
// For MODIS level 1B(using the swath name), check radiance,reflectance etc.
// If the DISABLESCALE key is true, no need to check scale and offset for other types.
// Otherwise, continue checking the scale and offset names.
// KY 2013-12-13
if(scaletype!=DEFAULT_CF_EQU && at!=NULL)
{
AttrTable::Attr_iter it = at->attr_begin();
string scale_factor_value="";
string add_offset_value="0";
string radiance_scales_value="";
string radiance_offsets_value="";
string reflectance_scales_value="";
string reflectance_offsets_value="";
string scale_factor_type, add_offset_type;
while (it!=at->attr_end())
{
if(at->get_name(it)=="radiance_scales")
radiance_scales_value = *(at->get_attr_vector(it)->begin());
if(at->get_name(it)=="radiance_offsets")
radiance_offsets_value = *(at->get_attr_vector(it)->begin());
if(at->get_name(it)=="reflectance_scales")
reflectance_scales_value = *(at->get_attr_vector(it)->begin());
if(at->get_name(it)=="reflectance_offsets")
reflectance_offsets_value = *(at->get_attr_vector(it)->begin());
// Ideally may just check if the attribute name is scale_factor.
// But don't know if some products use attribut name like "scale_factor "
// So now just filter out the attribute scale_factor_err. KY 2012-09-20
if(at->get_name(it).find("scale_factor")!=string::npos){
string temp_attr_name = at->get_name(it);
if (temp_attr_name != "scale_factor_err") {
scale_factor_value = *(at->get_attr_vector(it)->begin());
scale_factor_type = at->get_type(it);
}
}
if(at->get_name(it).find("add_offset")!=string::npos)
{
string temp_attr_name = at->get_name(it);
if (temp_attr_name !="add_offset_err") {
add_offset_value = *(at->get_attr_vector(it)->begin());
add_offset_type = at->get_type(it);
}
}
it++;
}
if((radiance_scales_value.length()!=0 && radiance_offsets_value.length()!=0)
|| (reflectance_scales_value.length()!=0 && reflectance_offsets_value.length()!=0))
return true;
if(scale_factor_value.length()!=0)
{
if(!(atof(scale_factor_value.c_str())==1 && atof(add_offset_value.c_str())==0))
return true;
}
}
return false;
}
// Obtain the MODIS swath dimension map info.
void HDFCFUtil::obtain_dimmap_info(const string& filename,HDFEOS2::Dataset*dataset,
vector<struct dimmap_entry> & dimmaps,
string & modis_geofilename, bool& geofile_has_dimmap) {
HDFEOS2::SwathDataset *sw = static_cast<HDFEOS2::SwathDataset *>(dataset);
const vector<HDFEOS2::SwathDataset::DimensionMap*>& origdimmaps = sw->getDimensionMaps();
vector<HDFEOS2::SwathDataset::DimensionMap*>::const_iterator it_dmap;
struct dimmap_entry tempdimmap;
// if having dimension maps, we need to retrieve the dimension map info.
for(size_t i=0;i<origdimmaps.size();i++){
tempdimmap.geodim = origdimmaps[i]->getGeoDimension();
tempdimmap.datadim = origdimmaps[i]->getDataDimension();
tempdimmap.offset = origdimmaps[i]->getOffset();
tempdimmap.inc = origdimmaps[i]->getIncrement();
dimmaps.push_back(tempdimmap);
}
#if 0
string check_modis_geofile_key ="H4.EnableCheckMODISGeoFile";
bool check_geofile_key = false;
check_geofile_key = HDFCFUtil::check_beskeys(check_modis_geofile_key);
#endif
// Only when there is dimension map, we need to consider the additional MODIS geolocation files.
// Will check if the check modis_geo_location file key is turned on.
if((origdimmaps.size() != 0) && (true == HDF4RequestHandler::get_enable_check_modis_geo_file()) ) {
// Has to use C-style since basename and dirname are not C++ routines.
char*tempcstr;
tempcstr = new char [filename.size()+1];
strncpy (tempcstr,filename.c_str(),filename.size());
string basefilename = basename(tempcstr);
string dirfilename = dirname(tempcstr);
delete [] tempcstr;
// If the current file is a MOD03 or a MYD03 file, we don't need to check the extra MODIS geolocation file at all.
bool is_modis_geofile = false;
if(basefilename.size() >5) {
if((0 == basefilename.compare(0,5,"MOD03")) || (0 == basefilename.compare(0,5,"MYD03")))
is_modis_geofile = true;
}
// This part is implemented specifically for supporting MODIS dimension map data.
// MODIS Aqua Swath dimension map geolocation file always starts with MYD03
// MODIS Terra Swath dimension map geolocation file always starts with MOD03
// We will check the first three characters to see if the dimension map geolocation file exists.
// An example MODIS swath filename is MOD05_L2.A2008120.0000.005.2008121182723.hdf
// An example MODIS geo-location file name is MOD03.A2008120.0000.005.2010003235220.hdf
// Notice that the "A2008120.0000" in the middle of the name is the "Acquistion Date" of the data
// So the geo-location file name should have exactly the same string. We will use this
// string to identify if a MODIS geo-location file exists or not.
// Note the string size is 14(.A2008120.0000).
// More information of naming convention, check http://modis-atmos.gsfc.nasa.gov/products_filename.html
// KY 2010-5-10
// Obtain string "MYD" or "MOD"
// Here we need to consider when MOD03 or MYD03 use the dimension map.
if ((false == is_modis_geofile) && (basefilename.size() >3)) {
string fnameprefix = basefilename.substr(0,3);
if(fnameprefix == "MYD" || fnameprefix =="MOD") {
size_t fnamemidpos = basefilename.find(".A");
if(fnamemidpos != string::npos) {
string fnamemiddle = basefilename.substr(fnamemidpos,14);
if(fnamemiddle.size()==14) {
string geofnameprefix = fnameprefix+"03";
// geofnamefp will be something like "MOD03.A2008120.0000"
string geofnamefp = geofnameprefix + fnamemiddle;
DIR *dirp;
struct dirent* dirs;
// Go through the directory to see if we have the corresponding MODIS geolocation file
dirp = opendir(dirfilename.c_str());
if (NULL == dirp)
throw InternalErr(__FILE__,__LINE__,"opendir fails.");
while ((dirs = readdir(dirp))!= NULL){
if(strncmp(dirs->d_name,geofnamefp.c_str(),geofnamefp.size())==0){
modis_geofilename = dirfilename + "/"+ dirs->d_name;
int num_dimmap = HDFCFUtil::check_geofile_dimmap(modis_geofilename);
if (num_dimmap < 0) {
closedir(dirp);
throw InternalErr(__FILE__,__LINE__,"this file is not a MODIS geolocation file.");
}
geofile_has_dimmap = (num_dimmap >0)?true:false;
break;
}
}
closedir(dirp);
}
}
}
}
}
}
// This is for the case that the separate MODIS geo-location file is used.
// Some geolocation names at the MODIS data file are not consistent with
// the names in the MODIS geo-location file. So need to correct them.
bool HDFCFUtil::is_modis_dimmap_nonll_field(string & fieldname) {
bool modis_dimmap_nonll_field = false;
vector<string> modis_dimmap_nonll_fieldlist;
modis_dimmap_nonll_fieldlist.push_back("Height");
modis_dimmap_nonll_fieldlist.push_back("SensorZenith");
modis_dimmap_nonll_fieldlist.push_back("SensorAzimuth");
modis_dimmap_nonll_fieldlist.push_back("Range");
modis_dimmap_nonll_fieldlist.push_back("SolarZenith");
modis_dimmap_nonll_fieldlist.push_back("SolarAzimuth");
modis_dimmap_nonll_fieldlist.push_back("Land/SeaMask");
modis_dimmap_nonll_fieldlist.push_back("gflags");
modis_dimmap_nonll_fieldlist.push_back("Solar_Zenith");
modis_dimmap_nonll_fieldlist.push_back("Solar_Azimuth");
modis_dimmap_nonll_fieldlist.push_back("Sensor_Azimuth");
modis_dimmap_nonll_fieldlist.push_back("Sensor_Zenith");
map<string,string>modis_field_to_geofile_field;
map<string,string>::iterator itmap;
modis_field_to_geofile_field["Solar_Zenith"] = "SolarZenith";
modis_field_to_geofile_field["Solar_Azimuth"] = "SolarAzimuth";
modis_field_to_geofile_field["Sensor_Zenith"] = "SensorZenith";
modis_field_to_geofile_field["Solar_Azimuth"] = "SolarAzimuth";
for (unsigned int i = 0; i <modis_dimmap_nonll_fieldlist.size(); i++) {
if (fieldname == modis_dimmap_nonll_fieldlist[i]) {
itmap = modis_field_to_geofile_field.find(fieldname);
if (itmap !=modis_field_to_geofile_field.end())
fieldname = itmap->second;
modis_dimmap_nonll_field = true;
break;
}
}
return modis_dimmap_nonll_field;
}
void HDFCFUtil::add_scale_offset_attrs(AttrTable*at,const std::string& s_type, float svalue_f, double svalue_d, bool add_offset_found,
const std::string& o_type, float ovalue_f, double ovalue_d) {
at->del_attr("scale_factor");
string print_rep;
if(s_type!="Float64") {
print_rep = HDFCFUtil::print_attr(DFNT_FLOAT32,0,(void*)(&svalue_f));
at->append_attr("scale_factor", "Float32", print_rep);
}
else {
print_rep = HDFCFUtil::print_attr(DFNT_FLOAT64,0,(void*)(&svalue_d));
at->append_attr("scale_factor", "Float64", print_rep);
}
if (true == add_offset_found) {
at->del_attr("add_offset");
if(o_type!="Float64") {
print_rep = HDFCFUtil::print_attr(DFNT_FLOAT32,0,(void*)(&ovalue_f));
at->append_attr("add_offset", "Float32", print_rep);
}
else {
print_rep = HDFCFUtil::print_attr(DFNT_FLOAT64,0,(void*)(&ovalue_d));
at->append_attr("add_offset", "Float64", print_rep);
}
}
}
void HDFCFUtil::add_scale_str_offset_attrs(AttrTable*at,const std::string& s_type, const std::string& s_value_str, bool add_offset_found,
const std::string& o_type, float ovalue_f, double ovalue_d) {
at->del_attr("scale_factor");
string print_rep;
if(s_type!="Float64")
at->append_attr("scale_factor", "Float32", s_value_str);
else
at->append_attr("scale_factor", "Float64", s_value_str);
if (true == add_offset_found) {
at->del_attr("add_offset");
if(o_type!="Float64") {
print_rep = HDFCFUtil::print_attr(DFNT_FLOAT32,0,(void*)(&ovalue_f));
at->append_attr("add_offset", "Float32", print_rep);
}
else {
print_rep = HDFCFUtil::print_attr(DFNT_FLOAT64,0,(void*)(&ovalue_d));
at->append_attr("add_offset", "Float64", print_rep);
}
}
}
/// Add comments.
void HDFCFUtil::handle_modis_special_attrs_disable_scale_comp(AttrTable *at,
const string &filename,
bool is_grid,
const string & newfname,
SOType sotype){
// Declare scale_factor,add_offset, fillvalue and valid_range type in string format.
string scale_factor_type;
string add_offset_type;
// Scale and offset values
string scale_factor_value="";
float orig_scale_value_float = 1;
float orig_scale_value_double = 1;
string add_offset_value="0";
float orig_offset_value_float = 0;
float orig_offset_value_double = 0;
bool add_offset_found = false;