-
Notifications
You must be signed in to change notification settings - Fork 0
/
GRIDINFORMER.py
1704 lines (1533 loc) · 82.1 KB
/
GRIDINFORMER.py
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
import math,re,sys,os,time
import random as RD
import time
import struct
try:
import netCDF4 as NC
except:
print("You no install netCDF4 for python")
print("So I do not import netCDF4")
try:
import numpy as NP
except:
print("You no install numpy")
print("Do not import numpy")
class GRIDINFORMATER:
"""
This object is the information of the input gridcells/array/map.
Using
.add_an_element to add an element/gridcell
.add_an_geo_element to add an element/gridcell
.create_resample_lat_lon to create a new map of lat and lon for resampling
.create_resample_map to create resample map as ARR_RESAMPLE_MAP
.create_reference_map to create ARR_REFERENCE_MAP to resample target map.
.export_reference_map to export ARR_REFERENCE_MAP into netCDF4 format
"""
STR_VALUE_INIT = "None"
NUM_VALUE_INIT = -9999.9
NUM_NULL = float("NaN")
ARR_RESAMPLE_X_LIM = []
ARR_RESAMPLE_Y_LIM = []
# FROM WRF: module_cam_shr_const_mod.f90
NUM_CONST_EARTH_R = 6.37122E6
NUM_CONST_PI = 3.14159265358979323846
def __init__(self, name="GRID", ARR_LAT=[], ARR_LON=[], NUM_NT=1, DIMENSIONS=2 ):
self.STR_NAME = name
self.NUM_DIMENSIONS = DIMENSIONS
self.NUM_LAST_INDEX = -1
self.ARR_GRID = []
self.NUM_NT = NUM_NT
self.ARR_LAT = ARR_LAT
self.ARR_LON = ARR_LON
self.ARR_RESAMPLE_MAP_PARA = { "EDGE": {"N" :-999, "S":-999, "E":-999, "W":-999 } }
if len(ARR_LAT) != 0 and len(ARR_LON) != 0:
NUM_ARR_NY_T1 = len(ARR_LAT)
NUM_ARR_NY_T2 = len(ARR_LON)
Y_T2 = len(ARR_LON)
NUM_ARR_NX_T1 = len(ARR_LAT[0])
NUM_ARR_NX_T2 = len(ARR_LON[0])
self.NUM_NX = NUM_ARR_NX_T1
self.NUM_NY = NUM_ARR_NY_T1
if NUM_ARR_NY_T1 - NUM_ARR_NY_T2 + NUM_ARR_NX_T1 - NUM_ARR_NX_T2 != 0:
print("The gridcell of LAT is {0:d}&{1:d}, and LON is {2:d}&{3:d} are not match"\
.format(NUM_ARR_NY_T1,NUM_ARR_NY_T2,NUM_ARR_NX_T1,NUM_ARR_NX_T2))
def index_map(self, ARR_IN=[], NUM_IN_NX=0, NUM_IN_NY=0):
if len(ARR_IN) == 0:
self.INDEX_MAP = [[ self.NUM_NULL for i in range(self.NUM_NX)] for j in range(self.NUM_NY)]
NUM_ALL_INDEX = len(self.ARR_GRID)
for n in range(NUM_ALL_INDEX):
self.INDEX_MAP[self.ARR_GRID[n]["INDEX_J"]][self.ARR_GRID[n]["INDEX_I"]] =\
self.ARR_GRID[n]["INDEX"]
else:
MAP_INDEX = [[ self.NUM_NULL for i in range(NUM_IN_NX)] for j in range(NUM_IN_NY)]
NUM_ALL_INDEX = len(ARR_IN)
for n in range(NUM_ALL_INDEX):
MAP_INDEX[ARR_IN[n]["INDEX_J"]][ARR_IN[n]["INDEX_I"]] = ARR_IN[n]["INDEX"]
return MAP_INDEX
def add_an_element(self, ARR_GRID, NUM_INDEX=0, STR_VALUE=STR_VALUE_INIT, NUM_VALUE=NUM_VALUE_INIT ):
""" Adding an element to an empty array """
OBJ_ELEMENT = {"INDEX" : NUM_INDEX, \
STR_VALUE : NUM_VALUE}
ARR_GRID.append(OBJ_ELEMENT)
def add_an_geo_element(self, ARR_GRID, NUM_INDEX=-999, NUM_J=0, NUM_I=0, \
NUM_NX = 0, NUM_NY = 0, NUM_NT=0, \
ARR_VALUE_STR=[], ARR_VALUE_NUM=[] ):
""" Adding an geological element to an empty array
The information for lat and lon of center, edge, and vertex will
be stored for further used.
"""
NUM_NVAR = len(ARR_VALUE_STR)
if NUM_NX == 0 or NUM_NY == 0:
NUM_NX = self.NUM_NX
NUM_NY = self.NUM_NY
if NUM_NT == 0:
NUM_NT = self.NUM_NT
NUM_CENTER_LON = self.ARR_LON[NUM_J][NUM_I]
NUM_CENTER_LAT = self.ARR_LAT[NUM_J][NUM_I]
if NUM_I == 0:
NUM_WE_LON = ( self.ARR_LON[NUM_J][NUM_I] - self.ARR_LON[NUM_J][NUM_I + 1] ) * 0.5
NUM_EW_LON = -1 * ( self.ARR_LON[NUM_J][NUM_I] - self.ARR_LON[NUM_J][NUM_I + 1] ) * 0.5
elif NUM_I == NUM_NX - 1:
NUM_WE_LON = -1 * ( self.ARR_LON[NUM_J][NUM_I] - self.ARR_LON[NUM_J][NUM_I - 1] ) * 0.5
NUM_EW_LON = ( self.ARR_LON[NUM_J][NUM_I] - self.ARR_LON[NUM_J][NUM_I - 1] ) * 0.5
else:
NUM_WE_LON = ( self.ARR_LON[NUM_J][NUM_I] - self.ARR_LON[NUM_J][NUM_I + 1] ) * 0.5
NUM_EW_LON = ( self.ARR_LON[NUM_J][NUM_I] - self.ARR_LON[NUM_J][NUM_I - 1] ) * 0.5
if NUM_J == 0:
NUM_SN_LAT = -1 * ( self.ARR_LAT[NUM_J][NUM_I] - self.ARR_LAT[NUM_J + 1][NUM_I ] ) * 0.5
NUM_NS_LAT = ( self.ARR_LAT[NUM_J][NUM_I] - self.ARR_LAT[NUM_J + 1][NUM_I ] ) * 0.5
elif NUM_J == NUM_NY - 1:
NUM_SN_LAT = ( self.ARR_LAT[NUM_J][NUM_I] - self.ARR_LAT[NUM_J - 1][NUM_I ] ) * 0.5
NUM_NS_LAT = -1 * ( self.ARR_LAT[NUM_J][NUM_I] - self.ARR_LAT[NUM_J - 1][NUM_I ] ) * 0.5
else:
NUM_SN_LAT = ( self.ARR_LAT[NUM_J][NUM_I] - self.ARR_LAT[NUM_J - 1][NUM_I ] ) * 0.5
NUM_NS_LAT = ( self.ARR_LAT[NUM_J][NUM_I] - self.ARR_LAT[NUM_J + 1][NUM_I ] ) * 0.5
ARR_NE = [ NUM_CENTER_LON + NUM_EW_LON , NUM_CENTER_LAT + NUM_NS_LAT ]
ARR_NW = [ NUM_CENTER_LON + NUM_WE_LON , NUM_CENTER_LAT + NUM_NS_LAT ]
ARR_SE = [ NUM_CENTER_LON + NUM_EW_LON , NUM_CENTER_LAT + NUM_SN_LAT ]
ARR_SW = [ NUM_CENTER_LON + NUM_WE_LON , NUM_CENTER_LAT + NUM_SN_LAT ]
if NUM_INDEX == -999:
NUM_INDEX = self.NUM_LAST_INDEX +1
self.NUM_LAST_INDEX += 1
OBJ_ELEMENT = {"INDEX" : NUM_INDEX,\
"INDEX_I" : NUM_I,\
"INDEX_J" : NUM_J,\
"CENTER" : {"LAT" : NUM_CENTER_LAT, "LON" : NUM_CENTER_LON},\
"VERTEX" : {"NE": ARR_NE, "SE": ARR_SE, "SW": ARR_SW, "NW": ARR_NW},\
"EDGE" : {"N": NUM_CENTER_LAT + NUM_NS_LAT,"S": NUM_CENTER_LAT + NUM_SN_LAT,\
"E": NUM_CENTER_LON + NUM_EW_LON,"W": NUM_CENTER_LON + NUM_WE_LON}}
if len(ARR_VALUE_STR) > 0:
for I, VAR in enumerate(ARR_VALUE_STR):
OBJ_ELEMENT[VAR] = [{ "VALUE" : 0.0} for t in range(NUM_NT) ]
if len(ARR_VALUE_NUM) == NUM_NVAR:
for T in range(NUM_NT):
OBJ_ELEMENT[VAR][T]["VALUE"] = ARR_VALUE_NUM[I][T]
ARR_GRID.append(OBJ_ELEMENT)
def add_an_geo_variable(self, ARR_GRID, NUM_INDEX=-999, NUM_J=0, NUM_I=0, NUM_NT=0,\
STR_VALUE=STR_VALUE_INIT, NUM_VALUE=NUM_VALUE_INIT ):
if NUM_INDEX == -999:
NUM_INDEX = self.INDEX_MAP[NUM_J][NUM_I]
if NUM_NT == 0:
NUM_NT = self.NUM_NT
ARR_GRID[NUM_INDEX][STR_VALUE] = {{"VALUE": NUM_VALUE } for t in range(NUM_NT)}
def create_resample_lat_lon(self, ARR_RANGE_LAT=[0,0],NUM_EDGE_LAT=0,\
ARR_RANGE_LON=[0,0],NUM_EDGE_LON=0 ):
self.NUM_GRIDS_LON = round((ARR_RANGE_LON[1] - ARR_RANGE_LON[0])/NUM_EDGE_LON)
self.NUM_GRIDS_LAT = round((ARR_RANGE_LAT[1] - ARR_RANGE_LAT[0])/NUM_EDGE_LAT)
self.ARR_LAT = [[ 0 for i in range(self.NUM_GRIDS_LON)] for j in range(self.NUM_GRIDS_LAT) ]
self.ARR_LON = [[ 0 for i in range(self.NUM_GRIDS_LON)] for j in range(self.NUM_GRIDS_LAT) ]
for j in range(self.NUM_GRIDS_LAT):
for i in range(self.NUM_GRIDS_LON):
NUM_LAT = ARR_RANGE_LAT[0] + NUM_EDGE_LAT * j
NUM_LON = ARR_RANGE_LON[0] + NUM_EDGE_LON * i
self.ARR_LON[j][i] = ARR_RANGE_LON[0] + NUM_EDGE_LON * i
self.ARR_LAT[j][i] = ARR_RANGE_LAT[0] + NUM_EDGE_LAT * j
def create_reference_map(self, MAP_TARGET, MAP_RESAMPLE, STR_TYPE="FIX", NUM_SHIFT=0.001, IF_PB=False):
"""Must input with OBJ_REFERENCE
WARNING: The edge of gridcells may not be included due to the unfinished algorithm
"""
self.ARR_REFERENCE_MAP = []
if STR_TYPE=="GRIDBYGEO":
NUM_OBJ_G_LEN = len(MAP_TARGET)
for OBJ_G in MAP_TARGET:
NUM_G_COOR = [OBJ_G["CENTER"]["LAT"], OBJ_G["CENTER"]["LON"]]
for OBJ_R in MAP_RESAMPLE:
NUM_CHK_IN_EW = (OBJ_R["EDGE"]["E"] - OBJ_G["CENTER"]["LON"]) *\
(OBJ_R["EDGE"]["W"] - OBJ_G["CENTER"]["LON"])
NUM_CHK_IN_SN = (OBJ_R["EDGE"]["N"] - OBJ_G["CENTER"]["LAT"]) *\
(OBJ_R["EDGE"]["S"] - OBJ_G["CENTER"]["LAT"])
if NUM_CHK_IN_EW == 0: NUM_CHK_IN_EW = (OBJ_R["EDGE"]["E"] + NUM_SHIFT - OBJ_G["CENTER"]["LON"]) *\
(OBJ_R["EDGE"]["W"] + NUM_SHIFT - OBJ_G["CENTER"]["LON"])
if NUM_CHK_IN_SN == 0: NUM_CHK_IN_SN = (OBJ_R["EDGE"]["E"] + NUM_SHIFT - OBJ_G["CENTER"]["LON"]) *\
(OBJ_R["EDGE"]["W"] + NUM_SHIFT - OBJ_G["CENTER"]["LON"])
if NUM_CHK_IN_EW < 0 and NUM_CHK_IN_SN < 0:
OBJ_ELEMENT = {"INDEX" : OBJ_G["INDEX"],\
"CENTER" : OBJ_G["CENTER"],\
"INDEX_REF" : OBJ_R["INDEX"],\
"INDEX_REF_I" : OBJ_R["INDEX_I"],\
"INDEX_REF_J" : OBJ_R["INDEX_J"],\
"CENTER_REF" : OBJ_R["CENTER"],\
}
self.ARR_REFERENCE_MAP.append(OBJ_ELEMENT)
break
if IF_PB: TOOLS.progress_bar(TOOLS.cal_loop_progress([OBJ_G["INDEX"]], [NUM_OBJ_G_LEN]), STR_DES="CREATING REFERENCE MAP")
elif STR_TYPE=="FIX":
NUM_OBJ_G_LEN = len(MAP_TARGET)
for OBJ_G in MAP_TARGET:
NUM_G_COOR = [OBJ_G["CENTER"]["LAT"], OBJ_G["CENTER"]["LON"]]
if self.ARR_RESAMPLE_MAP_PARA["EDGE"]["W"] == -999 or self.ARR_RESAMPLE_MAP_PARA["EDGE"]["E"] == -999:
NUM_CHK_EW_IN = -1
else:
NUM_CHK_EW_IN = (NUM_G_COOR[1] - self.ARR_RESAMPLE_MAP_PARA["EDGE"]["W"] ) * ( NUM_G_COOR[1] - self.ARR_RESAMPLE_MAP_PARA["EDGE"]["E"] )
if self.ARR_RESAMPLE_MAP_PARA["EDGE"]["N"] == -999 or self.ARR_RESAMPLE_MAP_PARA["EDGE"]["S"] == -999:
NUM_CHK_SN_IN = -1
else:
NUM_CHK_SN_IN = (NUM_G_COOR[0] - self.ARR_RESAMPLE_MAP_PARA["EDGE"]["S"] ) * ( NUM_G_COOR[0] - self.ARR_RESAMPLE_MAP_PARA["EDGE"]["N"] )
if NUM_CHK_EW_IN < 0 and NUM_CHK_SN_IN < 0:
for OBJ_R in MAP_RESAMPLE:
NUM_CHK_IN_EW = (OBJ_R["EDGE"]["E"] - OBJ_G["CENTER"]["LON"]) *\
(OBJ_R["EDGE"]["W"] - OBJ_G["CENTER"]["LON"])
NUM_CHK_IN_SN = (OBJ_R["EDGE"]["N"] - OBJ_G["CENTER"]["LAT"]) *\
(OBJ_R["EDGE"]["S"] - OBJ_G["CENTER"]["LAT"])
if NUM_CHK_IN_EW == 0: NUM_CHK_IN_EW = (OBJ_R["EDGE"]["E"] + NUM_SHIFT - OBJ_G["CENTER"]["LON"]) *\
(OBJ_R["EDGE"]["W"] + NUM_SHIFT - OBJ_G["CENTER"]["LON"])
if NUM_CHK_IN_SN == 0: NUM_CHK_IN_SN = (OBJ_R["EDGE"]["E"] + NUM_SHIFT - OBJ_G["CENTER"]["LON"]) *\
(OBJ_R["EDGE"]["W"] + NUM_SHIFT - OBJ_G["CENTER"]["LON"])
if NUM_CHK_IN_EW < 0 and NUM_CHK_IN_SN < 0:
OBJ_ELEMENT = {"INDEX" : OBJ_G["INDEX"],\
"INDEX_I" : OBJ_G["INDEX_I"],\
"INDEX_J" : OBJ_G["INDEX_J"],\
"CENTER" : OBJ_G["CENTER"],\
"INDEX_REF" : OBJ_R["INDEX"],\
"INDEX_REF_I" : OBJ_R["INDEX_I"],\
"INDEX_REF_J" : OBJ_R["INDEX_J"],\
"CENTER_REF" : OBJ_R["CENTER"],\
}
self.ARR_REFERENCE_MAP.append(OBJ_ELEMENT)
break
if IF_PB: TOOLS.progress_bar(TOOLS.cal_loop_progress([OBJ_G["INDEX"]], [NUM_OBJ_G_LEN]), STR_DES="CREATING REFERENCE MAP")
def export_grid_map(self, ARR_GRID_IN, STR_DIR, STR_FILENAME, ARR_VAR_STR=[],\
ARR_VAR_ITEM=["MEAN", "MEDIAN", "MIN", "MAX", "P95", "P75", "P25", "P05"],\
NUM_NX=0, NUM_NY=0, NUM_NT=0, STR_TYPE="netCDF4", IF_PB=False ):
TIME_NOW = time.gmtime()
STR_DATE_NOW = "{0:04d}-{1:02d}-{2:02d}".format(TIME_NOW.tm_year, TIME_NOW.tm_mon, TIME_NOW.tm_mday)
STR_TIME_NOW = "{0:04d}:{1:02d}:{2:02d}".format(TIME_NOW.tm_hour, TIME_NOW.tm_min, TIME_NOW.tm_sec)
if NUM_NX==0: NUM_NX = self.NUM_NX
if NUM_NY==0: NUM_NY = self.NUM_NY
if NUM_NT==0: NUM_NT = self.NUM_NT
if STR_TYPE == "netCDF4":
NCDF4_DATA = NC.Dataset("{0:s}/{1:s}".format(STR_DIR, STR_FILENAME), 'w', format="NETCDF4")
# CREATE ATTRIBUTEs:
NCDF4_DATA.description = \
"The grid information in netCDF4"
NCDF4_DATA.history = "Create on {0:s} at {1:s}".format(STR_DATE_NOW, STR_TIME_NOW)
# CREATE DIMENSIONs:
NCDF4_DATA.createDimension("Y" , NUM_NY )
NCDF4_DATA.createDimension("X" , NUM_NX )
NCDF4_DATA.createDimension("Time" , NUM_NT )
NCDF4_DATA.createDimension("Values", None )
# CREATE BASIC VARIABLES:
NCDF4_DATA.createVariable("INDEX", "i4", ("Y", "X"))
NCDF4_DATA.createVariable("INDEX_J", "i4", ("Y", "X"))
NCDF4_DATA.createVariable("INDEX_I", "i4", ("Y", "X"))
NCDF4_DATA.createVariable("CENTER_LON", "f8", ("Y", "X"))
NCDF4_DATA.createVariable("CENTER_LAT", "f8", ("Y", "X"))
# CREATE GROUP for Variables:
for VAR in ARR_VAR_STR:
NCDF4_DATA.createGroup(VAR)
for ITEM in ARR_VAR_ITEM:
if ITEM == "VALUE" :
NCDF4_DATA.groups[VAR].createVariable(ITEM, "f8", ("Time", "Y", "X", "Values"))
else:
NCDF4_DATA.groups[VAR].createVariable(ITEM, "f8", ("Time", "Y", "X"))
# WRITE IN VARIABLE
for V in ["INDEX", "INDEX_J", "INDEX_I"]:
map_in = self.convert_grid2map(ARR_GRID_IN, V, NX=NUM_NX, NY=NUM_NY, NC_TYPE="INT")
for n in range(len(map_in)):
NCDF4_DATA.variables[V][n] = map_in[n]
for V1 in ["CENTER"]:
for V2 in ["LON", "LAT"]:
map_in = self.convert_grid2map(ARR_GRID_IN, V1, V2, NX=NUM_NX, NY=NUM_NY, NC_TYPE="FLOAT")
for n in range(len(map_in)):
NCDF4_DATA.variables["{0:s}_{1:s}".format(V1, V2)][n] = map_in[n]
for V1 in ARR_VAR_STR:
for V2 in ARR_VAR_ITEM:
map_in = self.convert_grid2map(ARR_GRID_IN, V1, V2, NX=NUM_NX, NY=NUM_NY, NT=NUM_NT)
for n in range(len(map_in)):
NCDF4_DATA.groups[V1].variables[V2][n] = map_in[n]
NCDF4_DATA.close()
def export_grid(ARR_GRID_IN, STR_DIR, STR_FILENAME, ARR_VAR_STR=[], STR_GRID_NAME="",\
STR_TYPE="netCDF4", IF_PB=False ):
TIME_NOW = time.gmtime()
STR_DATE_NOW = "{0:04d}-{1:02d}-{2:02d}".format(TIME_NOW.tm_year, TIME_NOW.tm_mon, TIME_NOW.tm_mday)
STR_TIME_NOW = "{0:04d}:{1:02d}:{2:02d}".format(TIME_NOW.tm_hour, TIME_NOW.tm_min, TIME_NOW.tm_sec)
if STR_GRID_NAME == "":
STR_GRID_NAME = [ k for k,v in locals().items() if v == ARR_GRID_IN][0]
if STR_TYPE == "netCDF4":
NCDF4_DATA = Dataset("{0:s}/{1:s}".format(STR_DIR, STR_FILENAME), 'a', format="NETCDF4")
# CREATE ATTRIBUTEs:
NCDF4_DATA.description = \
"The grid information in netCDF4, the grid information will be based on the input grids. "
NCDF4_DATA.history = "Create on {0:s} at {1:s}".format(STR_DATE_NOW, STR_TIME_NOW)
# CREATE THE DIMENSIONS:
#numGrids = len(ARR_GRID_IN)
try:
NCDF4_DATA.createDimension("index", None )
except:
print("Dimension existed")
# CREATE GROUP for Variables:
try:
group = NCDF4_DATA.createGroup(STR_GRID_NAME)
except:
print("Group existed, not creating the group: {0:s}".format(STR_GRID_NAME))
group = NCDF4_DATA.group[STR_GRID_NAME]
# CREATE BASIC VARIABLES:
arrVarOut = []
arrVars = [ k for k in ARR_GRID_IN[0].keys() ]
for key in arrVars:
try:
arrSubVar = ARR_GRID_IN[0][key].keys()
for subkey in arrSubVar:
arrVarOut.append("{0:s}_sub_{1:s}".format(key,subkey))
except:
arrVarOut.append(key)
try:
for key in arrVarOut:
group.createVariable( key, "f8", ("index"))
except:
print("Variables existed")
# WRITE IN VARIABLE
NUM_LEN_GRID = len(ARR_GRID_IN)
for IND, OBJ in enumerate(ARR_GRID_IN):
for key in arrVarOut:
if len(re.findall("_sub_", key)) == 0:
v_in = group.variables[key]
v_in[IND] = OBJ[key]
else:
v_in = group.variables[key]
key1, key2 = re.split("_sub_", key)
v_in[IND] = OBJ[key1][key2]
#print(key1, key2, IND, OBJ[key1][key2] )
if IF_PB: TOOLS.progress_bar(IND/(NUM_LEN_GRID-1), STR_DES="WRITING PROGRESS")
NCDF4_DATA.close()
def import_grid(STR_DIR, STR_FILENAME, STR_GRID_NAME="",\
STR_TYPE="netCDF4", IF_PB=False ):
NC_IN = Dataset("{0:s}/{1:s}".format(STR_DIR, STR_FILENAME), 'r', format="NETCDF4")
group = NC_IN.groups[STR_GRID_NAME]
ARR_GRIDS = []
numGrid_size = 0
for ind in range(NC_IN.dimensions["index"].size):
chk = group.variables["INDEX"][ind].mask
value = int(group.variables["INDEX"][ind])
if chk:
break
else:
numGrid_size+=1
Obj_In = {"INDEX" : value }
for Key in group.variables:
v_in = group.variables[Key]
if len(re.split("_sub_",Key)) == 2:
key1, key2 = re.split("_sub_",Key)
Obj_In[key1] = {key2 : float(v_in[value])}
elif len(re.split("_sub_",Key)) == 0:
Obj_In[Key] = float(v_in[value])
ARR_GRIDS.append(Obj_In)
TOOLS.progress_bar(ind/NC_IN.dimensions["index"].size)
return ARR_GRIDS
def export_reference_map(self, STR_DIR, STR_FILENAME, STR_TYPE="netCDF4", IF_PB=False, IF_PARALLEL=False ):
TIME_NOW = time.gmtime()
self.STR_DATE_NOW = "{0:04d}-{1:02d}-{2:02d}".format(TIME_NOW.tm_year, TIME_NOW.tm_mon, TIME_NOW.tm_mday)
self.STR_TIME_NOW = "{0:02d}:{1:02d}:{2:02d}".format(TIME_NOW.tm_hour, TIME_NOW.tm_min, TIME_NOW.tm_sec)
STR_INPUT_FILENAME = "{0:s}/{1:s}".format(STR_DIR, STR_FILENAME)
if STR_TYPE == "netCDF4":
IF_FILECHK = os.path.exists(STR_INPUT_FILENAME)
if IF_FILECHK:
NCDF4_DATA = NC.Dataset(STR_INPUT_FILENAME, 'a', format="NETCDF4", parallel=IF_PARALLEL)
INDEX = NCDF4_DATA.variables["INDEX" ]
INDEX_J = NCDF4_DATA.variables["INDEX_J" ]
INDEX_I = NCDF4_DATA.variables["INDEX_I" ]
CENTER_LON = NCDF4_DATA.variables["CENTER_LON" ]
CENTER_LAT = NCDF4_DATA.variables["CENTER_LAT" ]
INDEX_REF = NCDF4_DATA.variables["INDEX_REF" ]
INDEX_REF_J = NCDF4_DATA.variables["INDEX_REF_J" ]
INDEX_REF_I = NCDF4_DATA.variables["INDEX_REF_I" ]
CENTER_REF_LON = NCDF4_DATA.variables["CENTER_REF_LON" ]
CENTER_REF_LAT = NCDF4_DATA.variables["CENTER_REF_LAT" ]
else:
NCDF4_DATA = NC.Dataset(STR_INPUT_FILENAME, 'w', format="NETCDF4", parallel=IF_PARALLEL)
# CREATE ATTRIBUTEs:
NCDF4_DATA.description = \
"The netCDF4 version of reference map which contains grid information for resampling"
NCDF4_DATA.history = "Create on {0:s} at {1:s}".format(self.STR_DATE_NOW, self.STR_TIME_NOW)
# CREATE DIMENSIONs:
NCDF4_DATA.createDimension("Y",self.NUM_NY)
NCDF4_DATA.createDimension("X",self.NUM_NX)
# CREATE_VARIABLES:
INDEX = NCDF4_DATA.createVariable("INDEX", "i4", ("Y", "X"))
INDEX_J = NCDF4_DATA.createVariable("INDEX_J", "i4", ("Y", "X"))
INDEX_I = NCDF4_DATA.createVariable("INDEX_I", "i4", ("Y", "X"))
CENTER_LON = NCDF4_DATA.createVariable("CENTER_LON", "f8", ("Y", "X"))
CENTER_LAT = NCDF4_DATA.createVariable("CENTER_LAT", "f8", ("Y", "X"))
INDEX_REF = NCDF4_DATA.createVariable("INDEX_REF", "i4", ("Y", "X"))
INDEX_REF_J = NCDF4_DATA.createVariable("INDEX_REF_J", "i4", ("Y", "X"))
INDEX_REF_I = NCDF4_DATA.createVariable("INDEX_REF_I", "i4", ("Y", "X"))
CENTER_REF_LON = NCDF4_DATA.createVariable("CENTER_REF_LON", "f8", ("Y", "X"))
CENTER_REF_LAT = NCDF4_DATA.createVariable("CENTER_REF_LAT", "f8", ("Y", "X"))
NUM_TOTAL_OBJ = len(self.ARR_REFERENCE_MAP)
NUM_MAX_I = self.NUM_NX
for OBJ in self.ARR_REFERENCE_MAP:
j = OBJ["INDEX_J"]
i = OBJ["INDEX_I"]
INDEX[j,i] = OBJ["INDEX"]
INDEX_J[j,i] = OBJ["INDEX_J"]
INDEX_I[j,i] = OBJ["INDEX_I"]
INDEX_REF[j,i] = OBJ["INDEX_REF"]
INDEX_REF_J[j,i] = OBJ["INDEX_REF_J"]
INDEX_REF_I[j,i] = OBJ["INDEX_REF_I"]
CENTER_LON [j,i] = OBJ["CENTER"]["LON"]
CENTER_LAT [j,i] = OBJ["CENTER"]["LAT"]
CENTER_REF_LON [j,i] = OBJ["CENTER_REF"]["LON"]
CENTER_REF_LAT [j,i] = OBJ["CENTER_REF"]["LAT"]
if IF_PB: TOOLS.progress_bar((i+j*NUM_MAX_I)/float(NUM_TOTAL_OBJ), STR_DES="Exporting")
NCDF4_DATA.close()
def import_reference_map(self, STR_DIR, STR_FILENAME, ARR_X_RANGE=[], ARR_Y_RANGE=[], STR_TYPE="netCDF4", IF_PB=False):
self.ARR_REFERENCE_MAP = []
self.NUM_MAX_INDEX_RS = 0
self.NUM_MIN_INDEX_RS = 999
if len(ARR_X_RANGE) != 0:
self.I_MIN = ARR_X_RANGE[0]
self.I_MAX = ARR_X_RANGE[1]
else:
self.I_MIN = 0
self.I_MAX = self.REFERENCE_MAP_NX
if len(ARR_Y_RANGE) != 0:
self.J_MIN = ARR_Y_RANGE[0]
self.J_MAX = ARR_Y_RANGE[1]
else:
self.J_MIN = 0
self.J_MAX = self.REFERENCE_MAP_NY
if STR_TYPE == "netCDF4":
NCDF4_DATA = NC.Dataset("{0:s}/{1:s}".format(STR_DIR, STR_FILENAME), 'r', format="NETCDF4")
# READ DIMENSIONs:
self.REFERENCE_MAP_NY = NCDF4_DATA.dimensions["Y"].size
self.REFERENCE_MAP_NX = NCDF4_DATA.dimensions["X"].size
# CREATE_VARIABLES:
INDEX = NCDF4_DATA.variables["INDEX" ]
INDEX_J = NCDF4_DATA.variables["INDEX_J" ]
INDEX_I = NCDF4_DATA.variables["INDEX_I" ]
CENTER_LON = NCDF4_DATA.variables["CENTER_LON" ]
CENTER_LAT = NCDF4_DATA.variables["CENTER_LAT" ]
INDEX_REF = NCDF4_DATA.variables["INDEX_REF" ]
INDEX_REF_J = NCDF4_DATA.variables["INDEX_REF_J" ]
INDEX_REF_I = NCDF4_DATA.variables["INDEX_REF_I" ]
CENTER_REF_LON = NCDF4_DATA.variables["CENTER_REF_LON" ]
CENTER_REF_LAT = NCDF4_DATA.variables["CENTER_REF_LAT" ]
for j in range(self.J_MIN, self.J_MAX):
for i in range(self.I_MIN, self.I_MAX):
OBJ_ELEMENT = {"INDEX" : 0 ,\
"INDEX_I" : 0 ,\
"INDEX_J" : 0 ,\
"CENTER" : {"LAT": 0.0, "LON": 0.0} ,\
"INDEX_REF" : 0 ,\
"INDEX_REF_I" : 0 ,\
"INDEX_REF_J" : 0 ,\
"CENTER_REF" : {"LAT": 0.0, "LON": 0.0} }
if INDEX [j][i] != None:
OBJ_ELEMENT["INDEX"] = INDEX [j][i]
OBJ_ELEMENT["INDEX_J"] = INDEX_J [j][i]
OBJ_ELEMENT["INDEX_I"] = INDEX_I [j][i]
OBJ_ELEMENT["INDEX_REF"] = INDEX_REF [j][i]
OBJ_ELEMENT["INDEX_REF_J"] = INDEX_REF_J [j][i]
OBJ_ELEMENT["INDEX_REF_I"] = INDEX_REF_I [j][i]
OBJ_ELEMENT["CENTER"]["LAT"] = CENTER_LAT [j][i]
OBJ_ELEMENT["CENTER"]["LON"] = CENTER_LON [j][i]
OBJ_ELEMENT["CENTER_REF"]["LAT"] = CENTER_REF_LAT[j][i]
OBJ_ELEMENT["CENTER_REF"]["LON"] = CENTER_REF_LON[j][i]
else:
OBJ_ELEMENT["INDEX"] = INDEX [j][i]
OBJ_ELEMENT["INDEX_I"] = INDEX_J [j][i]
OBJ_ELEMENT["INDEX_J"] = INDEX_I [j][i]
OBJ_ELEMENT["INDEX_REF"] = -999
OBJ_ELEMENT["INDEX_REF_J"] = -999
OBJ_ELEMENT["INDEX_REF_I"] = -999
OBJ_ELEMENT["CENTER"]["LAT"] = CENTER_LAT [j][i]
OBJ_ELEMENT["CENTER"]["LON"] = CENTER_LON [j][i]
OBJ_ELEMENT["CENTER_REF"]["LAT"] = -999
OBJ_ELEMENT["CENTER_REF"]["LON"] = -999
self.ARR_REFERENCE_MAP.append(OBJ_ELEMENT)
self.NUM_MIN_INDEX_RS = min(self.NUM_MIN_INDEX_RS, INDEX_REF[j][i])
self.NUM_MAX_INDEX_RS = max(self.NUM_MAX_INDEX_RS, INDEX_REF[j][i])
if IF_PB: TOOLS.progress_bar((j - self.J_MIN + 1)/float(self.J_MAX - self.J_MIN), STR_DES="IMPORTING")
if self.NUM_MIN_INDEX_RS == 0:
self.NUM_MAX_RS = self.NUM_MAX_INDEX_RS + 1
NCDF4_DATA.close()
def create_resample_map(self, ARR_REFERENCE_MAP=[], ARR_VARIABLES=["Value"], ARR_GRID_IN=[],\
IF_PB=False, NUM_NT=0, NUM_NX=0, NUM_NY=0, NUM_NULL=-9999.999):
if NUM_NT == 0:
NUM_NT = self.NUM_NT
if NUM_NX == 0:
NUM_NX = self.NUM_NX
if NUM_NY == 0:
NUM_NY = self.NUM_NY
if len(ARR_REFERENCE_MAP) == 0:
self.ARR_RESAMPLE_OUT = []
self.ARR_RESAMPLE_OUT_PARA = {"EDGE": {"N": 0.0,"S": 0.0,"E": 0.0,"W": 0.0}}
NUM_END_J = self.NUM_GRIDS_LAT - 1
NUM_END_I = self.NUM_GRIDS_LON - 1
ARR_EMPTY = [float("NaN") for n in range(self.NUM_NT)]
for J in range(self.NUM_GRIDS_LAT):
for I in range(self.NUM_GRIDS_LON):
NUM_IND = I + J * self.NUM_GRIDS_LON
self.add_an_geo_element(self.ARR_RESAMPLE_OUT, NUM_INDEX=NUM_IND, NUM_J=J, NUM_I=I, \
NUM_NX= self.NUM_GRIDS_LON, NUM_NY= self.NUM_GRIDS_LAT,\
ARR_VALUE_STR=ARR_VARIABLES, NUM_NT=NUM_NT)
self.ARR_RESAMPLE_MAP_PARA["EDGE"]["N"] = max( self.ARR_LAT[NUM_END_J][0], self.ARR_LAT[NUM_END_J][NUM_END_I] )
self.ARR_RESAMPLE_MAP_PARA["EDGE"]["S"] = min( self.ARR_LAT[0][0], self.ARR_LAT[0][NUM_END_I] )
self.ARR_RESAMPLE_MAP_PARA["EDGE"]["W"] = min( self.ARR_LAT[0][0], self.ARR_LAT[NUM_END_J][0] )
self.ARR_RESAMPLE_MAP_PARA["EDGE"]["E"] = max( self.ARR_LAT[0][NUM_END_I], self.ARR_LAT[NUM_END_J][NUM_END_I] )
self.NUM_MAX_INDEX_RS = NUM_IND
else:
if ARR_GRID_IN == []: ARR_GRID_IN = self.ARR_GRID
self.ARR_RESAMPLE_OUT = [ {} for n in range(NUM_NX * NUM_NY)]
for IND in range(len(self.ARR_RESAMPLE_OUT)):
for VAR in ARR_VARIABLES:
self.ARR_RESAMPLE_OUT[IND][VAR] = [{"VALUE" : []} for T in range(NUM_NT) ]
#for IND in range(len(ARR_REFERENCE_MAP)):
for IND in range(len(ARR_GRID_IN)):
R_IND = ARR_REFERENCE_MAP[IND]["INDEX_REF"]
R_J = ARR_REFERENCE_MAP[IND]["INDEX_REF_J"]
R_I = ARR_REFERENCE_MAP[IND]["INDEX_REF_I"]
R_IND_FIX = TOOLS.fix_ind(R_IND, R_J, R_I, ARR_XRANGE=self.ARR_RESAMPLE_LIM_X, ARR_YRANGE=self.ARR_RESAMPLE_LIM_Y, NX=NUM_NX, NY=NUM_NY)
if R_IND != None:
for VAR in ARR_VARIABLES:
for T in range(NUM_NT):
#print("R_IND:{0:d}, T:{1:d}, IND:{2:d} ".format(R_IND, T, IND))
NUM_VAL_IN = ARR_GRID_IN[IND][VAR][T]["VALUE"]
self.ARR_RESAMPLE_OUT[R_IND][VAR][T]["VALUE"].append(NUM_VAL_IN)
self.ARR_RESAMPLE_OUT[R_IND]["INDEX"] = ARR_REFERENCE_MAP[IND]["INDEX_REF"]
self.ARR_RESAMPLE_OUT[R_IND]["INDEX_J"] = ARR_REFERENCE_MAP[IND]["INDEX_REF_J"]
self.ARR_RESAMPLE_OUT[R_IND]["INDEX_I"] = ARR_REFERENCE_MAP[IND]["INDEX_REF_I"]
self.ARR_RESAMPLE_OUT[R_IND]["CENTER"] = {"LAT": 0.0, "LON": 0.0 }
self.ARR_RESAMPLE_OUT[R_IND]["CENTER"]["LAT"] = ARR_REFERENCE_MAP[IND]["CENTER"]["LAT"]
self.ARR_RESAMPLE_OUT[R_IND]["CENTER"]["LON"] = ARR_REFERENCE_MAP[IND]["CENTER"]["LON"]
if IF_PB: TOOLS.progress_bar(TOOLS.cal_loop_progress([IND], [len(ARR_GRID_IN)]), STR_DES="RESAMPLING PROGRESS")
def cal_resample_map(self, ARR_VARIABLES, ARR_GRID_IN=[], NUM_NT=0, IF_PB=False, \
DIC_PERCENTILE={ "P05": 0.05, "P10": 0.1, "P25": 0.25, "P75": 0.75, "P90": 0.90, "P95": 0.95}, NUM_NULL=-9999.999):
if NUM_NT == 0:
NUM_NT = self.NUM_NT
NUM_RS_OUT_LEN = len(self.ARR_RESAMPLE_OUT)
for IND in range(NUM_RS_OUT_LEN):
for VAR in ARR_VARIABLES:
for T in range(NUM_NT):
ARR_IN = self.ARR_RESAMPLE_OUT[IND][VAR][T]["VALUE"]
if len(ARR_IN) > 0:
ARR_IN.sort()
NUM_ARR_LEN = len(ARR_IN)
NUM_ARR_MEAN = sum(ARR_IN) / float(NUM_ARR_LEN)
NUM_ARR_S2SUM = 0
if math.fmod(NUM_ARR_LEN,2) == 1:
NUM_MPOS = [int((NUM_ARR_LEN-1)/2.0), int((NUM_ARR_LEN-1)/2.0)]
else:
NUM_MPOS = [int(NUM_ARR_LEN/2.0) , int(NUM_ARR_LEN/2.0 -1) ]
self.ARR_RESAMPLE_OUT[IND][VAR][T]["MIN"] = min(ARR_IN)
self.ARR_RESAMPLE_OUT[IND][VAR][T]["MAX"] = max(ARR_IN)
self.ARR_RESAMPLE_OUT[IND][VAR][T]["MEAN"] = NUM_ARR_MEAN
self.ARR_RESAMPLE_OUT[IND][VAR][T]["MEDIAN"] = ARR_IN[NUM_MPOS[0]] *0.5 + ARR_IN[NUM_MPOS[1]] *0.5
for STVA in DIC_PERCENTILE:
self.ARR_RESAMPLE_OUT[IND][VAR][T][STVA] = ARR_IN[ round(NUM_ARR_LEN * DIC_PERCENTILE[STVA])-1]
for VAL in ARR_IN:
NUM_ARR_S2SUM += (VAL - NUM_ARR_MEAN)**2
self.ARR_RESAMPLE_OUT[IND][VAR][T]["STD"] = (NUM_ARR_S2SUM / max(1, NUM_ARR_LEN-1))**0.5
if IF_PB: TOOLS.progress_bar(TOOLS.cal_loop_progress([IND], [NUM_RS_OUT_LEN]), STR_DES="RESAMPLING CALCULATION")
def convert_grid2map(self, ARR_GRID_IN, STR_VAR, STR_VAR_TYPE="", NX=0, NY=0, NT=0, IF_PB=False, NC_TYPE=""):
if NC_TYPE == "INT":
if NT == 0:
ARR_OUT = NP.empty([NY, NX], dtype=NP.int8)
else:
ARR_OUT = NP.empty([NT, NY, NX], dtype=NP.int8)
elif NC_TYPE == "FLOAT":
if NT == 0:
ARR_OUT = NP.empty([NY, NX], dtype=NP.float64)
else:
ARR_OUT = NP.empty([NT, NY, NX], dtype=NP.float64)
else:
if NT == 0:
ARR_OUT = [[ self.NUM_NULL for i in range(NX)] for j in range(NY) ]
else:
ARR_OUT = [[[ self.NUM_NULL for i in range(NX)] for j in range(NY) ] for t in range(NT)]
if STR_VAR_TYPE == "":
for I, GRID in enumerate(ARR_GRID_IN):
if GRID["INDEX"] != -999:
if NT == 0:
#print(GRID["INDEX_J"], GRID["INDEX_I"], GRID[STR_VAR])
ARR_OUT[ GRID["INDEX_J"] ][ GRID["INDEX_I"] ] = GRID[STR_VAR]
else:
for T in range(NT):
ARR_OUT[T][ GRID["INDEX_J"] ][ GRID["INDEX_I"] ] = GRID[STR_VAR][T]
if IF_PB==True: TOOLS.progress_bar(((I+1)/(len(ARR_GRID_IN))))
else:
for I, GRID in enumerate(ARR_GRID_IN):
if GRID["INDEX"] != -999:
if NT == 0:
ARR_OUT[ GRID["INDEX_J"] ][ GRID["INDEX_I"] ] = GRID[STR_VAR][STR_VAR_TYPE]
else:
for T in range(NT):
ARR_OUT[T][ GRID["INDEX_J"] ][ GRID["INDEX_I"] ] = GRID[STR_VAR][T][STR_VAR_TYPE]
if IF_PB==True: TOOLS.progress_bar(((I+1)/(len(ARR_GRID_IN))))
return ARR_OUT
def mask_grid(self, ARR_GRID_IN, STR_VAR, STR_VAR_TYPE, NUM_NT=0, STR_MASK="MASK",\
ARR_NUM_DTM=[0,1,2], ARR_NUM_DTM_RANGE=[0,1]):
if NUM_NT == 0:
NUM_NT= self.NUM_NT
for IND, GRID in enumerate(ARR_GRID_IN):
for T in range(NUM_NT):
NUM_DTM = GEO_TOOLS.mask_dtm(GRID[STR_VAR][T][STR_VAR_TYPE], ARR_NUM_DTM=ARR_NUM_DTM, ARR_NUM_DTM_RANGE=ARR_NUM_DTM_RANGE)
ARR_GRID_IN[IND][STR_VAR][T][STR_MASK] = NUM_DTM
class MATH_TOOLS:
""" Some math tools that help us to calculate.
gau_kde: kernel density estimator by Gaussian Function
standard_dev: The Standard deviation
"""
def GaussJordanEli(arr_in):
num_ydim = len(arr_in)
num_xdim = len(arr_in[0])
arr_out = arr_in
if num_ydim -num_xdim == 0 or num_xdim - num_ydim == 1:
arr_i = NP.array([[0.0 for j in range(num_ydim)] for i in range(num_ydim)])
for ny in range(num_ydim):
arr_i[ny][ny] = 1.0
#print(arr_i)
for nx in range(num_xdim):
for ny in range(nx+1, num_ydim):
arr_i [ny] = arr_i [ny] - arr_i [nx] * arr_out[ny][nx] / float(arr_out[nx][nx])
arr_out[ny] = arr_out[ny] - arr_out[nx] * arr_out[ny][nx] / float(arr_out[nx][nx])
if num_xdim - num_ydim == 1:
for nx in range(num_xdim-1,-1,-1):
for ny in range(num_ydim-1,nx, -1):
print(nx,ny)
arr_i [nx] = arr_i [nx] - arr_i [ny] * arr_out[nx][ny] / float(arr_out[ny][ny])
arr_out[nx] = arr_out[nx] - arr_out[ny] * arr_out[nx][ny] / float(arr_out[ny][ny])
else:
for nx in range(num_xdim,-1,-1):
for ny in range(num_ydim-1, nx, -1):
print(nx,ny)
arr_i [nx] = arr_i [nx] - arr_i [ny] * arr_out[nx][ny] / float(arr_out[ny][ny])
arr_out[nx] = arr_out[nx] - arr_out[ny] * arr_out[nx][ny] / float(arr_out[ny][ny])
if num_xdim - num_ydim == 1:
arr_sol = [0.0 for n in range(num_ydim)]
for ny in range(num_ydim):
arr_sol[ny] = arr_out[ny][num_xdim-1]/arr_out[ny][ny]
return arr_out, arr_i, arr_sol
else:
return arr_out, arr_i
else:
print("Y dim: {0:d}, X dim: {1:d}: can not apply Gaussian-Jordan".format(num_ydim, num_xdim))
return [0]
def finding_XM_LSM(arr_in1, arr_in2, m=2):
# Finding the by least square method
arr_out=[[0.0 for i in range(m+2)] for j in range(m+1)]
arr_x_power_m = [0.0 for i in range(m+m+1)]
arr_xy_power_m = [0.0 for i in range(m+1)]
for n in range(len(arr_x_power_m)):
for x in range(len(arr_in1)):
arr_x_power_m[n] += arr_in1[x] ** n
for n in range(len(arr_xy_power_m)):
for x in range(len(arr_in1)):
arr_xy_power_m[n] += arr_in1[x] ** n * arr_in2[x]
for j in range(m+1):
for i in range(j,j+m+1):
arr_out[j][i-j] = arr_x_power_m[i]
arr_out[j][m+1] = arr_xy_power_m[j]
return arr_out
def cal_modelperform (arr_obs , arr_sim , num_empty=-999.999):
# Based on Vazquez et al. 2002 (Hydrol. Process.)
num_arr = len(arr_obs)
num_n_total = num_arr
num_sum = 0
num_obs_sum = 0
for n in range( num_arr ):
if math.isnan(arr_obs[n]) or arr_obs[n] == num_empty:
num_n_total += -1
else:
num_sum = num_sum + ( arr_sim[n] - arr_obs[n] ) ** 2
num_obs_sum = num_obs_sum + arr_obs[n]
if num_n_total == 0 or num_obs_sum == 0:
RRMSE = -999.999
RMSE = -999.999
obs_avg = -999.999
else:
RRMSE = ( num_sum / num_n_total ) ** 0.5 * ( num_n_total / num_obs_sum )
RMSE = ( num_sum / num_n_total ) ** 0.5
obs_avg = num_obs_sum / num_n_total
num_n_total = num_arr
oo_sum = 0
po_sum = 0
for nn in range( num_arr ):
if math.isnan(arr_obs[nn]) or arr_obs[nn] == num_empty:
num_n_total = num_n_total - 1
else:
oo_sum = oo_sum + ( arr_obs[nn] - obs_avg ) ** 2
po_sum = po_sum + ( arr_sim[nn] - arr_obs[nn] ) ** 2
if num_n_total == 0 or oo_sum * po_sum == 0:
EF = -999.999
CD = -999.999
else:
EF = ( oo_sum - po_sum ) / oo_sum
CD = oo_sum / po_sum
return RRMSE,EF,CD,RMSE, num_arr
def cal_kappa(ARR_IN, NUM_n=0, NUM_N=0, NUM_k=0):
""" Fleiss' kappa
Mustt input with ARR_IN in the following format:
ARR_IN = [ [ NUM for k in range(catalogue)] for N in range(Subjects)]
Additional parameters: NUM_n is the number of raters (e.g. sim and obs results)
Additional parameters: NUM_N is the number of subjects (e.g the outputs
Additional parameters: NUM_k is the number of catalogue (e.g. results )
"""
if NUM_N == 0:
NUM_N = len(ARR_IN)
if NUM_n == 0:
NUM_n = sum(ARR_IN[0])
if NUM_k == 0:
NUM_k = len(ARR_IN[0])
ARR_p_out = [ 0 for n in range(NUM_k)]
ARR_P_OUT = [ 0 for n in range(NUM_N)]
for N in range(NUM_N):
for k in range(NUM_k):
ARR_p_out[k] += ARR_IN[N][k]
ARR_P_OUT[N] += ARR_IN[N][k] ** 2
ARR_P_OUT[N] -= NUM_n
ARR_P_OUT[N] = ARR_P_OUT[N] * (1./(NUM_n *(NUM_n - 1)))
for k in range(NUM_k):
ARR_p_out[k] = ARR_p_out[k] / (NUM_N * NUM_n)
NUM_P_BAR = 0
for N in range(NUM_N):
NUM_P_BAR += ARR_P_OUT[N]
NUM_P_BAR = NUM_P_BAR / float(NUM_N)
NUM_p_bar = 0
for k in ARR_p_out:
NUM_p_bar += k **2
return (NUM_P_BAR - NUM_p_bar) / (1 - NUM_p_bar)
def gau_kde(ARR_IN_X, ARR_IN_I, NUM_BW=0.1 ):
NUM_SUM = 0.
NUM_LENG = len(ARR_IN_X)
ARR_OUT = [ 0. for n in range(NUM_LENG)]
for IND_J, J in enumerate(ARR_IN_X):
NUM_SUM = 0.0
for I in ARR_IN_I:
NUM_SUM += 1 / (2 * math.pi)**0.5 * math.e ** (-0.5 * ((J-I)/NUM_BW) ** 2 )
ARR_OUT[IND_J] = NUM_SUM / len(ARR_IN_I) / NUM_BW
return ARR_OUT
def standard_dev(ARR_IN):
NUM_SUM = sum(ARR_IN)
NUM_N = len(ARR_IN)
NUM_MEAN = 1.0*NUM_SUM/NUM_N
NUM_SUM2 = 0.0
for N in ARR_IN:
if not math.isnan(N):
NUM_SUM2 += (N-NUM_MEAN)**2
else:
NUM_N += -1
return (NUM_SUM2 / (NUM_N-1)) ** 0.5
def h_esti(ARR_IN):
#A rule-of-thumb bandwidth estimator
NUM_SIGMA = standard_dev(ARR_IN)
NUM_N = len(ARR_IN)
return ((4 * NUM_SIGMA ** 5) / (3*NUM_N) ) ** 0.2
def data2array(ARR_IN, STR_IN="MEAN"):
NUM_J = len(ARR_IN)
NUM_I = len(ARR_IN[0])
ARR_OUT = [[ 0.0 for i in range(NUM_I)] for j in range(NUM_J) ]
for j in range(NUM_J):
for i in range(NUM_I):
ARR_OUT[j][i] = ARR_IN[j][i][STR_IN]
return ARR_OUT
def reshape2d(ARR_IN, NUM_NULL = 0.0):
ARR_OUT=[]
for A in ARR_IN:
for B in A:
if not math.isnan(B):
ARR_OUT.append(B)
return ARR_OUT
def NormalVector( V1, V2):
return [(V1[1]*V2[2] - V1[2]*V2[1]), (V1[2]*V2[0] - V1[0]*V2[2]),(V1[0]*V2[1] - V1[1]*V2[0])]
def NVtoPlane( P0, P1, P2):
"""Input of P should be 3-dimensionals"""
V1 = [(P1[0]-P0[0]),(P1[1]-P0[1]),(P1[2]-P0[2])]
V2 = [(P2[0]-P0[0]),(P2[1]-P0[1]),(P2[2]-P0[2])]
ARR_NV = MATH_TOOLS.NormalVector(V1, V2)
D = ARR_NV[0] * P0[0] + ARR_NV[1] * P0[1] + ARR_NV[2] * P0[2]
return ARR_NV[0],ARR_NV[1],ARR_NV[2],D
def FindZatP3( P0, P1, P2, P3):
""" input of P: (X,Y,Z); but P3 is (X,Y) only """
A,B,C,D = MATH_TOOLS.NVtoPlane(P0, P1, P2)
return (D-A*P3[0] - B*P3[1])/float(C)
def c2p(x,y):
if y != 0.0:
return math.fmod(math.atan(float(x/y)) * 180./math.pi + (x < 0) * 360 + (y < 0)*180, 360)
else:
return (x < 0) * 270 + (x > 0) * 90
def GrtCirDist(lon1,lat1,lon2,lat2,R=6.37122E6):
a2r = lambda x: x/180. * math.pi
term1 = math.sin(a2r(lat1)) * math.sin(a2r(lat2))
term2 = math.cos(a2r(lat1)) * math.cos(a2r(lat2))
term3 = math.cos(a2r( lon2 - lon1 ))
deltaSigma = math.acos( term1 + term2 * term3 ) * 180./math.pi
numDist = deltaSigma/360. * 2 * R * math.pi
return { "deltaSigma" : deltaSigma,
"dist" : numDist }
def NearestNeighbor(arr_x, arr_y, target_x, target_y):
""" This algorithm is used to find the nearest point
as 1-NN method
input: ARR_X/ARR_Y, the [j,i] array for x/y coordinates
target_x, target_y, the [j,i] array for target [x,y]
"""
lenNY = len(arr_x)
lenNX = len(arr_x[0])
numDist_chk = 9.99E20
for j in range(lenNY - 1):
for i in range(lenNX - 1):
chk1 = ( arr_x[j][i] - target_x ) ** 2
chk3 = ( arr_y[j][i] - target_y ) ** 2
numDist = (chk1 + chk3 ) ** 0.5
if min(numDist_chk, numDist) == numDist:
numDist_chk = numDist
found_i = i
found_j = j
return found_i, found_j
def NearestNeighbor1D(arr_x, target_v ):
""" This algorithm is used to find the nearest point
as 1-NN method
input: ARR_X/ARR_Y, the [j,i] array for x/y coordinates
target_x, target_y, the [j,i] array for target [x,y]
K is the number of K
Temperally solution for WRF and XX YY mesh.
"""
numOut = 9E12
numIndOut = 0
for ind, v_tmp in enumerate(arr_x):
chkTmp = (( v_tmp - target_v) ** 2 ) ** 0.5
if min( chkTmp, numOut) == chkTmp:
numIndOut = ind
numOut = chkTmp
return numIndOut, numOut
def KNearestNeighbor(arr_x, arr_y, target_x, target_y, numK, ):
""" This algorithm is used to find the nearest point
as 1-NN method
input: ARR_X/ARR_Y, the [j,i] array for x/y coordinates
target_x, target_y, the [j,i] array for target [x,y]
K is the number of K
Temperally solution for WRF and XX YY mesh.
"""
lenNY = len(arr_x)
lenNX = len(arr_x[0])
arrDistchk = [ [ 9.99E20, 0, 0 ] for n in range(numK) ]
arrNumChk = [ 9.99E20 for n in range(numK) ]
for j in range(lenNY - 1):
for i in range(lenNX - 1):
chk1 = ( arr_x[j][i] - target_x ) ** 2
chk3 = ( arr_y[j][i] - target_y ) ** 2
numDist = (chk1 + chk3 ) ** 0.5
for chk in arrDistChk:
if min( chk[0], numDist) == numDist:
arrDistChk = []
found_i = i
found_j = j
return arrDistChk
def Find_Xest(arrIn, dim_x, dim_y, num_crop=20, numMax = 9E20):
numMinOut = numMax
numMaxOut = -1 * numMax
Min_i = 0
Min_j = 0
Max_i = 0
Max_j = 0
MinV = 0
MaxV = 0
for j in range(num_crop, dim_y-num_crop):
for i in range(num_crop, dim_x-num_crop):
numIn = arrIn[j][i]
numMinOut = min( numMinOut, numIn )
numMaxOut = max( numMaxOut, numIn )
if numIn == numMinOut:
MinV = numIn
Min_i = i
Min_j = j
if numIn == numMaxOut:
MaxV = numIn
Max_i = i
Max_j = j
dicOut = {"MinV": MinV, "MinJ": Min_j, "MinI": Min_i,\
"MaxV": MaxV, "MaxJ": Max_j, "MaxI": Max_i}
return dicOut
class TOOLS:
""" TOOLS is contains:
timestamp
fix_ind
progress_bar
cal_progrss
"""
ARR_HOY = [0, 744, 1416, 2160, 2880, 3624, 4344, 5088, 5832, 6552, 7296, 8016, 8760]
ARR_HOY_LEAP = [0, 744, 1440, 2184, 2904, 3648, 4368, 5112, 5856, 6576, 7320, 8040, 8784]
def NNARR(ARR_IN, IF_PAIRING=False):
"Clean the NaN value in the array"
if IF_PAIRING:
ARR_SIZE = len(ARR_IN)
ARR_OUT = [ [] for N in range(ARR_SIZE)]
for ind_n, N in enumerate(ARR_IN[0]):
IF_NAN = False
for ind_a in range(ARR_SIZE):
if math.isnan(ARR_IN[ind_a][ind_n]):
IF_NAN = True
break
if not IF_NAN:
for ind_a in range(ARR_SIZE):
ARR_OUT[ind_a].append(ARR_IN[ind_a][ind_n])
else:
ARR_OUT = [ ]
for N in ARR_IN:
if not math.isnan(N):
ARR_OUT.append(N)
return ARR_OUT
def DATETIME2HOY(ARR_TIME, ARR_HOY_IN=[]):
if math.fmod(ARR_TIME[0], 4) == 0 and len(ARR_HOY_IN) == 0:
ARR_HOY_IN = [0, 744, 1440, 2184, 2904, 3648, 4368, 5112, 5856, 6576, 7320, 8040, 8784]
elif math.fmod(ARR_TIME[0], 4) != 0 and len(ARR_HOY_IN) == 0:
ARR_HOY_IN = [0, 744, 1416, 2160, 2880, 3624, 4344, 5088, 5832, 6552, 7296, 8016, 8760]
else:
ARR_HOY_IN = ARR_HOY_IN
return ARR_HOY_IN[ARR_TIME[1]-1] + (ARR_TIME[2]-1)*24 + ARR_TIME[3]
def timestamp(STR_IN=""):
str_out = "{0:04d}-{1:02d}-{2:02d}_{3:02d}:{4:02d}:{5:02d} {6:s}".format(time.gmtime().tm_year, time.gmtime().tm_mon, time.gmtime().tm_mday,\
time.gmtime().tm_hour, time.gmtime().tm_min, time.gmtime().tm_sec, STR_IN)
print(str_out)
return str_out
def fix_ind(IND_IN, IND_J, IND_I, ARR_XRANGE=[], ARR_YRANGE=[], NX=0, NY=0):
NUM_DY = ARR_YRANGE[0]
NUM_NX_F = ARR_XRANGE[0]
NUM_NX_R = NX - (ARR_XRANGE[1]+1)
if IND_J == ARR_YRANGE[0]:
IND_OUT = IND_IN - NUM_DY * NX - NUM_NX_F