-
Notifications
You must be signed in to change notification settings - Fork 1
/
clsRasterData.h
2514 lines (2305 loc) · 99.4 KB
/
clsRasterData.h
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
/*!
* \brief Define Raster class to handle raster data
*
* 1. Using GDAL and MongoDB (currently, mongo-c-driver 1.5.0+ is supported)
* 2. Array1D and Array2D raster data are supported
* 3. C++11 supported
* 4. Unit Tests based Google Test.
*
* \author Junzhi Liu, LiangJun Zhu
* \version 2.1
* \date Apr. 2011
* \revised May. 2016
* Dec. 2016 lj Separated from SEIMS to a common library for widely use.
* Mar. 2017 lj VLD check, bug fixed, function enhanced.
* Apr. 2017 lj Avoid try...catch block
* May. 2017 lj Use MongoDB wrapper
* Nov. 2017 lj Code review based on C++11 and use a single header file.
* Dec. 2017 lj Add Unittest based on Google Test.
*/
#ifndef CLS_RASTER_DATA
#define CLS_RASTER_DATA
/// include MongoDB, optional
#ifdef USE_MONGODB
#include "MongoUtil.h"
#endif /* USE_MONGODB */
/// include utility functions
#include "utilities.h"
/// include GDAL, required
#include "gdal.h"
#include "gdal_priv.h"
#include "cpl_string.h"
#include "ogr_spatialref.h"
/// include openmp if supported
#ifdef SUPPORT_OMP
#include <omp.h>
#endif /* SUPPORT_OMP */
/// include base headers
#include <cstdint>
#include <string>
#include <map>
#include <fstream>
#include <iomanip>
#include <typeinfo>
using namespace std;
/* Ignore warning on Windows MSVC compiler caused by GDAL.
* refers to http://blog.csdn.net/liminlu0314/article/details/8227518
*/
#if defined(_MSC_VER) && (_MSC_VER >= 1400)
#pragma warning(disable: 4100 4190 4251 4275 4305 4309 4819 4996)
#endif /* Ignore warnings of GDAL */
/*!
* Define Raster related constant strings used for raster headers
*/
#define HEADER_RS_NODATA "NODATA_VALUE"
#define HEADER_RS_XLL "XLLCENTER" /// or XLLCORNER
#define HEADER_RS_YLL "YLLCENTER" /// or YLLCORNER
#define HEADER_RS_NROWS "NROWS"
#define HEADER_RS_NCOLS "NCOLS"
#define HEADER_RS_CELLSIZE "CELLSIZE"
#define HEADER_RS_LAYERS "LAYERS"
#define HEADER_RS_CELLSNUM "CELLSNUM"
#define HEADER_RS_SRS "SRS"
/*!
* Define constant strings of statistics index
*/
#define STATS_RS_VALIDNUM "VALID_CELLNUMBER"
#define STATS_RS_MEAN "MEAN"
#define STATS_RS_MIN "MIN"
#define STATS_RS_MAX "MAX"
#define STATS_RS_STD "STD"
#define STATS_RS_RANGE "RANGE"
/*!
* Files or database constant strings
*/
#define ASCIIExtension "asc"
#define GTiffExtension "tif"
typedef pair<int, int> RowCol;
typedef pair<double, double> XYCoor;
/** Common functions independent to clsRasterData **/
inline void print_status(string status_str) {
#ifndef UNITTEST
cout << status_str << endl;
#endif
}
/*!
* \brief check the existence of given raster file
*/
inline bool _check_raster_files_exist(const string &filename) {
if (!FileExists(filename)) {
print_status("The raster file " + filename + " does not exist or has not read permission.");
return false;
}
return true;
}
/*!
* \brief check the existence of given vector of raster files
* \return True if all existed, else false
*/
inline bool _check_raster_files_exist(vector<string> &filenames) {
for (auto it = filenames.begin(); it != filenames.end(); it++) {
if (!_check_raster_files_exist(*it)) {
return false;
}
}
return true;
}
template<typename T1, typename T2>
inline void _get_data_from_gdal(T1 *dst, T2 *src, int nr, int nc) {
#pragma omp parallel for
for (int i = 0; i < nr; ++i) {
for (int j = 0; j < nc; ++j) {
int index = i * nc + j;
dst[index] = (T1) src[index];
}
}
}
/*!
* \class clsRasterData
* \ingroup data
* \brief Raster data (1D and 2D) I/O class
* Support I/O between TIFF, ASCII file or/and MongoBD database.
*/
template<typename T, typename MaskT = T>
class clsRasterData {
public:
/************* Construct functions ***************/
/*!
* \brief Constructor an empty clsRasterData instance
* By default, 1D raster data
* Set \a m_rasterPositionData, \a m_rasterData, \a m_mask to \a nullptr
* \TODO Add some Set functions to make this empty constructor usable.
*/
clsRasterData();
/*!
* \brief Construtor 1D raster from necessary data
*/
clsRasterData(T *data, int cols, int rows, T nodata, double dx, double xll, double yll, const string &srs = "");
/*!
* \brief Construtor 1D raster from necessary data
*/
clsRasterData(T **data2d,
int cols,
int rows,
int nlayers,
T nodata,
double dx,
double xll,
double yll,
const string &srs = "");
/*!
* \brief Constructor of clsRasterData instance from TIFF, ASCII, or other GDAL supported raster file
* \param[in] filename Full path of the raster file
* \param[in] calcPositions Calculate positions of valid cells excluding NODATA. The default is true.
* \param[in] mask \a clsRasterData<MaskT> Mask layer
* \param[in] useMaskExtent Use mask layer extent, even NoDATA exists.
* \param[in] defalutValue Default value when mask data exceeds the raster extend.
*
*/
explicit clsRasterData(const string &filename,
bool calcPositions = true,
clsRasterData<MaskT> *mask = nullptr,
bool useMaskExtent = true,
T defalutValue = (T) NODATA_VALUE);
/*!
* \brief Validation check before the constructor of clsRasterData,
* i.e., the raster file is existed and supported.
* This is the recommended way to construct an instance of clsRasterData.
* \usage
* clsRasterData<T, MaskT> *rs = clsRasterData<T, MaskT>::Init(filename)
* if (nullptr == rs) {
* throw exception("clsRasterData initialization failed!");
* // or other error handling code.
* }
*/
static clsRasterData<T, MaskT> *Init(const string &filename,
bool calcPositions = true,
clsRasterData<MaskT> *mask = nullptr,
bool useMaskExtent = true,
T defalutValue = (T) NODATA_VALUE);
/*!
* \brief Constructor of clsRasterData instance from TIFF, ASCII, or other GDAL supported raster file
* Support 1D and/or 2D raster data
* \sa ReadASCFile() ReadByGDAL()
* \param[in] filenames Full paths vector of the 2D raster data
* \param[in] calcPositions Calculate positions of valid cells excluding NODATA. The default is true.
* \param[in] mask \a clsRasterData<MaskT> Mask layer
* \param[in] useMaskExtent Use mask layer extent, even NoDATA exists.
*/
explicit clsRasterData(vector<string> &filenames,
bool calcPositions = true,
clsRasterData<MaskT> *mask = nullptr,
bool useMaskExtent = true,
T defalutValue = (T) NODATA_VALUE);
/*!
* \brief Validation check before the constructor of clsRasterData,
* i.e., the raster files are all existed and supported.
*/
static clsRasterData<T, MaskT> *Init(vector<string> &filenames,
bool calcPositions = true,
clsRasterData<MaskT> *mask = nullptr,
bool useMaskExtent = true,
T defalutValue = (T) NODATA_VALUE);
/*!
* \brief Construct an clsRasterData instance by 1D array data and mask
*/
clsRasterData(clsRasterData<MaskT> *mask, const T *values);
/*!
* \brief Construct an clsRasterData instance by 2D array data and mask
*/
clsRasterData(clsRasterData<MaskT> *mask, const T *const *values, int lyrs);
#ifdef USE_MONGODB
/*!
* \brief Constructor based on mongoDB
* \sa ReadFromMongoDB()
*
* \param[in] gfs \a mongoc_gridfs_t
* \param[in] romoteFilename \a char*
* \param[in] calcPositions Calculate positions of valid cells excluding NODATA. The default is true.
* \param[in] mask \a clsRasterData<MaskT> Mask layer
* \param[in] useMaskExtent Use mask layer extent, even NoDATA exists.
*/
clsRasterData(MongoGridFS *gfs, const char *remoteFilename, bool calcPositions = true,
clsRasterData<MaskT> *mask = nullptr, bool useMaskExtent = true,
T defalutValue = (T) NODATA_VALUE);
/*!
* \brief Validation check before the constructor of clsRasterData.
*/
static clsRasterData<T, MaskT> *Init(MongoGridFS *gfs, const char *remoteFilename,
bool calcPositions = true,
clsRasterData<MaskT> *mask = nullptr,
bool useMaskExtent = true,
T defalutValue = (T) NODATA_VALUE);
#endif
/*!
* \brief Copy constructor
* \usage
* Method 1: clsRasterData<T> newraster(baseraster);
*
* Method 2: clsRasterData<T> newraster;
* newraster.Copy(baseraster);
*
* Method 3: clsRasterData<T>* newraster = new clsRasterData<T>(baseraster);
* delete newraster;
*/
explicit clsRasterData(clsRasterData<T, MaskT> *another);
//! Destructor
~clsRasterData();
/************* Read functions ***************/
/*!
* \brief Read raster data from file, mask data is optional
* \param[in] filename \a string
* \param[in] calcPositions Calculate positions of valid cells excluding NODATA. The default is true.
* \param[in] mask \a clsRasterData<MaskT>
* \param[in] useMaskExtent Use mask layer extent, even NoDATA exists.
*/
bool ReadFromFile(string filename, bool calcPositions = true, clsRasterData<MaskT> *mask = nullptr,
bool useMaskExtent = true, T defalutValue = (T) NODATA_VALUE);
#ifdef USE_MONGODB
/*!
* \brief Read raster data from MongoDB
* \param[in] gfs \a mongoc_gridfs_t
* \param[in] filename \a char*, raster file name
* \param[in] calcPositions Calculate positions of valid cells excluding NODATA. The default is true.
* \param[in] mask \a clsRasterData<MaskT>
* \param[in] useMaskExtent Use mask layer extent, even NoDATA exists.
*/
bool ReadFromMongoDB(MongoGridFS *gfs,
string filename,
bool calcPositions = true,
clsRasterData<MaskT> *mask = nullptr,
bool useMaskExtent = true,
T defalutValue = (T) NODATA_VALUE);
#endif /* USE_MONGODB */
/************* Write functions ***************/
/*!
* \brief Write raster to raster file, if 2D raster, output name will be filename_LyrNum
* \param filename filename with prefix, e.g. ".asc" and ".tif"
*/
bool outputToFile(string filename);
/*!
* \brief Write 1D or 2D raster data into ASC file(s)
* \param[in] filename \a string, output ASC file path, take the CoreName as prefix
*/
bool outputASCFile(string filename);
/*!
* \brief Write 1D or 2D raster data into TIFF file by GDAL
* \param[in] filename \a string, output TIFF file path
*/
bool outputFileByGDAL(string filename);
#ifdef USE_MONGODB
/*!
* \brief Write raster data (matrix raster data) into MongoDB
* \param[in] filename \a string, output file name
* \param[in] gfs \a mongoc_gridfs_t
*/
void outputToMongoDB(string filename, MongoGridFS *gfs);
#endif /* USE_MONGODB */
/************************************************************************/
/* Set information functions */
/************************************************************************/
//! Set new core file name
void setCoreName(string name) { m_coreFileName = name; }
/*!
* \brief Set value to the given position and layer
*/
void setValue(int row, int col, T value, int lyr = 1);
/************************************************************************/
/* Get information functions */
/************************************************************************/
/*!
* \brief Calculate basic statistics values in one time
* Mean, Max, Min, STD, Range, etc.
*/
void calculateStatistics();
/*!
* \brief Force to update basic statistics values
* Mean, Max, Min, STD, Range, etc.
*/
void updateStatistics();
/*!
* \brief Release statistics map of 2D raster data
*/
void releaseStatsMap2D();
/*!
* \brief Get basic statistics value
* Mean, Max, Min, STD, Range, etc.
* \param[in] sindex \string, case insensitive
* \param[in] lyr optional for 1D and the first layer of 2D raster data.
* \param[out] Statistics value or NODATA
*/
double getStatistics(string sindex, int lyr = 1);
/*!
* \brief Get basic statistics values for 2D raster data.
* Mean, Max, Min, STD, Range, etc.
* \param[in] sindex \string, case insensitive
* \param[out] lyrnum \int, layer number
* \param[out] values \double* Statistics array or nullptr
*/
void getStatistics(string sindex, int *lyrnum, double **values);
/*!
* \brief Get the average of raster data
* \param[in] lyr optional for 1D and the first layer of 2D raster data.
*/
float getAverage(int lyr = 1) { return (float) this->getStatistics(string(STATS_RS_MEAN), lyr); }
/*!
* \brief Get the maximum of raster data
* \sa getAverage
*/
float getMaximum(int lyr = 1) { return (float) this->getStatistics(STATS_RS_MAX, lyr); }
/*!
* \brief Get the minimum of raster data
* \sa getAverage
*/
float getMinimum(int lyr = 1) { return (float) this->getStatistics(STATS_RS_MIN, lyr); }
/*!
* \brief Get the stand derivation of raster data
* \sa getAverage
*/
float getSTD(int lyr = 1) { return (float) this->getStatistics(STATS_RS_STD, lyr); }
/*!
* \brief Get the range of raster data
* \sa getMaximum, getMinimum
*/
float getRange(int lyr = 1) { return (float) this->getStatistics(STATS_RS_RANGE, lyr); }
/*!
* \brief Get the average of 2D raster data
* \param[out] lyrnum \int, layer number
* \param[out] values \double* Statistics array
*/
void getAverage(int *lyrnum, double **values) { this->getStatistics(STATS_RS_MEAN, lyrnum, values); }
/*!
* \brief Get the maximum of 2D raster data
* \sa getAverage
*/
void getMaximum(int *lyrnum, double **values) { this->getStatistics(STATS_RS_MAX, lyrnum, values); }
/*!
* \brief Get the minimum of 2D raster data
* \sa getAverage
*/
void getMinimum(int *lyrnum, double **values) { this->getStatistics(STATS_RS_MIN, lyrnum, values); }
/*!
* \brief Get the standard derivation of 2D raster data
* \sa getAverage
*/
void getSTD(int *lyrnum, double **values) { this->getStatistics(STATS_RS_STD, lyrnum, values); }
/*!
* \brief Get the range of 2D raster data
* \sa getAverage
*/
void getRange(int *lyrnum, double **values) { this->getStatistics(STATS_RS_RANGE, lyrnum, values); }
/*!
* \brief Get the non-NoDATA number of 2D raster data
* \sa getAverage
*/
void getValidNumber(int *lyrnum, double **values) { this->getStatistics(STATS_RS_VALIDNUM, lyrnum, values); }
/*!
* \brief Get the non-NoDATA cells number of the given raster layer data
* \sa getCellNumber, getDataLength
*/
int getValidNumber(int lyr = 1) { return (int) this->getStatistics(STATS_RS_VALIDNUM, lyr); }
//! Get stored cell number of raster data
int getCellNumber() const { return m_nCells; }
//! Get the first dimension size of raster data
//! TODO, check out if this function is need? by lj.
int getDataLength() const { return m_nCells; }
//! Get column number of raster data
int getCols() const { return (int) m_headers.at(HEADER_RS_NCOLS); }
//! Get row number of raster data
int getRows() const { return (int) m_headers.at(HEADER_RS_NROWS); }
//! Get cell size of raster data
float getCellWidth() const { return (float) m_headers.at(HEADER_RS_CELLSIZE); }
//! Get X coordinate of left lower corner of raster data
double getXllCenter() const { return m_headers.at(HEADER_RS_XLL); }
//! Get Y coordinate of left lower corner of raster data
double getYllCenter() const { return m_headers.at(HEADER_RS_YLL); }
inline int getLayers() const {
assert(m_nLyrs == (int) m_headers.at(HEADER_RS_LAYERS));
return m_nLyrs;
}
//! Get NoDATA value of raster data
T getNoDataValue() const { return (T) m_headers.at(HEADER_RS_NODATA); }
//! Get NoDATA value of raster data
T getDefaultValue() const { return m_defaultValue; }
/*!
* \brief Get position index in 1D raster data for specific row and column
* \return -1 --- the position is nodata
* -2 --- the position is out of the extent, which indicates an error
*/
int getPosition(int row, int col);
//! Get position index in 1D raster data for given coordinate (x,y)
int getPosition(float x, float y);
//! Get position index in 1D raster data for given coordinate (x,y)
int getPosition(double x, double y);
/*! \brief Get raster data, include valid cell number and data
* \return true if the raster data has been initialized, otherwise return false and print error info.
*/
bool getRasterData(int *nCells, T **data);
/*! \brief Get 2D raster data, include valid cell number of each layer, layer number, and data
* \return true if the 2D raster has been initialized, otherwise return false and print error info.
*/
bool get2DRasterData(int *nCells, int *nLyrs, T ***data);
//! Get raster header information
const map<string, double> &getRasterHeader() const { return m_headers; }
//! Get raster statistics information
const map<string, double> &getStatistics() const { return m_statsMap; }
//! Get raster statistics information of 2D raster
const map<string, double *> &getStatistics2D() const { return m_statsMap2D; };
//! Get full path name
string getFilePath() const { return m_filePathName; }
//! Get core name
string getCoreName() const { return m_coreFileName; }
/*!
* \brief Get position index data and the data length
* \param[out] datalength
* \param[out] positiondata, the pointer of 2D array (pointer)
*/
void getRasterPositionData(int *datalength, int ***positiondata);
//! Get pointer of raster data
T *getRasterDataPointer() const { return m_rasterData; }
//! Get pointer of position data
int **getRasterPositionDataPointer() const { return m_rasterPositionData; }
//! Get pointer of 2D raster data
T **get2DRasterDataPointer() const { return m_raster2DData; }
//! Get the spatial reference
const char *getSRS() { return m_srs.c_str(); }
//! Get the spatial reference string
string getSRSString() { return m_srs; }
/*!
* \brief Get raster data at the valid cell index
* The default lyr is 1, which means the 1D raster data, or the first layer of 2D data.
*/
T getValueByIndex(int cellIndex, int lyr = 1);
/*!
* \brief Get raster data at the valid cell index (both for 1D and 2D raster)
* \return a float array with length as nLyrs
*/
void getValueByIndex(int cellIndex, int *nLyrs, T **values);
/*!
* \brief Get raster data via row and col
* The default lyr is 1, which means the 1D raster data, or the first layer of 2D data.
*/
T getValue(int row, int col, int lyr = 1);
/*!
* \brief Get raster data (both for 1D and 2D raster) at the (row, col)
* \return a float array with length as nLyrs
*/
void getValue(int row, int col, int *nLyrs, T **values);
/*!
* \brief Check if the raster data is NoData via row and col
* The default lyr is 1, which means the 1D raster data, or the first layer of 2D data.
*/
inline T isNoData(int row, int col, int lyr = 1) {
return FloatEqual(this->getValue(row, col, lyr), m_noDataValue);
}
//! Is 2D raster data?
bool is2DRaster() const { return m_is2DRaster; }
//! Calculate positions or not
bool PositionsCalculated() const { return m_calcPositions; }
//! raster position data is stored as array (true), or just a pointer
bool PositionsAllocated() const { return m_storePositions; }
//! Use mask extent or not
bool MaskExtented() const { return m_useMaskExtent; }
//! Basic statistics has been calculated or not
bool StatisticsCalculated() const { return m_statisticsCalculated; }
//! The instance of clsRasterData has been initialized or not
bool Initialized() const { return m_initialized; }
/*!
* \brief Validate the available of raster data, both 1D and 2D data
*/
inline bool validate_raster_data() {
if ((!m_is2DRaster && nullptr != m_rasterData) || // Valid 1D raster
(m_is2DRaster && nullptr != m_raster2DData)) { // Valid 2D raster
return true;
} else {
print_status("Please initialize the raster object first.");
return false;
}
}
/*!
* \brief Validate the input row and col
*/
inline bool validate_row_col(int row, int col) {
if ((row < 0 || row >= this->getRows()) || (col < 0 || col >= this->getCols())) {
print_status("The row must between 0 and " + ValueToString(this->getRows() - 1) +
", and the col must between 0 and " + ValueToString(this->getCols() - 1));
return false;
} else { return true; }
}
/*!
* \brief Validate the input layer number
*/
inline bool validate_layer(int lyr) {
if (lyr <= 0 || lyr > m_nLyrs) {
print_status("The layer must be 1 ");
if (m_nLyrs > 1) print_status(" or between 1 and " + ValueToString(m_nLyrs));
return false;
} else { return true; }
}
/*!
* \brief Validate the input index
*/
inline bool validate_index(int idx) {
if (idx < 0 || idx >= m_nCells) {
print_status("The index must between 0 and " + ValueToString(m_nCells - 1));
return false;
} else { return true; }
}
//! Get full filename
string GetFullFileName() const { return m_filePathName; }
//! Get mask data pointer
clsRasterData<MaskT> *getMask() const { return m_mask; }
/*!
* \brief Copy clsRasterData object
*/
void Copy(const clsRasterData<T, MaskT> *orgraster);
/*!
* \brief Replace NoData value by the given value
*/
void replaceNoData(T replacedv);
/*!
* \brief classify raster
*/
void reclassify(map<int, T> reclassMap);
/************* Utility functions ***************/
/*!
* \brief Calculate XY coordinates by given row and col number
* \sa getPositionByCoordinate
* \param[in] row
* \param[in] col
* \return pair<double x, double y>
*/
XYCoor getCoordinateByRowCol(int row, int col);
/*!
* \brief Calculate position by given coordinate
* \sa getCoordinateByRowCol
* \param[in] x
* \param[in] y
* \param[in] header Optional, header map of raster layer data, the default is m_header
* \return pair<int row, int col>
*/
RowCol getPositionByCoordinate(double x, double y, map<string, double> *header = nullptr);
/*!
* \brief Copy header information to current Raster data
* \param[in] refers
*/
void copyHeader(const map<string, double> &refers);
private:
/*!
* \brief Initialize all raster related variables.
*/
void _initialize_raster_class();
/*!
* \brief Initialize read function for ASC, GDAL, and MongoDB
*/
void _initialize_read_function(string filename, bool calcPositions = true, clsRasterData<MaskT> *mask = nullptr,
bool useMaskExtent = true, T defalutValue = (T) NODATA_VALUE);
/*!
* \brief Constructor of clsRasterData instance from single file of TIFF, ASCII, or other GDAL supported raster file
* Support 1D and/or 2D raster data
* \param[in] filename Full path of the raster file
* \param[in] calcPositions Calculate positions of valid cells excluding NODATA. The default is true.
* \param[in] mask \a clsRasterData<T2> Mask layer
* \param[in] useMaskExtent Use mask layer extent, even NoDATA exists.
* \return true if read successfully, otherwise return false.
*/
bool _construct_from_single_file(string filename, bool calcPositions = true, clsRasterData<MaskT> *mask = nullptr,
bool useMaskExtent = true, T defalutValue = (T) NODATA_VALUE);
/*!
* \brief Read raster data from ASC file, the simply usage
* \param[in] ascFileName \a string
* \param[out] header Raster header information
* \param[out] values Raster data matrix
* \return true if read successfully, otherwise return false.
*/
bool _read_asc_file(string ascFileName, map<string, double> *header, T **values);
/*!
* \brief Read raster data by GDAL, the simply usage
* \param[in] filename \a string
* \param[out] header Raster header information
* \param[out] values Raster data matrix
* \return true if read successfully, otherwise return false.
*/
bool _read_raster_file_by_gdal(string filename, map<string, double> *header,
T **values, string *srs = nullptr);
/*!
* \brief Extract by mask data and calculate position index, if necessary.
*/
void _mask_and_calculate_valid_positions();
/*!
* \brief Calculate position index from rectangle grid values, if necessary.
* To use this function, mask should be nullptr.
*
*/
void _calculate_valid_positions_from_grid_data();
/*!
* \brief Write raster header information into ASC file
* If the file exists, delete it first.
* \param[in] filename \a string, output ASC file path
* \param[in] header header information
*/
bool _write_ASC_headers(string filename, map<string, double> &header);
/*!
* \brief Write single geotiff file
* If the file exists, delete it first.
* \param[in] filename \a string, output ASC file path
* \param[in] header header information
* \param[in] srs Coordinate system string
* \param[in] values float raster data array
*/
bool _write_single_geotiff(string filename, map<string, double> &header, string srs, float *values);
#ifdef USE_MONGODB
/*!
* \brief Write full-sized raster data as GridFS file
* If the file exists, delete it first.
* \param[in] filename \a string, GridFS file name
* \param[in] header header information
* \param[in] srs Coordinate system string
* \param[in] values float raster data array
*/
void _write_stream_data_as_gridfs(MongoGridFS *gfs,
string filename,
map<string, double> &header,
string srs,
T *values,
size_t datalength);
#endif /* USE_MONGODB */
/*!
* \brief Add other layer's rater data to m_raster2DData
* \param[in] row Row number be added on, e.g. 2
* \param[in] col Column number be added on, e.g. 3
* \param[in] cellidx Cell index in m_raster2DData, e.g. 23
* \param[in] lyr Layer number which is greater than 1, e.g. 2, 3, ..., n
* \param[in] lyrheader Header information of current layer
* \param[in] lyrdata Raster layer data
*/
void _add_other_layer_raster_data(int row, int col, int cellidx, int lyr,
map<string, double> lyrheader, T *lyrdata);
inline void _check_default_value() {
if (FloatEqual(m_defaultValue, (T) NODATA_VALUE) && !FloatEqual(m_noDataValue, (T) NODATA_VALUE)) {
m_defaultValue = m_noDataValue;
}
}
private:
/*!
* \brief Operator= without implementation
*/
clsRasterData &operator=(const clsRasterData &another);
private:
/*! cell number of raster data, i.e. the data length of \sa m_rasterData or \sa m_raster2DData
* 1. all grid cell number, i.e., ncols * nrows, when m_calcPositions is False
* 2. valid cell number excluding NoDATA, when m_calcPositions is True and m_useMaskExtent is False.
* 3. including NoDATA when mask is valid and m_useMaskExtent is True.
*/
int m_nCells;
//! Layer number of the 2D raster
int m_nLyrs;
///< noDataValue
T m_noDataValue;
///< default value when mask by mask data, if not specified, it equals to m_noDataValue
T m_defaultValue;
///< raster full path, e.g. "C:/tmp/studyarea.tif"
string m_filePathName;
///< core raster file name, e.g. "studyarea"
string m_coreFileName;
///< OGRSpatialReference
string m_srs;
///< 1D raster data
T *m_rasterData;
///< 2D raster data, [cellIndex][layer]
T **m_raster2DData;
///< cell index (row, col) in m_rasterData or the first layer of m_raster2DData (2D array)
int **m_rasterPositionData;
///< Header information, using double in case of truncation of coordinate value
map<string, double> m_headers;
//! Map to store basic statistics values for 1D raster data
map<string, double> m_statsMap;
//! Map to store basic statistics values for 2D raster data
map<string, double *> m_statsMap2D;
///< mask clsRasterData instance
clsRasterData<MaskT> *m_mask;
///< initial once
bool m_initialized;
///< Flag to identify 1D or 2D raster
bool m_is2DRaster;
///< calculate valid positions or not. The default is true.
bool m_calcPositions;
///< raster position data is newly allocated array (true), or just a pointer (false)
bool m_storePositions;
///< To be consistent with other datesets, keep the extent of Mask layer, even include NoDATA.
bool m_useMaskExtent;
///< Statistics calculated?
bool m_statisticsCalculated;
};
/*******************************************************/
/************* Implementation Code Begin ***************/
/*******************************************************/
/************* Construct functions ***************/
template<typename T, typename MaskT>
void clsRasterData<T, MaskT>::_initialize_raster_class() {
m_filePathName = "";
m_coreFileName = "";
m_nCells = -1;
m_noDataValue = (T) NODATA_VALUE;
m_defaultValue = (T) NODATA_VALUE;
m_rasterData = nullptr;
m_rasterPositionData = nullptr;
m_mask = nullptr;
m_nLyrs = -1;
m_is2DRaster = false;
m_raster2DData = nullptr;
m_calcPositions = false;
m_storePositions = false;
m_useMaskExtent = false;
m_statisticsCalculated = false;
const char *RASTER_HEADERS[8] = {HEADER_RS_NCOLS, HEADER_RS_NROWS, HEADER_RS_XLL, HEADER_RS_YLL, HEADER_RS_CELLSIZE,
HEADER_RS_NODATA, HEADER_RS_LAYERS, HEADER_RS_CELLSNUM};
for (int i = 0; i < 6; i++) {
m_headers.insert(make_pair(RASTER_HEADERS[i], NODATA_VALUE));
}
m_headers.insert(make_pair(HEADER_RS_LAYERS, -1.));
m_headers.insert(make_pair(HEADER_RS_CELLSNUM, -1.));
string statsnames[6] = {STATS_RS_VALIDNUM, STATS_RS_MIN, STATS_RS_MAX, STATS_RS_MEAN,
STATS_RS_STD, STATS_RS_RANGE};
for (int i = 0; i < 6; i++) {
m_statsMap.insert(make_pair(statsnames[i], NODATA_VALUE));
m_statsMap2D.insert(map<string, double *>::value_type(statsnames[i], nullptr));
}
m_initialized = true;
}
template<typename T, typename MaskT>
void clsRasterData<T, MaskT>::_initialize_read_function(string filename, bool calcPositions /* = true */,
clsRasterData<MaskT> *mask /* = nullptr */,
bool useMaskExtent /* = true */,
T defalutValue /* = (T) NODATA_VALUE */) {
if (!m_initialized) this->_initialize_raster_class();
if (nullptr != mask) m_mask = mask;
m_filePathName = filename; // full path
m_coreFileName = GetCoreFileName(m_filePathName);
m_calcPositions = calcPositions;
m_useMaskExtent = useMaskExtent;
m_defaultValue = defalutValue;
}
template<typename T, typename MaskT>
clsRasterData<T, MaskT>::clsRasterData() {
this->_initialize_raster_class();
}
template<typename T, typename MaskT>
clsRasterData<T, MaskT>::clsRasterData(T *data, int cols, int rows, T nodata, double dx,
double xll, double yll, const string &srs /* = "" */) {
this->_initialize_raster_class();
m_rasterData = data;
m_noDataValue = nodata;
m_srs = srs;
m_nCells = cols * rows;
m_nLyrs = 1;
m_headers[HEADER_RS_NCOLS] = cols;
m_headers[HEADER_RS_NROWS] = rows;
m_headers[HEADER_RS_XLL] = xll;
m_headers[HEADER_RS_YLL] = yll;
m_headers[HEADER_RS_CELLSIZE] = dx;
m_headers[HEADER_RS_NODATA] = nodata;
m_headers[HEADER_RS_LAYERS] = 1;
m_headers[HEADER_RS_CELLSNUM] = m_nCells;
}
template<typename T, typename MaskT>
clsRasterData<T, MaskT>::clsRasterData(T **data2d, int cols, int rows, int nlayers, T nodata, double dx,
double xll, double yll, const string &srs /* = "" */) {
this->_initialize_raster_class();
m_raster2DData = data2d;
m_is2DRaster = true;
m_noDataValue = nodata;
m_srs = srs;
m_nCells = cols * rows;
m_nLyrs = nlayers;
m_headers[HEADER_RS_NCOLS] = cols;
m_headers[HEADER_RS_NROWS] = rows;
m_headers[HEADER_RS_XLL] = xll;
m_headers[HEADER_RS_YLL] = yll;
m_headers[HEADER_RS_CELLSIZE] = dx;
m_headers[HEADER_RS_NODATA] = nodata;
m_headers[HEADER_RS_LAYERS] = nlayers;
m_headers[HEADER_RS_CELLSNUM] = m_nCells;
}
template<typename T, typename MaskT>
clsRasterData<T, MaskT>::clsRasterData(const string &filename, bool calcPositions /* = true */,
clsRasterData<MaskT> *mask /* = nullptr */,
bool useMaskExtent /* = true */,
T defalutValue /* = (T) NODATA_VALUE */) {
this->ReadFromFile(filename, calcPositions, mask, useMaskExtent, defalutValue);
}
template<typename T, typename MaskT>
clsRasterData<T, MaskT> *clsRasterData<T, MaskT>::Init(const string &filename,
bool calcPositions /* = true */,
clsRasterData<MaskT> *mask /* = nullptr */,
bool useMaskExtent /* = true */,
T defalutValue /* = (T) NODATA_VALUE */) {
if (!_check_raster_files_exist(filename)) return nullptr;
return new clsRasterData<T, MaskT>(filename, calcPositions, mask, useMaskExtent, defalutValue);
}
template<typename T, typename MaskT>
clsRasterData<T, MaskT>::clsRasterData(vector<string> &filenames,
bool calcPositions /* = true */,
clsRasterData<MaskT> *mask /* = nullptr */,
bool useMaskExtent /* = true */,
T defalutValue /* = (T) NODATA_VALUE */) {
this->_initialize_raster_class();
if (filenames.empty()) { /// if filenames is empty
print_status("The filenames MUST have at least one raster file path!");
return;
}
if (!_check_raster_files_exist(filenames)) { /// if not all filenames are presented
print_status("Please make sure all file path existed!");
return;
}
if (filenames.size() == 1) { /// if filenames has only one file
if (!this->_construct_from_single_file(filenames[0], calcPositions, mask,
useMaskExtent, defalutValue)) {
return;
}
} else { /// construct from multi-layers file
m_nLyrs = (int) filenames.size();
/// 1. firstly, take the first layer as the main input, to calculate position index or
/// extract by mask if stated.
if (!this->_construct_from_single_file(filenames[0], calcPositions, mask,