forked from daspy/daspy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DAS_Assim_Common.py
2847 lines (2355 loc) · 215 KB
/
DAS_Assim_Common.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
# -*- coding: utf-8 -*-
'''
Copyright of DasPy:
Author - Xujun Han (Forschungszentrum Jülich, Germany)
DasPy was funded by:
1. Forschungszentrum Jülich, Agrosphere (IBG 3), Jülich, Germany
2. Cold and Arid Regions Environmental and Engineering Research Institute, Chinese Academy of Sciences, Lanzhou, PR China
3. Centre for High-Performance Scientific Computing in Terrestrial Systems: HPSC TerrSys, Geoverbund ABC/J, Jülich, Germany
Please include the following references related to DasPy:
1. Han, X., Li, X., He, G., Kumbhar, P., Montzka, C., Kollet, S., Miyoshi, T., Rosolem, R., Zhang, Y., Vereecken, H., and Franssen, H. J. H.:
DasPy 1.0 : the Open Source Multivariate Land Data Assimilation Framework in combination with the Community Land Model 4.5, Geosci. Model Dev. Discuss., 8, 7395-7444, 2015.
2. Han, X., Franssen, H. J. H., Rosolem, R., Jin, R., Li, X., and Vereecken, H.:
Correction of systematic model forcing bias of CLM using assimilation of cosmic-ray Neutrons and land surface temperature: a study in the Heihe Catchment, China, Hydrology and Earth System Sciences, 19, 615-629, 2015a.
3. Han, X., Franssen, H. J. H., Montzka, C., and Vereecken, H.:
Soil moisture and soil properties estimation in the Community Land Model with synthetic brightness temperature observations, Water Resour Res, 50, 6081-6105, 2014a.
4. Han, X., Franssen, H. J. H., Li, X., Zhang, Y. L., Montzka, C., and Vereecken, H.:
Joint Assimilation of Surface Temperature and L-Band Microwave Brightness Temperature in Land Data Assimilation, Vadose Zone J, 12, 0, 2013.
'''
from mpi4py import MPI
import os, sys, time, datetime, calendar, random, math, gc, imp, subprocess, glob, signal, string, shutil, fnmatch, warnings, multiprocessing, socket, getpass, ctypes, platform, functools, copy
import numpy, scipy, scipy.stats, scipy.signal, netCDF4, scipy.ndimage
sys.path.append('SysModel')
sys.path.append('SysModel/CLM')
sys.path.append('Utilities')
sys.path.append('Utilities/Soil')
sys.path.append('Algorithm')
sys.path.append('Algorithm/DAS')
sys.path.append('ForcingData')
from Call_CLM_CESM import *
from numpy import min, max
from Read_Soil_Texture import *
import ParFor
import pp, pyper
#from IPython.parallel import depend, require, dependent
#********************************************************************Call Model************************************************************************
def Prepare_Model_Operator(Ens_Index, Model_Driver, Def_CESM_Multi_Instance, Def_Par_Sensitivity, Def_Par_Correlation, Def_Par_Optimized, Do_DA_Flag, Def_Debug, CLM_NA, NAvalue, finidat_initial_CLM, Def_ParFor, Def_Region, Def_Initial, \
Irrig_Scheduling, Irrigation_Hours, Def_SpinUp, Def_First_Run, Def_Print, Region_Name, Run_Dir_Home, Run_Dir_Multi_Instance, Run_Dir_Array, Model_Path, CLM_Flag, num_processors,
CLM_File_Name_List, Parameter_Range_Soil, Start_Year, Start_Month, Start_Day, Stop_Year, Stop_Month, Stop_Day, Datetime_Start, Datetime_Start_Init, Datetime_Stop, Datetime_Stop_Init, Datetime_End, Datetime_Initial,
DAS_Data_Path, DasPy_Path, DAS_Output_Path, Forcing_File_Path_Array, dtime, Variable_Assimilation_Flag, Variable_List,\
Def_PP, N_Steps, Ensemble_Number, Ensemble_Number_Predict, Row_Numbers, Col_Numbers, Row_Numbers_String, Col_Numbers_String,
DAS_Depends_Path, maxpft, ntasks_CLM, rootpe_CLM, nthreads_CLM, Weather_Forecast_Days, Irrigation_Scheduling_Flag,\
omp_get_num_procs_ParFor, Low_Ratio_Par, High_Ratio_Par, Soil_Texture_Layer_Opt_Num, Def_Snow_Effects, PFT_Par_Sens_Array,\
Soil_Thickness, Soil_Layer_Num, Snow_Layer_Num, Density_of_liquid_water, Initial_Perturbation, Initial_Perturbation_SM_Flag, Initial_Perturbation_ST_Flag, \
NC_FileName_Assimilation_2_Constant, NC_FileName_Assimilation_2_Diagnostic, NC_FileName_Assimilation_2_Initial, NC_FileName_Assimilation_2_Bias, NC_FileName_Assimilation_2_Parameter, NC_FileName_Parameter_Space_Single):
pyper = imp.load_source("pyper",DasPy_Path+"Utilities/pyper.py")
DAS_Utilities = imp.load_source("pyper",DasPy_Path+"DAS_Utilities.py")
ParFor = imp.load_source("ParFor",DasPy_Path+"ParFor.py")
fndepdat_name = fnmatch.filter(CLM_File_Name_List,"fndep*")[0]
fatmgrid_name = fnmatch.filter(CLM_File_Name_List,"griddata_*")[0]
fatmlndfrc_name = fnmatch.filter(CLM_File_Name_List,"domain*")[0]
fsurdat_name = fnmatch.filter(CLM_File_Name_List,"surfdata_*")[0]
fglcmask_name = fnmatch.filter(CLM_File_Name_List,"glcmaskdata_*")[0]
flndtopo_name = fnmatch.filter(CLM_File_Name_List,"topodata_*")[0]
fsnowoptics_name = fnmatch.filter(CLM_File_Name_List,"snicar_optics_5bnd_c090915*")[0]
fsnowaging_name = fnmatch.filter(CLM_File_Name_List,"snicar_drdt_bst_fit_60_c070416*")[0]
fpftcon_name = fnmatch.filter(CLM_File_Name_List,"pft*")[0]
domain_name = fnmatch.filter(CLM_File_Name_List,"domain*")[0]
rdirc_name = fnmatch.filter(CLM_File_Name_List,"rdirc_0*")[0]
popd_streams_name = fnmatch.filter(CLM_File_Name_List,"*clmforc.Li_2012_hdm*")[0]
light_streams_name = fnmatch.filter(CLM_File_Name_List,"*clmforc.Li_2012_climo*")[0]
NC_File_Out_Assimilation_2_Constant = netCDF4.Dataset(NC_FileName_Assimilation_2_Constant, 'r')
Land_Mask_Data = NC_File_Out_Assimilation_2_Constant.variables['Land_Mask_Data'][:,:]
Teta_Saturated = NC_File_Out_Assimilation_2_Constant.variables['Teta_Saturated'][:,:,:]
NC_File_Out_Assimilation_2_Diagnostic = netCDF4.Dataset(NC_FileName_Assimilation_2_Diagnostic, 'r')
Initial_SM_Noise = NC_File_Out_Assimilation_2_Diagnostic.variables['Initial_SM_Noise'][:,:,:]
Initial_ST_Noise = NC_File_Out_Assimilation_2_Diagnostic.variables['Initial_ST_Noise'][:,:,:]
NC_File_Out_Assimilation_2_Diagnostic.close()
NC_File_Parameter_Space_Single = netCDF4.Dataset(NC_FileName_Parameter_Space_Single,'r')
Parameter_ParFlow_Space_Single = NC_File_Parameter_Space_Single.variables['Parameter_ParFlow_Space_Single'][:,:,:]
Parameter_Soil_Space_Single = NC_File_Parameter_Space_Single.variables['Parameter_Soil_Space_Single'][:,:,:]
Parameter_Veg_Space_Single = NC_File_Parameter_Space_Single.variables['Parameter_Veg_Space_Single'][:,:]
GaussRF_Array = NC_File_Parameter_Space_Single.variables['GaussRF_Array'][:,:]
Sand_Ratio = NC_File_Parameter_Space_Single.variables['Sand_Ratio'][:,:,:]
Clay_Ratio = NC_File_Parameter_Space_Single.variables['Clay_Ratio'][:,:,:]
Organic_Ratio = NC_File_Parameter_Space_Single.variables['Organic_Ratio'][:,:,:]
MONTHLY_LAI_Empirical = NC_File_Parameter_Space_Single.variables['MONTHLY_LAI_Empirical'][:,:]
NC_File_Parameter_Space_Single.close()
NC_File_Out_Assimilation_2_Initial = netCDF4.Dataset(NC_FileName_Assimilation_2_Initial, 'r')
NC_File_Out_Assimilation_2_Parameter = netCDF4.Dataset(NC_FileName_Assimilation_2_Parameter, 'r')
Run_Dir = Run_Dir_Array[Ens_Index]
Forcing_File_Path = Forcing_File_Path_Array[Ens_Index]
if Def_Print:
print "Processing " + str(Ens_Index + 1) + 'th Ensemble under',Run_Dir
if Def_First_Run == 1:
if Def_Print:
print "*******************************Copy Surfdata File**********************"
#print DAS_Data_Path + "SysModel/CLM/tools/mksurfdata/surfdata_"+Row_Numbers_String+"x"+Col_Numbers_String+".nc",Run_Dir+"/"+"surfdata_"+Row_Numbers_String+"x"+Col_Numbers_String+".nc"
#DAS_Utilities.copyLargeFile(DAS_Data_Path + "SysModel/CLM/tools/mkgriddata/griddata_"+Row_Numbers_String+"x"+Col_Numbers_String+".nc",Run_Dir+"/"+"griddata_"+Row_Numbers_String+"x"+Col_Numbers_String+".nc")
DAS_Utilities.copyLargeFile(DAS_Data_Path + "SysModel/CLM/tools/"+fatmlndfrc_name,Run_Dir+fatmlndfrc_name)
DAS_Utilities.copyLargeFile(DAS_Data_Path + "SysModel/CLM/tools/"+fsurdat_name,Run_Dir+fsurdat_name)
#DAS_Utilities.copyLargeFile(DAS_Data_Path + "SysModel/CLM/inputdata/glc/cism/griddata/"+fglcmask_name,Run_Dir+fglcmask_name)
#DAS_Utilities.copyLargeFile(DAS_Data_Path + "SysModel/CLM/tools/"+flndtopo_name,Run_Dir+flndtopo_name)
DAS_Utilities.copyLargeFile(DAS_Data_Path + "SysModel/CLM/inputdata/lnd/clm2/pftdata/"+fpftcon_name,Run_Dir+fpftcon_name)
DAS_Utilities.copyLargeFile(DAS_Data_Path + "SysModel/CLM/inputdata/lnd/clm2/rtmdata/"+rdirc_name,Run_Dir+rdirc_name)
DAS_Utilities.copyLargeFile(DAS_Data_Path + "SysModel/CLM/inputdata/lnd/clm2/snicardata/"+fsnowoptics_name,Run_Dir+fsnowoptics_name)
DAS_Utilities.copyLargeFile(DAS_Data_Path + "SysModel/CLM/inputdata/lnd/clm2/snicardata/"+fsnowaging_name,Run_Dir+fsnowaging_name)
DAS_Utilities.copyLargeFile(DAS_Data_Path + "SysModel/CLM/inputdata/lnd/clm2/ndepdata/"+fndepdat_name,Run_Dir+fndepdat_name)
mksurfdata_NC_FileName_In = Run_Dir+"/"+fsurdat_name
pft_physiology_file_name = Run_Dir+"/"+fpftcon_name
if Ensemble_Number > 1 and Def_Par_Optimized:
if Def_Print:
print "******************************* Parameter Perturbation and Modify the surfdata.nc *******************************"
mksurfdata_NC_File_Orig = netCDF4.Dataset(DAS_Data_Path + "SysModel/CLM/tools/"+fsurdat_name, 'r')
mksurfdata_NC_File_In = netCDF4.Dataset(mksurfdata_NC_FileName_In, 'r+')
Sand_Mat = numpy.zeros((10,Row_Numbers,Col_Numbers),dtype=numpy.float32)
Clay_Mat = numpy.zeros((10,Row_Numbers,Col_Numbers),dtype=numpy.float32)
Parameter_Soil_Space_Ensemble = numpy.asarray(NC_File_Out_Assimilation_2_Parameter.variables['Parameter_Soil_Space_Ensemble'][:,:,:,:])
for Soil_Layer_Index in range(10):
Sand_Mat[Soil_Layer_Index,:,:] = numpy.flipud(Parameter_Soil_Space_Ensemble[Ens_Index,0,::]) * Sand_Ratio[Soil_Layer_Index,:,:]
numexpr_a = Sand_Mat[Soil_Layer_Index,:,:]
numexpr_b = Parameter_Range_Soil[0,0]
numexpr_c = numpy.where(numexpr_a < numexpr_b)
Sand_Mat[Soil_Layer_Index,:,:][numexpr_c] = Parameter_Range_Soil[0,0]
numexpr_a = Sand_Mat[Soil_Layer_Index,:,:]
numexpr_b = Parameter_Range_Soil[1,0]
numexpr_c = numpy.where(numexpr_a > numexpr_b)
Sand_Mat[Soil_Layer_Index,:,:][numexpr_c] = Parameter_Range_Soil[1,0]
Clay_Mat[Soil_Layer_Index,:,:] = numpy.flipud(Parameter_Soil_Space_Ensemble[Ens_Index,0+Soil_Texture_Layer_Opt_Num,::]) * Clay_Ratio[Soil_Layer_Index,:,:]
numexpr_a = Clay_Mat[Soil_Layer_Index,:,:]
numexpr_b = Parameter_Range_Soil[0,1]
numexpr_c = numpy.where(numexpr_a < numexpr_b)
Clay_Mat[Soil_Layer_Index,:,:][numexpr_c] = Parameter_Range_Soil[0,1]
numexpr_a = Clay_Mat[Soil_Layer_Index,:,:]
numexpr_b = Parameter_Range_Soil[1,1]
numexpr_c = numpy.where(numexpr_a > numexpr_b)
Clay_Mat[Soil_Layer_Index,:,:][numexpr_c] = Parameter_Range_Soil[1,1]
mksurfdata_NC_File_In.variables["PCT_SAND"][:,:,:] = Sand_Mat
mksurfdata_NC_File_In.variables["PCT_CLAY"][:,:,:] = Clay_Mat
del Sand_Mat,Clay_Mat
Organic_mat = numpy.zeros((10,Row_Numbers,Col_Numbers),dtype=numpy.float32)
for Soil_Layer_Index in range(8):
Organic_mat[Soil_Layer_Index,:,:] = numpy.flipud(Parameter_Soil_Space_Ensemble[Ens_Index,0+2*Soil_Texture_Layer_Opt_Num,::]) * Organic_Ratio[Soil_Layer_Index,:,:]
numexpr_a = Organic_mat[Soil_Layer_Index,:,:]
numexpr_b = Parameter_Range_Soil[0,2]
numexpr_c = numpy.where(numexpr_a < numexpr_b)
Organic_mat[Soil_Layer_Index,:,:][numexpr_c] = Parameter_Range_Soil[0,2]
numexpr_a = Organic_mat[Soil_Layer_Index,:,:]
numexpr_b = Parameter_Range_Soil[1,2]
numexpr_c = numpy.where(numexpr_a > numexpr_b)
Organic_mat[Soil_Layer_Index,:,:][numexpr_c] = Parameter_Range_Soil[1,2]
mksurfdata_NC_File_In.variables["ORGANIC"][:,:,:] = Organic_mat
del Organic_mat
del Parameter_Soil_Space_Ensemble
del numexpr_a, numexpr_b, numexpr_c
if (numpy.size(numpy.where(numpy.asarray(PFT_Par_Sens_Array) == True)) >= 1):
mksurfdata_NC_File_In.variables["MONTHLY_LAI"][:,:,:,:] = \
numpy.multiply(mksurfdata_NC_File_Orig.variables["MONTHLY_LAI"][:,:,:,:], numpy.flipud(NC_File_Out_Assimilation_2_Parameter.variables['Parameter_PFT_Space_Ensemble'][Ens_Index,0,::]))
mksurfdata_NC_File_In.variables["MONTHLY_SAI"][:,:,:,:] = \
numpy.multiply(mksurfdata_NC_File_Orig.variables["MONTHLY_SAI"][:,:,:,:], numpy.flipud(NC_File_Out_Assimilation_2_Parameter.variables['Parameter_PFT_Space_Ensemble'][Ens_Index,1,::]))
mksurfdata_NC_File_In.variables["MONTHLY_HEIGHT_TOP"][:,:,:,:] = \
numpy.multiply(mksurfdata_NC_File_Orig.variables["MONTHLY_HEIGHT_TOP"][:,:,:,:], numpy.flipud(NC_File_Out_Assimilation_2_Parameter.variables['Parameter_PFT_Space_Ensemble'][Ens_Index,2,::]))
del MONTHLY_LAI_Empirical
mksurfdata_NC_File_In.sync()
mksurfdata_NC_File_In.close()
mksurfdata_NC_File_Orig.close()
if Initial_Perturbation and ((numpy.sum(Initial_Perturbation_SM_Flag) or numpy.sum(Initial_Perturbation_ST_Flag)) or Def_First_Run) and Def_Initial:
if Def_Print:
print "**************************Initial Value Perturbation, Open Initial File:", Run_Dir+"/"+ finidat_initial_CLM
CLM_Initial_File = netCDF4.Dataset(Run_Dir+"/"+ finidat_initial_CLM, "r+")
column_len = len(CLM_Initial_File.dimensions['column'])
for Soil_Layer_Index in range(Soil_Layer_Num-5):
if Initial_Perturbation_SM_Flag[Soil_Layer_Index]:
#print numpy.shape(CLM_Initial_File.variables["H2OSOI_LIQ"][:,Snow_Layer_Num+Soil_Layer_Index]),numpy.shape(Initial_SM_Noise[Ens_Index,:,:][numpy.where(Land_Mask_Data != NAvalue)].flatten())
CLM_Initial_File.variables["H2OSOI_LIQ"][:,Snow_Layer_Num+Soil_Layer_Index] += numpy.repeat(Initial_SM_Noise[Ens_Index,:,:][numpy.where(Land_Mask_Data != NAvalue)].flatten(),column_len/(Row_Numbers*Col_Numbers)) * (Soil_Thickness[Soil_Layer_Index] * Density_of_liquid_water)
#print numpy.max(Initial_SM_Noise[Ens_Index,:,:][numpy.where(Land_Mask_Data != NAvalue)].flatten() * (Soil_Thickness[Soil_Layer_Index] * Density_of_liquid_water)),numpy.min(Initial_SM_Noise[Ens_Index,:,:][numpy.where(Land_Mask_Data != NAvalue)].flatten() * (Soil_Thickness[Soil_Layer_Index] * Density_of_liquid_water))
CLM_Initial_File.variables["H2OSOI_LIQ"][:,Snow_Layer_Num+Soil_Layer_Index][numpy.where(CLM_Initial_File.variables["H2OSOI_LIQ"][:,Snow_Layer_Num+Soil_Layer_Index] < 0.0)] = 0.2 * (Soil_Thickness[Soil_Layer_Index] * Density_of_liquid_water)
CLM_Initial_File.variables["T_GRND"][:] += numpy.repeat(Initial_ST_Noise[Ens_Index,:,:][numpy.where(Land_Mask_Data != NAvalue)].flatten(),column_len/(Row_Numbers*Col_Numbers))
for Soil_Layer_Index in range(Soil_Layer_Num):
if Initial_Perturbation_ST_Flag[Soil_Layer_Index]:
CLM_Initial_File.variables["T_SOISNO"][:,Snow_Layer_Num+Soil_Layer_Index][:] += Initial_ST_Noise[Ens_Index,:,:][numpy.where(Land_Mask_Data != NAvalue)].flatten()
CLM_Initial_File.sync()
CLM_Initial_File.close()
NC_File_Out_Assimilation_2_Parameter.sync()
NC_File_Out_Assimilation_2_Parameter.close()
NC_File_Out_Assimilation_2_Initial.close()
NC_File_Out_Assimilation_2_Constant.close()
#NC_File_Assimilation_2_Parameter_Ens.sync()
#NC_File_Assimilation_2_Parameter_Ens.close()
del Initial_SM_Noise,Initial_ST_Noise,Land_Mask_Data, Teta_Saturated
del Parameter_ParFlow_Space_Single,Parameter_Soil_Space_Single,Parameter_Veg_Space_Single
del Sand_Ratio, Clay_Ratio, Organic_Ratio, GaussRF_Array
gc.collect()
del gc.garbage[:]
return 0
def Call_Model_Operator(Ens_Index, Model_Driver, Def_CESM_Multi_Instance, Def_Par_Sensitivity, Def_Par_Correlation, Def_Par_Optimized, Do_DA_Flag, Def_Debug, CLM_NA, NAvalue, finidat_initial_CLM, Def_ParFor, Def_Region, Def_Initial, \
Irrig_Scheduling, Irrigation_Hours, Def_SpinUp, Def_First_Run, Def_Print, Region_Name, Run_Dir_Home, Run_Dir_Multi_Instance, Run_Dir_Array, Model_Path, CLM_Flag, num_processors,
CLM_File_Name_List, Start_Year, Start_Month, Start_Day, Stop_Year, Stop_Month, Stop_Day, Datetime_Start, Datetime_Start_Init, Datetime_Stop, Datetime_Stop_Init, Datetime_End, Datetime_Initial, DAS_Data_Path, DasPy_Path, Forcing_File_Path_Array, dtime,\
Def_PP, N_Steps, Ensemble_Number, Ensemble_Number_Predict, Row_Numbers, Col_Numbers, Row_Numbers_String, Col_Numbers_String, DAS_Depends_Path, maxpft, ntasks_CLM, rootpe_CLM, nthreads_CLM, Weather_Forecast_Days, Irrigation_Scheduling_Flag,\
Low_Ratio_Par, High_Ratio_Par, Soil_Texture_Layer_Opt_Num, Def_Snow_Effects, PFT_Par_Sens_Array,\
Soil_Thickness, Soil_Layer_Num, Snow_Layer_Num, Density_of_liquid_water, Initial_Perturbation, Initial_Perturbation_SM_Flag, Initial_Perturbation_ST_Flag, \
NC_FileName_Assimilation_2_Constant, NC_FileName_Assimilation_2_Diagnostic, NC_FileName_Assimilation_2_Initial, NC_FileName_Assimilation_2_Bias, NC_FileName_Parameter_Space_Single, COUP_OAS_PFL, CESM_Init_Flag, mpi4py_comm_split, mpi4py_null):
if Def_PP == 2:
fcomm_rank = mpi4py_comm_split.Get_rank()
fcomm = mpi4py_comm_split
fcomm_null = mpi4py_null
else:
fcomm_rank = 0
fcomm = 0
fcomm_null = 0
#if Def_Print:
# print "fcomm,fcomm_null,fcomm_rank",fcomm,fcomm_null,fcomm_rank
fndepdat_name = fnmatch.filter(CLM_File_Name_List,"fndep*")[0]
fatmgrid_name = fnmatch.filter(CLM_File_Name_List,"griddata_*")[0]
fatmlndfrc_name = fnmatch.filter(CLM_File_Name_List,"domain*")[0]
fsurdat_name = fnmatch.filter(CLM_File_Name_List,"surfdata_*")[0]
fglcmask_name = fnmatch.filter(CLM_File_Name_List,"glcmaskdata_*")[0]
flndtopo_name = fnmatch.filter(CLM_File_Name_List,"topodata_*")[0]
fsnowoptics_name = fnmatch.filter(CLM_File_Name_List,"snicar_optics_5bnd_c090915*")[0]
fsnowaging_name = fnmatch.filter(CLM_File_Name_List,"snicar_drdt_bst_fit_60_c070416*")[0]
fpftcon_name = fnmatch.filter(CLM_File_Name_List,"pft*")[0]
domain_name = fnmatch.filter(CLM_File_Name_List,"domain*")[0]
rdirc_name = fnmatch.filter(CLM_File_Name_List,"rdirc_0*")[0]
popd_streams_name = fnmatch.filter(CLM_File_Name_List,"*clmforc.Li_2012_hdm*")[0]
light_streams_name = fnmatch.filter(CLM_File_Name_List,"*clmforc.Li_2012_climo*")[0]
Run_Dir = Run_Dir_Array[Ens_Index]
Forcing_File_Path = Forcing_File_Path_Array[Ens_Index]
if Def_Print:
print "Processing " + str(Ens_Index + 1) + 'th Ensemble under',Run_Dir
if Def_Initial and os.path.isfile(Run_Dir + finidat_initial_CLM):
finidat_name = finidat_initial_CLM
else:
finidat_name = ""
if Def_Print:
print "Initial File Information", Def_Initial, finidat_name
if Def_Print:
print "---------------------------------------------- Run CLM Model ---------------------------"
Run_CLM(Model_Driver, Def_PP, Do_DA_Flag, Def_CESM_Multi_Instance, Def_Par_Sensitivity, Def_Par_Correlation, Def_Par_Optimized, Def_Region, Def_Initial, \
Irrig_Scheduling, Irrigation_Hours, Def_SpinUp, Def_First_Run, Def_Print, Region_Name, Run_Dir_Home, Run_Dir_Multi_Instance,
Run_Dir, Run_Dir_Array, Model_Path, CLM_Flag, domain_name, rdirc_name, \
fatmgrid_name, fatmlndfrc_name, fndepdat_name, fsurdat_name, fsnowoptics_name, fsnowaging_name, fglcmask_name, finidat_name, flndtopo_name, \
fpftcon_name, popd_streams_name, light_streams_name, N_Steps, Row_Numbers_String, Col_Numbers_String, Start_Year, Start_Month, Start_Day, Stop_Year, Stop_Month, Stop_Day, Datetime_Start, \
Datetime_Start_Init, Datetime_Stop, Datetime_Stop_Init, DasPy_Path, DAS_Data_Path, Forcing_File_Path, Forcing_File_Path_Array,
dtime, ntasks_CLM, rootpe_CLM, nthreads_CLM, Ensemble_Number, num_processors,
COUP_OAS_PFL, CESM_Init_Flag, fcomm, fcomm_null, fcomm_rank)
stop_tod_string = str((Datetime_Stop - Datetime_Stop_Init).seconds).zfill(5)
history_file_name = Region_Name + '.clm2.h0.' + Stop_Year + '-' + Stop_Month + '-' + Stop_Day + '-' + stop_tod_string + '.nc'
restart_file_name = Region_Name + '.clm2.r.' + Stop_Year + '-' + Stop_Month + '-' + Stop_Day + '-' + stop_tod_string + '.nc'
gc.collect()
del gc.garbage[:]
if Def_Print:
print history_file_name, restart_file_name
return 0
#*******************************************************************Obervation********************************************************************************************
def Observation_Blocks(Observation_Matrix_Index, Def_PP, Def_CESM_Multi_Instance, Def_Region, Def_ReBEL, Def_Localization, DasPy_Path, DAS_Depends_Path, DAS_Output_Path, Region_Name, Num_Local_Obs,\
Row_Numbers, Col_Numbers, Ensemble_Number, Ensemble_Number_Predict, Call_Gstat_Flag, Plot_Analysis, \
Write_DA_File_Flag, Use_Mask_Flag, Mask_File, Forcing_File_Path, dtime, Observation_Path, Observation_File_Name, \
DAS_Data_Path, Grid_Resolution_CEA, Grid_Resolution_GEO, NAvalue, Variable_List, Variable_Assimilation_Flag, \
SensorType, SensorVariable, SensorQuantity, SensorResolution, Variable_ID, QC_ID, PDAF_Assim_Framework, PDAF_Filter_Type, \
mksrf_edgee, mksrf_edges, mksrf_edgew, mksrf_edgen, Datetime_Start, Datetime_Stop, Datetime_Stop_Init, \
Stop_Year, Stop_Month, Stop_Day, Def_Print, Observation_Bias_Range, Observation_Bias_Range_STD, Observation_Bias_Initialization_Flag, plt, cm, colors, *vartuple):
octave = vartuple[0]
r = vartuple[1]
# Matrix to store the observation supplementary information
Observation_Misc = numpy.zeros((10, Row_Numbers, Col_Numbers),dtype=numpy.float32)
print "######################### Open Observation File: ", Observation_File_Name
print "\n"
if numpy.sum(Variable_Assimilation_Flag) > 0:
Observation_File = netCDF4.Dataset(Observation_File_Name, "r")
#----------------- Get the Observation Matrix Dimension
#print Observation_File.dimensions["lat"]
Observation_NLats = len(Observation_File.dimensions["lat"])
Observation_NLons = len(Observation_File.dimensions["lon"])
Observation_Latitude = numpy.zeros((Observation_NLats, Observation_NLons),dtype=numpy.float32)
Observation_Longitude = numpy.zeros((Observation_NLats, Observation_NLons),dtype=numpy.float32)
Observation_View_Zenith_Angle = numpy.zeros((Observation_NLats, Observation_NLons),dtype=numpy.float32)
Observation_View_Time = numpy.zeros((Observation_NLats, Observation_NLons),dtype=numpy.float32)
Observation_Latitude = Observation_File.variables["CEA_Y"][::]
Observation_Longitude = Observation_File.variables["CEA_X"][::]
Observation_Latitude = numpy.flipud(Observation_Latitude)
Observation_Matrix = Observation_File.variables[Variable_ID][::]
if Variable_Assimilation_Flag[Variable_List.index(SensorVariable)] and SensorVariable == "Surface_Temperature" or\
Variable_Assimilation_Flag[Variable_List.index(SensorVariable)] and SensorVariable == "Sensible_Heat":
if SensorType == "Terra" or SensorType == "Aqua":
Observation_View_Zenith_Angle = numpy.abs(numpy.flipud(Observation_File.variables["View_angl"][::]) - 65.0)
numexpr_a = Observation_View_Zenith_Angle
numexpr_b = 255.0-65.0
numexpr_c = numpy.where(numexpr_a == numexpr_b)
Observation_View_Zenith_Angle[numexpr_c] = 0.0
else:
Observation_View_Zenith_Angle = numpy.abs(numpy.flipud(Observation_File.variables["View_angl"][::]))
if Variable_Assimilation_Flag[Variable_List.index(SensorVariable)] and SensorVariable == "Surface_Temperature":
Observation_View_Time = numpy.abs(numpy.flipud(Observation_File.variables["View_time"][::])) # MODIS is local time, but changed in MRT_Py to UTC
else:
Observation_NLats = Row_Numbers
Observation_NLons = Col_Numbers
Observation_Latitude = numpy.zeros((Observation_NLats, Observation_NLons),dtype=numpy.float32)
Observation_Longitude = numpy.zeros((Observation_NLats, Observation_NLons),dtype=numpy.float32)
Observation_Matrix = numpy.zeros((Observation_NLats, Observation_NLons),dtype=numpy.float32)
Observation_View_Zenith_Angle = numpy.zeros((Observation_NLats, Observation_NLons),dtype=numpy.float32)
Observation_View_Time = numpy.zeros((Observation_NLats, Observation_NLons),dtype=numpy.float32)
if Variable_Assimilation_Flag[Variable_List.index(SensorVariable)] and SensorVariable == "Soil_Moisture":
if SensorType == "AMSR_E" and SensorQuantity != "K":
if Variable_ID == "A_Soil_Moisture" or Variable_ID == "D_Soil_Moisture":
AMSR_E_QA = Observation_File.variables[QC_ID][::]
AMSR_E_QA_Index = numpy.zeros((Observation_NLats, Observation_NLons), dtype=numpy.bool)
for Lat_Index in range(Observation_NLats):
for Long_Index in range(Observation_NLons):
AMSR_E_QA_String = numpy.binary_repr(int(AMSR_E_QA[Lat_Index, Long_Index]), width=16)
#print AMSR_E_QA[Lat_Index,Long_Index],AMSR_E_QA_String[6],AMSR_E_QA_String[-10]
if AMSR_E_QA_String[-10] == "0":
AMSR_E_QA_Index[Lat_Index, Long_Index] = True
else:
AMSR_E_QA_Index[Lat_Index, Long_Index] = False
Observation_Matrix = Observation_Matrix / 1000.0
numexpr_a = Observation_Matrix
numexpr_b = 0.0
numexpr_c = numpy.where(numexpr_a < numexpr_b)
Observation_Matrix[numexpr_c] = NAvalue
numexpr_a = Observation_Matrix
numexpr_b = 0.8
numexpr_c = numpy.where(numexpr_a >= numexpr_b)
Observation_Matrix[numexpr_c] = NAvalue
Grid_Resolution_GEO_Global = (179.999999415 + 179.999995782) / 1383.0
mksrf_edgew_temp = mksrf_edgew + Grid_Resolution_GEO[0] / 2.0
mksrf_edgen_temp = mksrf_edgen - Grid_Resolution_GEO[1] / 2.0
Corner_Row_Index = int(numpy.floor((86.716744081 - mksrf_edgen_temp) / Grid_Resolution_GEO_Global)) - 5
Corner_Col_Index = int(numpy.floor((mksrf_edgew_temp + 179.999999415) / Grid_Resolution_GEO_Global)) - 5
Observation_Latitude = Observation_Latitude[Corner_Row_Index:(Corner_Row_Index + numpy.ceil(Row_Numbers / (Grid_Resolution_GEO_Global / Grid_Resolution_GEO[1])) + 10), \
Corner_Col_Index:(Corner_Col_Index + numpy.ceil(Col_Numbers / (Grid_Resolution_GEO_Global / Grid_Resolution_GEO[0])) + 10)]
Observation_Longitude = Observation_Longitude[Corner_Row_Index:(Corner_Row_Index + numpy.ceil(Row_Numbers / (Grid_Resolution_GEO_Global / Grid_Resolution_GEO)) + 10), \
Corner_Col_Index:(Corner_Col_Index + numpy.ceil(Col_Numbers / (Grid_Resolution_GEO_Global / Grid_Resolution_GEO[0])) + 10)]
Observation_Matrix = numpy.flipud(numpy.flipud(Observation_Matrix)[Corner_Row_Index:(Corner_Row_Index + numpy.ceil(Row_Numbers / (Grid_Resolution_GEO_Global / Grid_Resolution_GEO[1])) + 10), \
Corner_Col_Index:(Corner_Col_Index + numpy.ceil(Col_Numbers / (Grid_Resolution_GEO_Global / Grid_Resolution_GEO[0])) + 10)])
Observation_Matrix = numpy.flipud(Observation_Matrix)
elif SensorType == "SMOS" and SensorQuantity == "K":
Observation_Matrix = numpy.flipud(Observation_Matrix)
elif SensorType == "SMOS" and SensorQuantity == "m3/m3":
Observation_Matrix = numpy.flipud(Observation_Matrix)
elif SensorType == "ASCAT" and SensorQuantity == "m3/m3":
Observation_Matrix = numpy.flipud(Observation_Matrix)
elif SensorType == "ASAR" and SensorQuantity == "DB":
Observation_Matrix = numpy.flipud(Observation_Matrix)
elif SensorType == "PALSAR" and SensorQuantity == "DB":
Observation_Matrix = numpy.flipud(Observation_Matrix)
elif (SensorType == "Terra" or SensorType == "Aqua") and SensorQuantity == "m3/m3":
Observation_Matrix = numpy.flipud(Observation_Matrix)
elif SensorType == "ECV_SM" and SensorQuantity == "m3/m3":
Observation_Matrix = numpy.flipud(Observation_Matrix)
elif SensorType == "COSMOS" and SensorQuantity == "Neutron_Count":
Observation_Matrix = numpy.flipud(Observation_Matrix)
if Def_Region == 3 or Def_Region == 8:
Observation_Misc[0,:,:] = numpy.abs(numpy.flipud(Observation_File.variables["bd"][::]))
Observation_Misc[1,:,:] = numpy.abs(numpy.flipud(Observation_File.variables["lw"][::]))
Observation_Misc[2,:,:] = numpy.abs(numpy.flipud(Observation_File.variables["Ncosmic"][::]))
elif SensorType == "InSitu":
Observation_Matrix = numpy.flipud(Observation_Matrix)
else:
Observation_Matrix = numpy.flipud(Observation_Matrix)
elif Variable_Assimilation_Flag[Variable_List.index(SensorVariable)] and SensorVariable == "Surface_Temperature":
if SensorType == "Terra" or SensorType == "Aqua":
LST_QA = Observation_File.variables[QC_ID][::]
LST_QA_Index = numpy.zeros((Observation_NLats, Observation_NLons), dtype=numpy.bool)
for Lat_Index in range(Observation_NLats):
for Long_Index in range(Observation_NLons):
LST_QA_String = numpy.binary_repr(int(LST_QA[Lat_Index, Long_Index]), width=8)
if LST_QA_String[6:8] == "00":
LST_QA_Index[Lat_Index, Long_Index] = True
else:
LST_QA_Index[Lat_Index, Long_Index] = False
numexpr_a = Observation_Matrix
numexpr_b = 65535
numexpr_c = numpy.where(numexpr_a > numexpr_b)
Observation_Matrix[numexpr_c] = NAvalue / 0.02
numexpr_a = Observation_Matrix
numexpr_b = 7500
numexpr_c = numpy.where(numexpr_a < numexpr_b)
Observation_Matrix[numexpr_c] = NAvalue / 0.02
Observation_Matrix[~LST_QA_Index] = NAvalue / 0.02
# Because there are different observation time for one catchment, we need 1 most common time clock.
Observation_Matrix[numpy.where(Observation_View_Time == -9999)] = NAvalue / 0.02
Observation_Matrix = numpy.flipud(Observation_Matrix * 0.02)
elif SensorType == "InSitu":
Observation_Matrix = numpy.flipud(Observation_Matrix)
else:
Observation_Matrix = numpy.flipud(Observation_Matrix)
# Make sure the Observation Bias is perturbed only once
Observation_Bias_Initialization_Flag[:,:,:] += 1
# Observation Corner Location
Observation_X_Left = float(Observation_Longitude.min())
Observation_X_Right = float(Observation_Longitude.max())
Observation_Y_Lower = float(Observation_Latitude.min())
Observation_Y_Upper = float(Observation_Latitude.max())
Observation_Longitude = Observation_Longitude - Observation_X_Left
Observation_Latitude = Observation_Latitude - Observation_Y_Lower
Observation_X_Right = Observation_X_Right - Observation_X_Left
Observation_X_Left = Observation_X_Left - Observation_X_Left
Observation_Y_Upper = Observation_Y_Upper - Observation_Y_Lower
Observation_Y_Lower = Observation_Y_Lower- Observation_Y_Lower
print "--------------Observation_X_Left,Observation_X_Right,Observation_Y_Lower,Observation_Y_Upper-----------------"
print Observation_X_Left,Observation_X_Right,Observation_Y_Lower,Observation_Y_Upper
r.assign("Observation_X_Left", Observation_X_Left)
r.assign("Observation_X_Right", Observation_X_Right)
r.assign("Observation_Y_Lower", Observation_Y_Lower)
r.assign("Observation_Y_Upper", Observation_Y_Upper)
Observation_Variance = numpy.zeros((Observation_NLats, Observation_NLons),dtype=numpy.float32)
print "****************************** Pre-Defined Observation Variance!"
Observation_Matrix[numpy.isnan(Observation_Matrix)] = NAvalue
Observation_Matrix_None_NA_Index = numpy.where(Observation_Matrix != NAvalue)
print "numpy.size(Observation_Matrix_None_NA_Index) / 2",numpy.size(Observation_Matrix_None_NA_Index) / 2
print "numpy.min(Observation_Matrix[Observation_Matrix_None_NA_Index]),numpy.max(Observation_Matrix[Observation_Matrix_None_NA_Index])"
print numpy.min(Observation_Matrix[Observation_Matrix_None_NA_Index]),numpy.max(Observation_Matrix[Observation_Matrix_None_NA_Index])
if SensorVariable == "Soil_Moisture":
if SensorQuantity == "K":
Observation_Variance[Observation_Matrix_None_NA_Index] = numpy.square(Observation_Matrix[Observation_Matrix_None_NA_Index] * 0.01)
Observation_Variance[Observation_Matrix_None_NA_Index] = 4.0
elif SensorQuantity == "DB":
Observation_Variance[Observation_Matrix_None_NA_Index] = numpy.square(Observation_Matrix[Observation_Matrix_None_NA_Index] * 0.05)
elif SensorQuantity == "m3/m3":
Observation_Variance[Observation_Matrix_None_NA_Index] = numpy.square(Observation_Matrix[Observation_Matrix_None_NA_Index] * 0.05)
if SensorType == "ECV_SM" or SensorType == "ASCAT":
# To avoid the missing values of variance
Variance_Max = numpy.max(numpy.asarray(Observation_File.variables[Variable_ID+"_noise"][::]))
print "-------------- Variance_Max",Variance_Max
if Variance_Max > 0.0:
Observation_Variance = numpy.square(numpy.flipud(Observation_File.variables[Variable_ID+"_noise"][::]))
else:
Observation_Variance[Observation_Matrix_None_NA_Index] = 0.0016
else:
if Def_Region == -1:
Observation_Variance[Observation_Matrix_None_NA_Index] = 0.0016
elif Def_Region == 0:
Observation_Variance[Observation_Matrix_None_NA_Index] = 0.0009
else:
Observation_Variance[Observation_Matrix_None_NA_Index] = 0.0016
elif SensorQuantity == "Neutron_Count":
print "-----------------------------Assign COSMOS Observation Error"
Observation_Variance[Observation_Matrix_None_NA_Index] = Observation_Matrix[Observation_Matrix_None_NA_Index] * 0.25
if Def_Region == -2:
Observation_Variance[Observation_Matrix_None_NA_Index] = Observation_Matrix[Observation_Matrix_None_NA_Index] * 0.25
elif SensorVariable == "Surface_Temperature" or SensorVariable == "Vegetation_Temperature":
Observation_Variance[Observation_Matrix_None_NA_Index] = numpy.square(Observation_Matrix[Observation_Matrix_None_NA_Index] * 0.01)
Observation_Variance[Observation_Matrix_None_NA_Index] = 1.0
#if SensorType == "Terra" or SensorType == "Aqua":
# Observation_Variance[Observation_Matrix_None_NA_Index] = 0.25 # http://landval.gsfc.nasa.gov/ProductStatus.php?ProductID=MOD11
if numpy.sum(Variable_Assimilation_Flag) > 0:
Observation_File.close()
Grid_Resolution_CEA_Local = (Observation_X_Right-Observation_X_Left)/Col_Numbers
Observation_Corelation_Par = numpy.zeros((5, 2))
Observation_Corelation_Par[0, 0] = 2 # exponential Model
#Observation_Corelation_Par[0, 0] = 12 # Gaspari_Cohn Model
Observation_Corelation_Par[1, 0] = 0.0
Observation_Corelation_Par[2, 0] = 1.0
Observation_Corelation_Par[3, 0] = 10.0*Grid_Resolution_CEA_Local
Observation_Corelation_Par[4, 0] = 1.0
print "Observation Variance is:", numpy.mean(Observation_Variance[Observation_Matrix_None_NA_Index])
if Write_DA_File_Flag:
numpy.savetxt(DasPy_Path+"Analysis/DAS_Temp/Observation_Corelation_Par.txt", Observation_Corelation_Par)
numpy.savetxt(DasPy_Path+"Analysis/DAS_Temp/R.txt", Observation_Variance)
numpy.savetxt(DasPy_Path+"Analysis/DAS_Temp/Observation_Matrix.txt",Observation_Matrix)
print " -------------Define Observation Collection NC Files"
NC_FileName_Observation = DAS_Output_Path+"Analysis/"+Region_Name+"/Observation_"+str(Observation_Matrix_Index+1)+".nc"
if os.path.exists(NC_FileName_Observation):
os.remove(NC_FileName_Observation)
if Def_Print:
print 'Write NetCDF File:',NC_FileName_Observation
NC_File_Observation = netCDF4.Dataset(NC_FileName_Observation, 'w', diskless=True, persist=True, format='NETCDF4')
# Dim the dimensions of NetCDF
NC_File_Observation.createDimension('lon', Observation_NLons)
NC_File_Observation.createDimension('lat', Observation_NLats)
NC_File_Observation.createDimension('misc', 10)
NC_File_Observation.createVariable('Observation_Variance','f4',('lat','lon',),zlib=True)
NC_File_Observation.variables['Observation_Variance'][:,:] = Observation_Variance
NC_File_Observation.createVariable('Observation_Latitude','f4',('lat','lon',),zlib=True)
NC_File_Observation.variables['Observation_Latitude'][:,:] = Observation_Latitude
NC_File_Observation.createVariable('Observation_Longitude','f4',('lat','lon',),zlib=True)
NC_File_Observation.variables['Observation_Longitude'][:,:] = Observation_Longitude
NC_File_Observation.createVariable('Observation_Matrix','f4',('lat','lon',),zlib=True)
NC_File_Observation.variables['Observation_Matrix'][:,:] = Observation_Matrix
NC_File_Observation.createVariable('Observation_View_Zenith_Angle','f4',('lat','lon',),zlib=True)
NC_File_Observation.variables['Observation_View_Zenith_Angle'][:,:] = Observation_View_Zenith_Angle
NC_File_Observation.createVariable('Observation_View_Time','f4',('lat','lon',),zlib=True)
NC_File_Observation.variables['Observation_View_Time'][:,:] = Observation_View_Time
NC_File_Observation.createVariable('Observation_Misc','f4',('misc','lat','lon',),zlib=True)
NC_File_Observation.variables['Observation_Misc'][:,:,:] = Observation_Misc
NC_File_Observation.sync()
NC_File_Observation.close()
numexpr_a = []
numexpr_b = []
numexpr_c = []
del Observation_Variance, Observation_Latitude, Observation_Longitude, Observation_Matrix, Observation_View_Zenith_Angle, Observation_View_Time
r('gc(TRUE)')
gc.collect()
del gc.garbage[:]
return Observation_NLons, Observation_NLats, Observation_X_Left, Observation_X_Right, Observation_Y_Lower, Observation_Y_Upper, \
Observation_Corelation_Par, Observation_Bias_Range, Observation_Bias_Range_STD, Observation_Bias_Initialization_Flag
def Read_History_File(Ens_Index, Model_Driver, Def_First_Run, Def_Region, Def_PP, Dim_CLM_State, Row_Numbers, Col_Numbers, column_len, pft_len, \
Datetime_Start, Datetime_Stop, Start_Year, Stop_Month, Region_Name, Run_Dir_Home, history_file_name, Ensemble_Number, Constant_File_Name_Header,
Variable_Assimilation_Flag, Variable_List, Additive_Noise_SM, Additive_Noise_ST, N0, nlyr,
Mean_Dir, Two_Step_Bias_Estimation_Active, Feedback_Assim, Soil_Texture_Layer_Opt_Num,
Grid_Resolution_CEA, Grid_Resolution_GEO, MODEL_X_Left, MODEL_X_Right, MODEL_Y_Lower, MODEL_Y_Upper,
SensorType, SensorVariable, Variable_ID, Analysis_Variable_Name, Soil_Layer_Num, ParFlow_Layer_Num, numrad, Def_ParFor, DAS_Depends_Path, DAS_Data_Path, Def_Print,
Irrig_Scheduling, Density_of_liquid_water, Density_of_ice, NAvalue, CLM_NA, omp_get_num_procs_ParFor, DAS_Output_Path, \
NC_FileName_Assimilation_2_Constant, NC_FileName_Assimilation_2_Diagnostic, NC_FileName_Assimilation_2_Initial, \
NC_FileName_Assimilation_2_Bias, NC_FileName_Assimilation_2_Parameter, finidat_name_string, Plot_Analysis, DasPy_Path, *vartuple):
# numpy.savez("Read_History_File.npz",Ens_Index, Dim_CLM_State, Row_Numbers, Col_Numbers, Run_Dir_Home, history_file_name, Ensemble_Number, Constant_File_Name_Header, Bias_Forecast, Additive_Noise_SM, \
# Soil_Moisture_DA_Flag, Surface_Temperature_DA_Flag, Vegetation_Temperature_DA_Flag, Albedo_DA_Flag, Snow_Depth_DA_Flag, Snow_Cover_Fraction_DA_Flag,Canopy_Water_DA_Flag,
# Snow_Water_Equivalent_DA_Flag, Crop_Planting_DA_Flag, Crop_Harvest_DA_Flag, LAI_DA_Flag, Latent_Heat_DA_Flag, Latent_Heat_Daily_DA_Flag, Sensible_Heat_DA_Flag, Water_Storage_DA_Flag, Water_Table_Depth_DA_Flag, Emissivity_DA_Flag, \
# SensorType, SensorVariable, Teta_Residual, Teta_Saturated, Teta_Field_Capacity, Teta_Wilting_Point, Analysis_Variable_Name, Soil_Layer_Num, numrad, Def_ParFor, DAS_Depends_Path, \
# Irrigation_Rate_DA_Flag, Irrig_Scheduling, Irrigation_Scheduling_Flag, Model_Driver, Density_of_liquid_water, Density_of_ice, NAvalue, CLM_NA, omp_get_num_procs_ParFor)
COSMIC_Py = imp.load_source("COSMIC_Py",DasPy_Path+"ObsModel/COSMOS/COSMIC_Py.py")
COSMIC = imp.load_dynamic("COSMIC",DasPy_Path+"ObsModel/COSMOS/COSMIC.so")
Clumping_Index = imp.load_source("Clumping_Index",DasPy_Path+"ObsModel/LST/Clumping_Index.py")
ParFor = imp.load_source("ParFor",DasPy_Path+"ParFor.py")
CLM_Initial_File = netCDF4.Dataset(finidat_name_string, 'r')
cols1d_ixy = CLM_Initial_File.variables['cols1d_ixy'][:]
cols1d_jxy = CLM_Initial_File.variables['cols1d_jxy'][:]
cols1d_ityplun = CLM_Initial_File.variables['cols1d_ityplun'][:]
#numpy.savetxt('cols1d_ixy',cols1d_ixy)
#numpy.savetxt('cols1d_jxy',cols1d_jxy)
pfts1d_ixy = CLM_Initial_File.variables['pfts1d_ixy'][:]
pfts1d_jxy = CLM_Initial_File.variables['pfts1d_jxy'][:]
pfts1d_itypveg = CLM_Initial_File.variables['pfts1d_itypveg'][:]
pfts1d_ci = CLM_Initial_File.variables['pfts1d_ci'][:]
pfts1d_ityplun = CLM_Initial_File.variables['pfts1d_ityplun'][:]
CLM_Initial_File.close()
NC_File_Out_Assimilation_2_Constant = netCDF4.Dataset(NC_FileName_Assimilation_2_Constant, 'r')
PCT_Veg = NC_File_Out_Assimilation_2_Constant.variables['PCT_Veg'][:,:]
STD_ELEV = NC_File_Out_Assimilation_2_Constant.variables['STD_ELEV'][:,:]
DEM_Data = NC_File_Out_Assimilation_2_Constant.variables['DEM_Data'][:,:]
Land_Mask_Data = NC_File_Out_Assimilation_2_Constant.variables['Land_Mask_Data'][:,:]
Bulk_Density_Top_Region = NC_File_Out_Assimilation_2_Constant.variables['Bulk_Density_Top_Region'][:,:]
Bulk_Density_Sub_Region = NC_File_Out_Assimilation_2_Constant.variables['Bulk_Density_Sub_Region'][:,:]
PFT_Dominant_Index = NC_File_Out_Assimilation_2_Constant.variables['PFT_Dominant_Index'][:,:]
Bare_Grid_Index = numpy.where(PFT_Dominant_Index == 0)
NC_File_Out_Assimilation_2_Initial = netCDF4.Dataset(NC_FileName_Assimilation_2_Initial, 'r')
Soil_Layer_Thickness_Ratio_Moisture = NC_File_Out_Assimilation_2_Constant.variables['Soil_Layer_Thickness_Ratio_Moisture'][:, :, :]
Soil_Layer_Thickness_Ratio_Moisture_Sum = numpy.sum(Soil_Layer_Thickness_Ratio_Moisture,axis=0)
for Soil_Layer_Index in range(Soil_Layer_Num):
Soil_Layer_Thickness_Ratio_Moisture[Soil_Layer_Index,:,:] = Soil_Layer_Thickness_Ratio_Moisture[Soil_Layer_Index,:,:]/Soil_Layer_Thickness_Ratio_Moisture_Sum
PCT_LAKE = NC_File_Out_Assimilation_2_Constant.variables['PCT_LAKE'][:,:]
PCT_LAKE_Index = numpy.where(PCT_LAKE > 50)
NC_File_Out_Assimilation_2_Parameter = netCDF4.Dataset(NC_FileName_Assimilation_2_Parameter, 'r')
Parameter_Soil_Space_Ensemble = numpy.mean(NC_File_Out_Assimilation_2_Parameter.variables['Parameter_Soil_Space_Ensemble'][:,:,:,:],axis=0)
#Parameter_Soil_Space_Ensemble = NC_File_Out_Assimilation_2_Parameter.variables['Parameter_Soil_Space_Ensemble'][Ens_Index,:,:,:]
NC_File_Out_Assimilation_2_Parameter.close()
Sand_Top_Region = Parameter_Soil_Space_Ensemble[0,::]
Sand_Sub_Region = Parameter_Soil_Space_Ensemble[1,::]
Clay_Top_Region = Parameter_Soil_Space_Ensemble[0+Soil_Texture_Layer_Opt_Num,::]
Clay_Sub_Region = Parameter_Soil_Space_Ensemble[1+Soil_Texture_Layer_Opt_Num,::]
Prop_Grid_Array_Sys_Sub = numpy.zeros((Dim_CLM_State, Row_Numbers, Col_Numbers),dtype=numpy.float32)
CLM_Soil_Moisture_Ensemble_Mat_Sub = numpy.zeros((Soil_Layer_Num, Row_Numbers, Col_Numbers),dtype=numpy.float32)
CLM_Soil_Temperature_Ensemble_Mat_Sub = numpy.zeros((Soil_Layer_Num, Row_Numbers, Col_Numbers),dtype=numpy.float32)
CLM_ROOTFR_Ensemble_Mat_Sub = numpy.zeros((Soil_Layer_Num, Row_Numbers, Col_Numbers),dtype=numpy.float32)
CLM_ROOTR_Ensemble_Mat_Sub = numpy.zeros((Soil_Layer_Num, Row_Numbers, Col_Numbers),dtype=numpy.float32)
CLM_Soil_Moisture = numpy.zeros((Soil_Layer_Num, Row_Numbers, Col_Numbers),dtype=numpy.float32) # Units: m3/m3
CLM_Soil_Temperature = numpy.zeros((Soil_Layer_Num, Row_Numbers, Col_Numbers),dtype=numpy.float32) # soil-snow temperature Units: K
CLM_ROOTFR = numpy.zeros((Soil_Layer_Num, Row_Numbers, Col_Numbers),dtype=numpy.float32) # fraction of roots in each soil layer
CLM_ROOTR = numpy.zeros((Soil_Layer_Num, Row_Numbers, Col_Numbers),dtype=numpy.float32) # effective fraction of roots in each soil layer
CLM_Ground_Temperature = numpy.zeros((Row_Numbers, Col_Numbers),dtype=numpy.float32) # Units: K
CLM_Onset_Freezing_Degree_Days_Counter = numpy.zeros((Row_Numbers, Col_Numbers),dtype=numpy.float32) # Units: C degree-days
CLM_Vegetation_Temperature = numpy.zeros((Row_Numbers, Col_Numbers),dtype=numpy.float32) # Units: K
CLM_Urban_Ground_Temperature = numpy.zeros((Row_Numbers, Col_Numbers),dtype=numpy.float32) # Urban Ground Temperature Units: K
CLM_Rural_Ground_Temperature = numpy.zeros((Row_Numbers, Col_Numbers),dtype=numpy.float32) # Rural Ground Temperature Units: K
CLM_Lake_Temperature = numpy.zeros((10,Row_Numbers, Col_Numbers),dtype=numpy.float32)
CLM_LAI = numpy.zeros((Row_Numbers, Col_Numbers),dtype=numpy.float32)
CLM_Albedo = numpy.zeros((numrad*2, Row_Numbers, Col_Numbers),dtype=numpy.float32) # Units None
CLM_Snow_Depth = numpy.zeros((Row_Numbers, Col_Numbers),dtype=numpy.float32) # Units Meters
CLM_INT_SNOW = numpy.zeros((Row_Numbers, Col_Numbers),dtype=numpy.float32) # Units mm
CLM_FH2OSFC = numpy.zeros((Row_Numbers, Col_Numbers),dtype=numpy.float32) # surface water mm
CLM_Snow_Cover_Fraction = numpy.zeros((Row_Numbers, Col_Numbers),dtype=numpy.float32) # Units Meters
CLM_Snow_Water = numpy.zeros((Row_Numbers, Col_Numbers),dtype=numpy.float32)
CLM_QIRRIG = numpy.zeros((Row_Numbers, Col_Numbers),dtype=numpy.float32)
CLM_Soil_Moisture_Ratio = numpy.ones((Soil_Layer_Num, Row_Numbers,Col_Numbers),dtype=numpy.float32) # Ration Among the different columns
CLM_Soil_Temperature_Ratio = numpy.ones((Soil_Layer_Num, Row_Numbers,Col_Numbers),dtype=numpy.float32) # Ration Among the different columns
CLM_Soil_Moisture_Ratio_MultiScale = numpy.ones((Soil_Layer_Num, Row_Numbers,Col_Numbers),dtype=numpy.float32) # Ration Among the different columns
CLM_HTOP = numpy.zeros((Row_Numbers, Col_Numbers),dtype=numpy.float32)
CLM_HBOT = numpy.zeros((Row_Numbers, Col_Numbers),dtype=numpy.float32)
CLM_Water_Storage = numpy.zeros((Row_Numbers, Col_Numbers),dtype=numpy.float32)
CLM_Water_Table_Depth = numpy.zeros((Row_Numbers, Col_Numbers),dtype=numpy.float32)
CLM_Irrigation_Rate = numpy.zeros((Row_Numbers, Col_Numbers),dtype=numpy.float32)
CLM_Latent_Heat_Daily = numpy.zeros((Row_Numbers, Col_Numbers),dtype=numpy.float32) # Units: W/m^2
CLM_Sensible_Heat = numpy.zeros((Row_Numbers, Col_Numbers),dtype=numpy.float32) # Units: W/m^2
CLM_Latent_Heat = numpy.zeros((Row_Numbers, Col_Numbers),dtype=numpy.float32) # Units: W/m^2
CLM_Vcmax_SCOPE = numpy.zeros((Row_Numbers, Col_Numbers),dtype=numpy.float32) # Units: umol co2/m**2/s
CLM_m_SCOPE = numpy.zeros((Row_Numbers, Col_Numbers),dtype=numpy.float32) # Units:
CLM_SLA_SCOPE = numpy.zeros((Row_Numbers, Col_Numbers),dtype=numpy.float32) # Units: m2 g-1 C)
CLM_2m_Air_Temperature = numpy.zeros((Row_Numbers, Col_Numbers),dtype=numpy.float32) # Units: K
CLM_Air_Pressure = numpy.zeros((Row_Numbers, Col_Numbers),dtype=numpy.float32)
CLM_Shortwave_Radiation = numpy.zeros((Row_Numbers, Col_Numbers),dtype=numpy.float32)
CLM_Longwave_Radiation = numpy.zeros((Row_Numbers, Col_Numbers),dtype=numpy.float32)
CLM_Specific_Humdity = numpy.zeros((Row_Numbers, Col_Numbers),dtype=numpy.float32)
CLM_Wind_Speed = numpy.zeros((Row_Numbers, Col_Numbers),dtype=numpy.float32)
CLM_Z0MV = numpy.zeros((Row_Numbers, Col_Numbers),dtype=numpy.float32)
CLM_DISPLA = numpy.zeros((Row_Numbers, Col_Numbers),dtype=numpy.float32)
Analysis_Variable_Name = ['' for i in range(Dim_CLM_State)]
Soil_Layer_Index_DA = 0
# For soil moisture, soil temperature bias estimation, we need the mean model simulation, for latent and sensbile heat bias estimation (observation bias)
# We use the ensemble simulation
if Two_Step_Bias_Estimation_Active and (not Variable_Assimilation_Flag[Variable_List.index("Latent_Heat")] == 1) and \
(not Variable_Assimilation_Flag[Variable_List.index("Sensible_Heat")] == 1):
Run_Dir = Mean_Dir
else:
Run_Dir = Run_Dir_Home+"_Ens"+str(Ens_Index+1)
if Def_Print:
print "Open History File:", Run_Dir+"/"+history_file_name
try:
CLM_History_File = netCDF4.Dataset(Run_Dir+"/"+history_file_name, 'r')
except:
print Run_Dir+"/"+history_file_name,"does not exist!...\n"
os.abort()
# if history_file_name[-20:-1] == finidat_name[-20:-1]:
# Constant_File_Name = finidat_name
# else:
#Constant_File_Name = []
# if Def_First_Run == 1:
# Constant_File_Name = Run_Dir +"/"+ CLM_History_File.Time_constant_3Dvars_filename[2:]
#Constant_File_Name = Run_Dir +"/"+ Region_Name+'.clm2.h0.'+Start_Year+'-'+Start_Month+'-'+Start_Day+'-'+str((Datetime_Start - Datetime_Start_Init).seconds)+'.nc'
if Ensemble_Number == 1:
Constant_File_Name = Run_Dir_Home +"/"+ Constant_File_Name_Header
else:
if Def_Region == 4 or Def_Region == 8 or Def_Region == 9:
if Def_First_Run == 1:
Constant_File_Name = Run_Dir+ Constant_File_Name_Header
else:
Mean_Dir = Run_Dir_Home+"_Ens_Mean"
Constant_File_Name = Mean_Dir +"/"+ Constant_File_Name_Header
else:
Constant_File_Name = Run_Dir +"/"+ Constant_File_Name_Header
CLM_Onset_Freezing_Degree_Days_Counter = numpy.flipud(CLM_History_File.variables['ONSET_FDD'][0, :, :]) # onset freezing degree days counter
if Variable_Assimilation_Flag[Variable_List.index("Soil_Moisture")] == 1 or Feedback_Assim == 1:
Analysis_Variable_Name[0] = "Soil Moisture"
if Def_Print:
print Analysis_Variable_Name[0]
#------------------------------------------- Read the Soil Moisture Data
if True:
CLM_Ground_Temperature = numpy.flipud(CLM_History_File.variables['TG'][0, :, :]) # Ground Temperature Units: K
CLM_Ground_Temperature[numpy.isnan(CLM_Ground_Temperature)] = 283.15
CLM_Vegetation_Temperature = numpy.flipud(CLM_History_File.variables['TV'][0, :, :]) # Units: K
CLM_Vegetation_Temperature[numpy.isnan(CLM_Vegetation_Temperature)] = 283.15
CLM_Snow_Depth = numpy.flipud(CLM_History_File.variables['SNOWDP'][0, :, :])
#CLM_Snow_Depth[numpy.ma.getmask(CLM_Snow_Depth)] = NAvalue
CLM_Snow_Water = numpy.flipud(CLM_History_File.variables['H2OSNO'][0, :, :]) # Snow Water: Units: (mm)
#CLM_Snow_Water[numpy.ma.getmask(CLM_Snow_Water)] = NAvalue
CLM_2m_Air_Temperature = numpy.flipud(CLM_History_File.variables['TSA'][0, :, :])
#CLM_2m_Air_Temperature[numpy.ma.getmask(CLM_2m_Air_Temperature)] = 273.15
CLM_Air_Pressure = numpy.flipud(CLM_History_File.variables['PSurf'][0, :, :])
for Soil_Layer_Index in range(Soil_Layer_Num-5):
#CLM_Soil_Moisture[Soil_Layer_Index, :, :] = numpy.flipud(CLM_History_File.variables['H2OSOI'][0, Soil_Layer_Index, :, :])
CLM_Soil_Moisture[Soil_Layer_Index, :, :] = numpy.flipud(CLM_History_File.variables['H2OSOI'][0, Soil_Layer_Index, :, :])
CLM_Soil_Temperature[Soil_Layer_Index, :, :] = numpy.flipud(CLM_History_File.variables['TSOI'][0, Soil_Layer_Index, :, :])
CLM_Soil_Moisture_Ratio[Soil_Layer_Index,:,:] = CLM_Soil_Moisture[Soil_Layer_Index, :, :] / CLM_Soil_Moisture[0, :, :]
if Def_Print >= 2:
print "Check the Ourliers"
NA_Flag = False
numexpr_a = CLM_Soil_Temperature[Soil_Layer_Index,:,:]
numexpr_b = CLM_NA
numexpr_c = numpy.where(numexpr_a == numexpr_b)
CLM_Soil_Moisture[Soil_Layer_Index,:,:][numexpr_c] = 0.2
CLM_Soil_Moisture[Soil_Layer_Index,:,:][numpy.isnan(CLM_Soil_Moisture[Soil_Layer_Index,:,:])] = 0.2
Check_Outliers(DasPy_Path, Land_Mask_Data, Def_ParFor,DAS_Depends_Path,omp_get_num_procs_ParFor,CLM_Soil_Moisture[Soil_Layer_Index,:,:],NA_Flag, 'Soil_Moisture', Variable_Assimilation_Flag, Variable_List,
numpy.asarray(NC_File_Out_Assimilation_2_Constant.variables['Teta_Residual'][Soil_Layer_Index,:,:]), numpy.asarray(NC_File_Out_Assimilation_2_Constant.variables['Teta_Saturated'][Soil_Layer_Index,:,:]),
numpy.asarray(NC_File_Out_Assimilation_2_Constant.variables['Teta_Field_Capacity'][Soil_Layer_Index,:,:]), numpy.asarray(NC_File_Out_Assimilation_2_Constant.variables['Teta_Wilting_Point'][Soil_Layer_Index,:,:]), NAvalue)
CLM_Soil_Moisture_Ensemble_Mat_Sub[Soil_Layer_Index,:,:] = CLM_Soil_Moisture[Soil_Layer_Index, :, :]
numexpr_a = CLM_Soil_Temperature[Soil_Layer_Index,:,:]
numexpr_b = CLM_NA
numexpr_c = numpy.where(numexpr_a == numexpr_b)
CLM_Soil_Temperature[Soil_Layer_Index,:,:][numexpr_c] = 283.15
CLM_Soil_Temperature[Soil_Layer_Index,:,:][numpy.isnan(CLM_Soil_Temperature[Soil_Layer_Index,:,:])] = 283.15
Check_Outliers(DasPy_Path, Land_Mask_Data, Def_ParFor,DAS_Depends_Path,omp_get_num_procs_ParFor,CLM_Soil_Temperature[Soil_Layer_Index, :, :],NA_Flag,'Soil_Temperature', Variable_Assimilation_Flag, Variable_List,
numpy.asarray(NC_File_Out_Assimilation_2_Constant.variables['Teta_Residual'][0,:,:]), numpy.asarray(NC_File_Out_Assimilation_2_Constant.variables['Teta_Saturated'][0,:,:]),
numpy.asarray(NC_File_Out_Assimilation_2_Constant.variables['Teta_Field_Capacity'][0,:,:]), numpy.asarray(NC_File_Out_Assimilation_2_Constant.variables['Teta_Wilting_Point'][0,:,:]), NAvalue)
CLM_Soil_Temperature_Ensemble_Mat_Sub[Soil_Layer_Index,:,:] = CLM_Soil_Temperature[Soil_Layer_Index, :, :]
try:
SensorType_Name = SensorType[SensorVariable.index("Soil_Moisture")]
if SensorType_Name == 'ECV_SM' or SensorType_Name == 'AMSR_E' or SensorType_Name == 'SMOS' or SensorType_Name == 'ASCAT' or SensorType_Name == 'ASAR' or SensorType_Name == 'PALSAR':
Soil_Layer_Index_DA = 1
elif SensorType_Name == 'Terra' or SensorType_Name == 'Aqua':
Soil_Layer_Index_DA = 2
elif SensorType_Name == "InSitu":
Soil_Layer_Index_DA = 1
elif SensorType_Name == "COSMOS":
Soil_Layer_Index_DA = 0
except:
SensorType_Name = "InSitu"
Soil_Layer_Index_DA = 1
Prop_Grid_Array_Sys_Sub[0, :, :] = CLM_Soil_Moisture[Soil_Layer_Index_DA, :, :] + Additive_Noise_SM[Ens_Index, Soil_Layer_Index_DA]
if SensorType_Name == "COSMOS":
CLM_Soil_Moisture_Ratio_MultiScale[:, :, :] = 1.0
CLM_Soil_Moisture_Ensemble_Mat_Sub[:,:,:] = CLM_Soil_Moisture[:, :, :]
Air_Pressure = CLM_Air_Pressure
Observation_Frequency = 1 # Hours
#Sensor_Layer, Sensor_Depth, Sensor_Soil_Moisture, N_uncorr = COSMOS(N0, nlyr, Def_Print, Observation_Frequency, DEM_Data, CLM_Soil_Moisture, CLM_Soil_Layer_Thickness, Air_Pressure, Bulk_Density_Top_Region, Bulk_Density_Sub_Region, Row_Numbers, Col_Numbers, Soil_Layer_Num)
Mask = numpy.zeros((Row_Numbers, Col_Numbers),dtype=numpy.bool)
Mask[::] = True
numexpr_a = CLM_Soil_Moisture[0,:,:]
numexpr_b = NAvalue
numexpr_c = numpy.where(numexpr_a == numexpr_b)
Mask[numexpr_c] = False
Mask_Col = Mask.flatten()
Mask_Index = numpy.where(Mask_Col == True)
Mask_Size = numpy.size(Mask_Index)
CLM_Soil_Layer_Thickness_Cumsum = numpy.asarray(NC_File_Out_Assimilation_2_Constant.variables['CLM_Soil_Layer_Thickness_Cumsum'][:,:,:]) * 100
soil_moisture = numpy.zeros((Mask_Size,Soil_Layer_Num-5),dtype=numpy.float32)
layerz = numpy.zeros((Mask_Size,Soil_Layer_Num-5),dtype=numpy.float32)
for Soil_Layer_Index in range(Soil_Layer_Num-5):
soil_moisture[:,Soil_Layer_Index] = CLM_Soil_Moisture[Soil_Layer_Index,:,:].flatten()[Mask_Index]
layerz[:,Soil_Layer_Index] = CLM_Soil_Layer_Thickness_Cumsum[Soil_Layer_Index,:,:].flatten()[Mask_Index]
bd = Bulk_Density_Top_Region.flatten()[Mask_Index]
n = numpy.zeros(Mask_Size,dtype=numpy.float32)
lattwat = numpy.zeros(Mask_Size,dtype=numpy.float32)
n[:] = N0
lattwat[:] = 0.03
nthreads = omp_get_num_procs_ParFor
Neutron_COSMOS, Sensor_Soil_Moisture_COSMOS, Sensor_Depth_COSMOS = COSMIC_Py.COSMIC_Py(COSMIC,n,nlyr,soil_moisture,layerz,bd,lattwat,nthreads)
Sensor_Soil_Moisture = numpy.zeros((Row_Numbers, Col_Numbers),dtype=numpy.float32)
Sensor_Soil_Moisture_Col = Sensor_Soil_Moisture.flatten()
Sensor_Soil_Moisture_Col[Mask_Index] = Sensor_Soil_Moisture_COSMOS
Sensor_Soil_Moisture = numpy.reshape(Sensor_Soil_Moisture_Col,(Row_Numbers, Col_Numbers))
Prop_Grid_Array_Sys_Sub[0, :, :] = Sensor_Soil_Moisture + Additive_Noise_SM[Ens_Index, Soil_Layer_Index_DA]
#Prop_Grid_Array_Sys_Sub[0, :, :] = CLM_Soil_Moisture[1, :, :]
if Plot_Analysis >= 1:
import matplotlib
# Force matplotlib to not use any Xwindows backend.
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import matplotlib.colors as colors
Mask_Valid = numpy.zeros((Row_Numbers,Col_Numbers),dtype=numpy.bool)
Mask_Valid[::] = False
numexpr_a = Land_Mask_Data
numexpr_b = NAvalue
numexpr_c = numpy.where(numexpr_a == numexpr_b)
Mask_Valid[numexpr_c] = True
Data1 = numpy.ma.masked_where(Mask_Valid, CLM_Soil_Moisture[1, :, :])
Data2 = numpy.ma.masked_where(Mask_Valid, Sensor_Soil_Moisture[:, :])
Data3 = numpy.ma.masked_where(Mask_Valid, Sensor_Soil_Moisture)
Variable_Min = 0.05
Variable_Max = 0.55
ticks = numpy.arange(Variable_Min, Variable_Max, (Variable_Max - Variable_Min) / 5.0)
color_boun_list = []
color_bound = [Variable_Min, Variable_Max, (Variable_Max - Variable_Min) / 100.0]
for i in range(int((color_bound[1] - color_bound[0]) / color_bound[2])):
color_bound[0] += color_bound[2]
color_boun_list.append(color_bound[0])
fig1 = plt.figure(figsize=(15, 10), dpi=80)
ax = fig1.add_subplot(1, 3, 1)
im1 = ax.imshow(Data1, cmap=cm.jet, norm=colors.BoundaryNorm(color_boun_list, ncolors=300))
plt.colorbar(im1, ticks=ticks, orientation='horizontal')
ax.set_title('CLM_Soil_Moisture')
ax = fig1.add_subplot(1, 3, 2)
im1 = ax.imshow(Data2, cmap=cm.jet, norm=colors.BoundaryNorm(color_boun_list, ncolors=300))
plt.colorbar(im1, ticks=ticks, orientation='horizontal')
ax.set_title('CLM_Soil_Moisture_Smoothed')
ax = fig1.add_subplot(1, 3, 3)
im1 = ax.imshow(Data3, cmap=cm.jet, norm=colors.BoundaryNorm(color_boun_list, ncolors=300))
plt.colorbar(im1, ticks=ticks, orientation='horizontal')
ax.set_title('Sensor_Soil_Moisture')
plt.grid(True)
plt.savefig(DasPy_Path+"Analysis/DAS_Temp/"+Region_Name+"/COSMOS_SM_Operator_XF.png")
plt.close('all')
del Mask, numexpr_a, numexpr_b, numexpr_c, Mask_Col, Mask_Index, CLM_Soil_Layer_Thickness_Cumsum, soil_moisture, layerz, n, lattwat
del Neutron_COSMOS, Sensor_Soil_Moisture_COSMOS, Sensor_Depth_COSMOS, Sensor_Soil_Moisture
else:
Prop_Grid_Array_Sys_Sub[0, :, :] = CLM_Soil_Moisture[Soil_Layer_Index_DA, :, :] + Additive_Noise_SM[Ens_Index, Soil_Layer_Index_DA]
if Def_Print >= 2:
print "Check the Ourliers"
NA_Flag = False
numexpr_a = Prop_Grid_Array_Sys_Sub[0, :, :]
numexpr_b = CLM_NA
numexpr_c = numpy.where(numexpr_a == numexpr_b)
Prop_Grid_Array_Sys_Sub[0, :, :][numexpr_c] = 0.2
Prop_Grid_Array_Sys_Sub[0, :, :][numpy.isnan(Prop_Grid_Array_Sys_Sub[0, :, :])] = 0.2
Check_Outliers(DasPy_Path, Land_Mask_Data, Def_ParFor,DAS_Depends_Path,omp_get_num_procs_ParFor,Prop_Grid_Array_Sys_Sub[0, :, :],NA_Flag, 'Soil_Moisture', Variable_Assimilation_Flag, Variable_List,
numpy.asarray(NC_File_Out_Assimilation_2_Constant.variables['Teta_Residual'][Soil_Layer_Index_DA,:,:]), numpy.asarray(NC_File_Out_Assimilation_2_Constant.variables['Teta_Saturated'][Soil_Layer_Index_DA,:,:]),
numpy.asarray(numpy.asarray(NC_File_Out_Assimilation_2_Constant.variables['Teta_Field_Capacity'][Soil_Layer_Index_DA,:,:])), numpy.asarray(NC_File_Out_Assimilation_2_Constant.variables['Teta_Wilting_Point'][Soil_Layer_Index_DA,:,:]), NAvalue)
CLM_LAI = numpy.flipud(CLM_History_File.variables['TLAI'][0, ::]) # Units: m2/m2
if Def_Print >= 2:
print "Check the Ourliers"
NA_Flag = False
Check_Outliers(DasPy_Path, Land_Mask_Data, Def_ParFor,DAS_Depends_Path,omp_get_num_procs_ParFor,CLM_LAI,NA_Flag, "LAI", Variable_Assimilation_Flag, Variable_List,
numpy.asarray(NC_File_Out_Assimilation_2_Constant.variables['Teta_Residual'][0,:,:]), numpy.asarray(NC_File_Out_Assimilation_2_Constant.variables['Teta_Saturated'][0,:,:]),
numpy.asarray(NC_File_Out_Assimilation_2_Constant.variables['Teta_Field_Capacity'][0,:,:]), numpy.asarray(NC_File_Out_Assimilation_2_Constant.variables['Teta_Wilting_Point'][0,:,:]), NAvalue)
Prop_Grid_Array_Sys_Sub[12, :, :] = CLM_LAI[:, :]
if Variable_Assimilation_Flag[Variable_List.index("Surface_Temperature")] == 1 or Feedback_Assim == 1:
Analysis_Variable_Name[1] = "Soil Temperature"
if Def_Print:
print Analysis_Variable_Name[1]
#------------------------------------------- Read the Soil Temperature Data
CLM_Ground_Temperature = numpy.flipud(CLM_History_File.variables['TG'][0, :, :]) # Ground Temperature Units: K
CLM_Ground_Temperature[numpy.isnan(CLM_Ground_Temperature)] = 283.15
CLM_Vegetation_Temperature[numpy.isnan(CLM_Vegetation_Temperature)] = 283.15
#print numpy.max(CLM_Vegetation_Temperature),numpy.min(CLM_Vegetation_Temperature)
CLM_Urban_Ground_Temperature = numpy.flipud(CLM_History_File.variables['TG_U'][0, :, :]) # Urban Ground Temperature Units: K
CLM_Rural_Ground_Temperature = numpy.flipud(CLM_History_File.variables['TG_R'][0, :, :]) # Rural Ground Temperature Units: K
#CLM_Snow_Temperature = # T_SOISNO
for Soil_Layer_Index in range(Soil_Layer_Num):
if Def_Print >= 2:
print "Check the Ourliers"
NA_Flag = False
CLM_Soil_Temperature[Soil_Layer_Index, :, :] = numpy.flipud(CLM_History_File.variables['TSOI'][0, Soil_Layer_Index, :, :])
CLM_Soil_Temperature_Ratio[Soil_Layer_Index,:,:] = CLM_Soil_Temperature[Soil_Layer_Index, :, :] / CLM_Soil_Temperature[0, :, :]
numexpr_a = CLM_Soil_Temperature[Soil_Layer_Index,:,:]
numexpr_b = CLM_NA
numexpr_c = numpy.where(numexpr_a == numexpr_b)
CLM_Soil_Temperature[Soil_Layer_Index,:,:][numexpr_c] = 283.15
CLM_Soil_Temperature[Soil_Layer_Index,:,:][numpy.isnan(CLM_Soil_Temperature[Soil_Layer_Index,:,:])] = 283.15
Check_Outliers(DasPy_Path, Land_Mask_Data, Def_ParFor,DAS_Depends_Path,omp_get_num_procs_ParFor,CLM_Soil_Temperature[Soil_Layer_Index, :, :],NA_Flag,'Soil_Temperature', Variable_Assimilation_Flag, Variable_List,
numpy.asarray(NC_File_Out_Assimilation_2_Constant.variables['Teta_Residual'][0,:,:]), numpy.asarray(NC_File_Out_Assimilation_2_Constant.variables['Teta_Saturated'][0,:,:]),
numpy.asarray(NC_File_Out_Assimilation_2_Constant.variables['Teta_Field_Capacity'][0,:,:]), numpy.asarray(NC_File_Out_Assimilation_2_Constant.variables['Teta_Wilting_Point'][0,:,:]), NAvalue)
CLM_Soil_Temperature_Ensemble_Mat_Sub[Soil_Layer_Index,:,:] = CLM_Soil_Temperature[Soil_Layer_Index, :, :]
if Soil_Layer_Index <= 9:
CLM_Lake_Temperature[Soil_Layer_Index, :, :] = numpy.flipud(CLM_History_File.variables['TLAKE'][0, Soil_Layer_Index, :, :]) # Lake Ground Temperature Units: K
# Assign the Lake temperature to lake grid cells
Check_Outliers(DasPy_Path, Land_Mask_Data, Def_ParFor,DAS_Depends_Path,omp_get_num_procs_ParFor,CLM_Lake_Temperature[Soil_Layer_Index,::],NA_Flag, 'Soil_Temperature', Variable_Assimilation_Flag, Variable_List,
numpy.asarray(NC_File_Out_Assimilation_2_Constant.variables['Teta_Residual'][0,:,:]), numpy.asarray(NC_File_Out_Assimilation_2_Constant.variables['Teta_Saturated'][0,:,:]),
numpy.asarray(NC_File_Out_Assimilation_2_Constant.variables['Teta_Field_Capacity'][0,:,:]), numpy.asarray(NC_File_Out_Assimilation_2_Constant.variables['Teta_Wilting_Point'][0,:,:]), NAvalue)
CLM_Soil_Temperature[Soil_Layer_Index, :, :][PCT_LAKE_Index] = CLM_Lake_Temperature[Soil_Layer_Index, :, :][PCT_LAKE_Index]
CLM_Soil_Temperature_Ensemble_Mat_Sub[Soil_Layer_Index, :, :][PCT_LAKE_Index] = CLM_Soil_Temperature[Soil_Layer_Index, :, :][PCT_LAKE_Index]
#print CLM_Ground_Temperature
if Def_Print >= 2:
print "Check the Ourliers"
NA_Flag = False
#print CLM_Ground_Temperature
Check_Outliers(DasPy_Path, Land_Mask_Data, Def_ParFor,DAS_Depends_Path,omp_get_num_procs_ParFor,CLM_Ground_Temperature,NA_Flag, 'Soil_Temperature', Variable_Assimilation_Flag, Variable_List,
numpy.asarray(NC_File_Out_Assimilation_2_Constant.variables['Teta_Residual'][0,:,:]), numpy.asarray(NC_File_Out_Assimilation_2_Constant.variables['Teta_Saturated'][0,:,:]),
numpy.asarray(NC_File_Out_Assimilation_2_Constant.variables['Teta_Field_Capacity'][0,:,:]), numpy.asarray(NC_File_Out_Assimilation_2_Constant.variables['Teta_Wilting_Point'][0,:,:]), NAvalue)
Check_Outliers(DasPy_Path, Land_Mask_Data, Def_ParFor,DAS_Depends_Path,omp_get_num_procs_ParFor,CLM_Vegetation_Temperature,NA_Flag, "Vegetation_Temperature", Variable_Assimilation_Flag, Variable_List,
numpy.asarray(NC_File_Out_Assimilation_2_Constant.variables['Teta_Residual'][0,:,:]), numpy.asarray(NC_File_Out_Assimilation_2_Constant.variables['Teta_Saturated'][0,:,:]),
numpy.asarray(NC_File_Out_Assimilation_2_Constant.variables['Teta_Field_Capacity'][0,:,:]), numpy.asarray(NC_File_Out_Assimilation_2_Constant.variables['Teta_Wilting_Point'][0,:,:]), NAvalue)
Check_Outliers(DasPy_Path, Land_Mask_Data, Def_ParFor,DAS_Depends_Path,omp_get_num_procs_ParFor,CLM_Urban_Ground_Temperature,NA_Flag, 'Soil_Temperature', Variable_Assimilation_Flag, Variable_List,
numpy.asarray(NC_File_Out_Assimilation_2_Constant.variables['Teta_Residual'][0,:,:]), numpy.asarray(NC_File_Out_Assimilation_2_Constant.variables['Teta_Saturated'][0,:,:]),
numpy.asarray(NC_File_Out_Assimilation_2_Constant.variables['Teta_Field_Capacity'][0,:,:]), numpy.asarray(NC_File_Out_Assimilation_2_Constant.variables['Teta_Wilting_Point'][0,:,:]), NAvalue)