forked from scaine1/pyWRF
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathpyWRF.py
2488 lines (1851 loc) · 66.2 KB
/
pyWRF.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
#module: pyWRF
""" This is a python package for those iterested in working with
the Weather Research and Forecasting model output.
Users are required to add PYWRFPATH to their .profile
For example:
export PYWRFPATH=/path/to/pyWRF
you should also add PYWRFPATH to your PYTHONPATH so you can import
pyWRF from any directory you want. i.e.
export PYTHONPATH=$PYTHONPATH:$PYWRFPATH
The pyWRF module comes with a library directory which contains
information required for plotting,microphysics calculations etc.
DO NOT REMOVE THIS DIRECTORY.
Example python scripts can be found in the example_scripts directory.
"""
import sys
import os
PYWRFPATH=os.environ['PYWRFPATH']
sys.path.append(PYWRFPATH+'/library/')
import Nio
import wrf_user_unstagger
import perturbation_variables
import numpy as n
import pylab as pl
import scipy as s
#from mpl_toolkits.basemap import Basemap, shiftgrid
from mpl_toolkits import basemap
import coltbls
import dircache
class calc_vars():
""" This is where routines to calcalate variables should be stored.
If you add something please document the innput and output variables
"""
def __init__(self):
pass
def compute_lat_lon_nmm(self,var):
"""convert lat or lon in degrees (from radians)
Inputs:
-------
GLAT or GLON from NMM core
Returns:
-------
XLAT or XLONG in degrees
"""
if self.wrf_core == 'NMM':
print 'converting your input array from radians to degrees'
outvar=var*57.2957795
else:
print 'you are not using the nmm core and should not need this, returning input variable'
outvar=var
return outvar
def compute_tk(self,pressure=None,theta=None):
"""Compute temperature in kelvin
Inputs:
-------
Pressure (pa I think)
Potential Temperature (Kelvin)
If called without inputs, function will try and get the variables for you.
Returns:
-------
Temperature in Kelvin
"""
if (pressure == None):
try:
pressure=self.variable_dict['PRES']
except:
pressure=self.get_var('PRES')
if (theta == None):
try:
theta=self.variable_dict['THETA']
except:
theta=self.get_var('THETA')
pressure=pressure*100.
print 'calculating temperature in kelvin\n'
p1000mb=100000.
r_d=287.
cp = (7/2.)*r_d
pi=(pressure/p1000mb)**(r_d/cp)
tk=pi*theta
return tk
def compute_rh(self,qvapor=None,pressure=None,temperature=None):
"""Compute the relative humidity
Inputs:
------
Qvapor (kg/kg)
pressure (pa)
Temperature (K) ---> This should be actual temperature not potential temperature I think
***if called without input args function will try to get the variables for you
Returns:
--------
Relative Humidity
"""
if (qvapor == None):
try:
qvapor=self.variable_dict['QVAPOR']
except:
qvapor=self.get_var('QVAPOR')
if (pressure == None):
try:
pressure=self.variable_dict['PRES']
except:
pressure=self.get_var('PRES')
if (temperature == None):
try:
temperature=self.variable_dict['TEMP']
except:
temperature=self.get_var('TEMP')
pressure=pressure*100.
print 'calculating relative humidity\n'
svp1=0.6112
svp2=17.67
svp3=29.65
svpt0=273.15
r_d=287.
r_v=461.6
ep_2=r_d/r_v
ep_3=0.622
es =10.*svp1*n.exp(svp2*(temperature-svpt0)/(temperature-svp3))
qvs =ep_3*es/(0.01 * pressure- (1-ep_3)*es)
qvap_on_qvs=qvapor/qvs
inner_part=n.where(qvap_on_qvs >= 1.0, 1.0,qvap_on_qvs)
rh=100*n.where(inner_part <=0,0,inner_part)
return rh
def compute_vtmk(self,qvapor=None,tmk=None):
"""calculate the virtual temperature
Inputs:
-------
None, will obtain variables for you.
Optional Inputs:
-------
QVAPOR (kg/kg):- use qvapor=
Temperature (kevlin i think): use tmk=
Returns:
-------
Virtual emperature in Kelvin
Exammple:
-------
wf=pyWRF.wrf_file('wrfoutxxxx')
wf.compute_vtmk()
or
qvp=wf.get_var('QVAPOR')
tmk=wf.get_var('TEMP')
wf.compute_vtmk(qvpaor=qvp, tmk=tmk)
Notes:
------
doing this quick, could be errors,check later simon
"""
if (qvapor == None):
try:
qvapor=self.variable_dict['QVAPOR']
except:
qvapor=self.get_var('QVAPOR')
if (tmk == None):
try:
tmk=self.variable_dict['TEMP']
except:
tmk=self.get_var('TEMP')
print 'calculating virtual temperature in kelvin\n'
qvapor_temp=qvapor*0.001
eps=0.622
vtmk=tmk * (eps+qvapor_temp)/(eps*(1.+qvapor_temp))
return vtmk
def compute_td(self,qvapor=None,pressure=None):
"""calculate the dew point temperature
Inputs:
-------
QVAPOR (kg/kg)
Pressure (mb I think)
Returns:
-------
Dew point temperature in Kelvin
Notes:
------
Need to modify this so that it does not matter if pressure is in pa or hpa
"""
if (qvapor == None):
try:
qvapor=self.variable_dict['QVAPOR']
except:
qvapor=self.get_var('QVAPOR')
if (pressure == None):
try:
pressure=self.variable_dict['PRES']
except:
pressure=self.get_var('PRES')
print 'calculating dew point temperature in kelvin\n'
# pressure=pressure/100. #I think pressure needs to be in mb
qv = n.where(qvapor <0.,0.,qvapor)
vapor_pres = (qv*pressure)/(0.622+qv)
vapor_pres = n.where(vapor_pres < 0.001, 0.001,vapor_pres) #avoid problems near zero
td = (243.5*n.log(vapor_pres)-440.8)/(19.48-n.log(vapor_pres))
return td
def compute_mslp(self):
"""calculate mslp using the hypsometric equation in the following form:
MSLP =Psfc*exp^g*dz/(R*T)
Inputs:
-------
Z (distance in meters from the surface to mean sea-level)
g is gravity
R is the dry gas constant
T is the mean layer temperature from the surface to sea-level
Returns:
-------
Mean Sea Level Pressure (in mb)
Notes:
------
"""
if (self.wrf_core == 'ARW') or (self.wrf_core == 'NMM'):
# try:
# psfc=self.variable_dict['PSFC']/100.
# except:
# psfc=self.get_var('PSFC')/100.
try:
pres=self.variable_dict['PRES']
except:
pres=self.get_var('PRES')
try:
Z=self.variable_dict['Z']
except:
Z=self.get_var('Z')
try:
T=self.variable_dict['TEMP']
except:
T=self.get_var('TEMP')
rgas=287.04
grav=9.81
exponent=(grav*Z[0,0,:,:])/(rgas*T[0,0,:,:])
# mslp = psfc[0,:,:]*n.exp(exponent)
mslp = pres[0,0,:,:]*n.exp(exponent)
return mslp
def compute_sph(self,qvapor=None):
"""calculate the specific humidity
Inputs:
-------
QVAPOR (kg/kg)
Returns:
-------
Specific humidity in kg/kg
"""
print 'calculating specific humidity in kg/kg'
if (qvapor == None):
try:
qvapor=self.variable_dict['QVAPOR']
except:
qvapor=self.get_var('QVAPOR')
sph=qvapor/(1+qvapor)
return sph
def compute_sph(self,qvapor=None):
"""calculate the specific humidity
Inputs:
-------
QVAPOR (kg/kg)
Returns:
-------
Specific humidity in kg/kg
"""
print 'calculating specific humidity in kg/kg'
if (qvapor == None):
try:
qvapor=self.variable_dict['QVAPOR']
except:
qvapor=self.get_var('QVAPOR')
sph=qvapor/(1+qvapor)
return sph
def get_ij_lat_long(self,lat_array,long_array,user_lat,user_lon):
"""This function is designed to return the closest grid point to your chosen lat, long.
Inputs:
------
lat_array: (i.e. XLAT)
lon_array: (i.e. XLONG)
user_lat: The lat you want to find
user_lon: The long you want to find.
Returns:
--------
i,j coordinate of the WRF grid point closest to your chosen lat,long.
where i corresponds to ns dimension and j corresponds to the we dimenion (I think)
Notes:
------
lat_array and lon_array currently needs to be 3 dimensional.
the first dimension is time, which wrf creates for no good
reason unles you have a moving nest.
will try and make this script smarter so that it doesnt die
if xlat and xlon is 2d.
"""
del_lat=del_lon=4.0 #2 degrees! this should easily be enough for all possible cases
i=j=[0,0]
loop=1
div_factor_lat=2.0
div_factor_lon=2.0
loop_count=0.
while loop == 1:
while (len(i) > 1) | ( len(j) >1):
upper_lat=user_lat+del_lat
lower_lat=user_lat-del_lat
upper_lon=user_lon+del_lon
lower_lon=user_lon-del_lon
lat_ij=n.where((lat_array[0,:,:] < upper_lat) & (lat_array[0,:,:] >= lower_lat),1,0)
lon_ij=n.where((long_array[0,:,:] > lower_lon) & (long_array[0,:,:] <= upper_lon),1,0)
i,j = n.where((lat_ij == 1) & (lon_ij==1))
del_lat_old=del_lat
del_lon_old=del_lon
del_lat=del_lat/div_factor_lat
del_lon=del_lon/div_factor_lon
# print 'len i j ', len(i),len(j)
#
# print 'del lat',del_lat, 'del lon',del_lon
#
#
# print 'user lat', user_lat, 'user lon', user_lon
#
# print 'lower lat', lower_lat, 'upper lat', upper_lat
#
# print 'lower lon', lower_lon, 'upper lon', upper_lon
#
# print n.sum(lat_ij), n.sum(lon_ij),loop_count
if (loop_count >= 2000):
print i,j
try:
return i[0], j[0]
except:
print 'passing'
pass
#
# print 'div factor lat', div_factor_lat
# print 'div factor lon', div_factor_lon
# print ''
loop_count+=1
# if loop_count == 70:
# raw_input('pause')
if (n.shape(i)[0] == 0):
del_lat=del_lat_old*div_factor_lat
del_lat=del_lat*(99/100.)
# div_factor_lat=div_factor_lat/1.001
i=[0,0]
if (n.shape(j)[0] == 0):
del_lon=del_lon_old*div_factor_lon
del_lon=del_lon*(99/100.)
# div_factor_lon=div_factor_lon/1.001
j=[0,0]
# print loop_count
if (n.shape(i)[0] == 1) & (n.shape(j)[0] == 1):
loop=0.
print 'finding the closest grid point to coordinate (',user_lat,',' ,user_lon,')'
print i,j
# print del_lat_old
# print del_lon_old
return i[0],j[0]
#return point_i,point_j
def interp_to_height(self,height_levels, height_on_model_levels,input_variable):
"""interpolate your data from model levels to height above ground
Inputs:
-------
height_levels (in meters, 1-D vector)
height_on_model_levels (in meters, basically geopotental height / 9.81) i.e. get_var('Z')
input_variable (which ever variable you wish to interpolate)
Returns:
-------
Your variable interpolated to constant height above ground
Notes:
------
Assuming the following dimensions
4 dimensions = (time, bottom_top,sound_north, west_east)
"""
if (len(n.shape(input_variable)) == 4):
ti_dim=n.shape(input_variable)[0]
hi_dim=n.shape(input_variable)[1]
sn_dim=n.shape(input_variable)[2]
we_dim=n.shape(input_variable)[3]
output_variable=n.zeros((ti_dim,len(height_levels),sn_dim,we_dim),dtype=n.float32)
for the_time in range(ti_dim):
for i in range(sn_dim):
for j in range(we_dim):
output_variable[the_time,:,i,j] = s.interp(height_levels[:],height_on_model_levels[the_time,:,i,j],input_variable[the_time,:,i,j])
if (len(n.shape(input_variable)) == 1):
hi_dim=n.shape(input_variable)[0]
output_variable=n.zeros((len(height_levels)),dtype=n.float32)
output_variable[:] = s.interp(height_levels[:],height_on_model_levels[:],input_variable[:])
return output_variable
def calculate_dbz_lin(self):
"""Calculate simulated radar reflectivity based on Lin et al microphysics
Inputs:
-------
None: will get the variables it needs itself
Returns:
-------
reflectivity fields
Notes:
------
The actual convesion routine is based on a fortran routine stolen from grads
If this does not work you may need to recomiple the libary object for your
system. Use the program f2py
example: f2py -c -m dbzcalc_lin_py dbzcalc_lin_py.f
Further note: you need to check in the dbzcalc_lin_py.f that the intercept variables
are correct for your version of the lin code. I.e. Check the actual microphysics
routine in wrf.
"""
try:
import dbzcalc_lin_py
except:
print 'cannot import dbzcalc_lin_py, please run f2py on dbzcalc_lin_py.f'
print 'reflectivity functions for Lin scheme will not be available untill you do this'
try:
qvp=self.variable_dict['QVAPOR']
except:
qvp=self.get_var('QVAPOR')
try:
qra=self.variable_dict['QRAIN']
except:
qra= self.get_var('QRAIN')
try:
qsn=self.variable_dict['QSNOW']
except:
qsn=self.get_var('QSNOW')
try:
qgr=self.variable_dict['QRGAUP']
except:
qgr=self.get_var('QGRAUP')
try:
tk=self.variable_dict['TEMP']
except:
tk=self.get_var('TEMP')
try:
prs=self.variable_dict['PRES']
except:
prs=self.get_var('PRES')
in0r=0
in0s=0
in0g=0
iliqskin=0
if (len(n.shape(qvp)) == 4):
ntimes=n.shape(qvp)[0]
mkzh=n.shape(qvp)[1]
mjx=n.shape(qvp)[2] #NORTH-SOUTH
miy=n.shape(qvp)[3] #WEST-EAST
#need to reorient z x y to x y z
qvp_r=n.zeros((miy,mjx,mkzh),dtype=n.float32)
qra_r=n.zeros((miy,mjx,mkzh),dtype=n.float32)
qsn_r=n.zeros((miy,mjx,mkzh),dtype=n.float32)
qgr_r=n.zeros((miy,mjx,mkzh),dtype=n.float32)
tk_r =n.zeros((miy,mjx,mkzh),dtype=n.float32)
prs_r=n.zeros((miy,mjx,mkzh),dtype=n.float32)
qvp_r=n.zeros((miy,mjx,mkzh),dtype=n.float32)
dbz=n.zeros((ntimes,miy,mjx,mkzh),dtype=n.float32)
for ti in range(ntimes):
for k in range(mkzh):
qvp_r[:,:,k]=n.transpose(qvp[ti,k,:,:])
qra_r[:,:,k]=n.transpose(qra[ti,k,:,:])
qsn_r[:,:,k]=n.transpose(qsn[ti,k,:,:])
qgr_r[:,:,k]=n.transpose(qgr[ti,k,:,:])
tk_r[:,:,k]= n.transpose(tk[ti,k,:,:])
prs_r[:,:,k]=n.transpose(prs[ti,k,:,:])
#qvp_r[:,:,k]=n.transpose(qvp[ti,k,:,:])
dbz[ti,:,:,:]=dbzcalc_lin_py.dbzcalc(qvp_r[:,:,:],qra_r[:,:,:],qsn_r[:,:,:],qgr_r[:,:,:],tk_r[:,:,:],prs_r[:,:,:],dbz[ti,:,:,:],in0r,in0s,in0g,iliqskin,miy=miy,mjx=mjx,mkzh=mkzh)
#transpose back
dbz_lin=n.zeros((ntimes,mkzh,mjx,miy),dtype=n.float32)
for ti in range(ntimes):
for k in range(mkzh):
dbz_lin[ti,k,:,:]=n.transpose(dbz[ti,:,:,k])
self.variable_dict.update({'dbz_lin':dbz_lin})
return dbz_lin
def calculate_dbz_thompson(self):
"""Calculate simulated radar reflectivity based on Thompson et al microphysics
Inputs:
-------
None: will get the variables it needs itself
Returns:
-------
reflectivity fields
Notes:
------
simon needs to write something here
"""
try:
import dbzcalc_thompson_py_ext
except:
print 'cannot import dbzcalc_thompson_py_ext please run f2py on fortran file'
print 'reflectivity functions for Thompson scheme will not be available untill you do this'
try:
qvp=self.variable_dict['QVAPOR']
except:
qvp=self.get_var('QVAPOR')
try:
qra=self.variable_dict['QRAIN']
except:
qra= self.get_var('QRAIN')
try:
qsn=self.variable_dict['QSNOW']
except:
qsn=self.get_var('QSNOW')
try:
qgr=self.variable_dict['QRGAUP']
except:
qgr=self.get_var('QGRAUP')
try:
tk=self.variable_dict['TEMP']
except:
tk=self.get_var('TEMP')
try:
prs=self.variable_dict['PRES']
except:
prs=self.get_var('PRES')
def compute_rho_dry(rho,tmk, pressure):
rgas=287.04
rho = pressure*100.0/(rgas*tmk)
return rho
def compute_rho(rho,tmk, pressure, qvp,nx,ny,nz):
rgas=287.04
rho = pressure*100.0/(rgas*(tmk*(0.622+qvp)/(0.622*(1.+qvp))))
return rho
in0r=0
in0s=0
in0g=0
iliqskin=0
if (len(n.shape(qvp)) == 4):
ntimes=n.shape(qvp)[0]
mkzh=n.shape(qvp)[1]
mjx=n.shape(qvp)[2] #NORTH-SOUTH
miy=n.shape(qvp)[3] #WEST-EAST
#need to reorient z x y to x y z
qvp_r=n.zeros((miy,mjx,mkzh),dtype=n.float32)
qnr_r=n.zeros((miy,mjx,mkzh),dtype=n.float32)
qra_r=n.zeros((miy,mjx,mkzh),dtype=n.float32)
qsn_r=n.zeros((miy,mjx,mkzh),dtype=n.float32)
qgr_r=n.zeros((miy,mjx,mkzh),dtype=n.float32)
tk_r =n.zeros((miy,mjx,mkzh),dtype=n.float32)
prs_r=n.zeros((miy,mjx,mkzh),dtype=n.float32)
rho_r=n.zeros((miy,mjx,mkzh),dtype=n.float32)
dbz=n.zeros((ntimes,miy,mjx,mkzh),dtype=n.float32)
rho=n.zeros((ntimes,miy,mjx,mkzh),dtype=n.float32)
rho=compute_rho(rho,tk,prs,qvp,miy,mjx,mkzh)
#rho=compute_rho_dry(rho,tk,prs)
for ti in range(ntimes):
for k in range(mkzh):
rho_r[:,:,k]=n.transpose(rho[ti,k,:,:])
qra_r[:,:,k]=n.transpose(qra[ti,k,:,:])
qsn_r[:,:,k]=n.transpose(qsn[ti,k,:,:])
qgr_r[:,:,k]=n.transpose(qgr[ti,k,:,:])
tk_r[:,:,k]= n.transpose(tk[ti,k,:,:])
prs_r[:,:,k]=n.transpose(prs[ti,k,:,:])
#qvp_r[:,:,k]=n.transpose(qvp[ti,k,:,:])
print miy,mjx,mkzh
print n.shape(qra_r)
print n.shape(qnr_r)
print n.shape(qsn_r)
print n.shape(qgr_r)
print n.shape(tk_r)
print n.shape(rho_r)
print n.shape(dbz[ti,:,:,:])
# dbz[ti,:,:,:]=dbzcalc_lin_py .dbzcalc(qvp_r[:,:,:],qra_r[:,:,:],qsn_r[:,:,:],qgr_r[:,:,:],tk_r[:,:,:],prs_r[:,:,:],dbz[ti,:,:,:],in0r,in0s,in0g,iliqskin,miy=miy,mjx=mjx,mkzh=mkzh)
#dbz[ti,:,:,:]=dbzcalc_thompson_py_ext.dbzcalc2(qra_r[:,:,:],qnr_r[:,:,:],qsn_r[:,:,:],qgr_r[:,:,:],tk_r[:,:,:],rho_r[:,:,:],dbz[ti,:,:,:],miy=miy,mjx=mjx,mkzh=mkzh) #dbz will be top-down
poo=dbzcalc_thompson_py_ext.dbzcalc2(qra_r[:,:,:],qnr_r[:,:,:],qsn_r[:,:,:],qgr_r[:,:,:],tk_r[:,:,:],rho_r[:,:,:],dbz[ti,:,:,:],miy=miy,mjx=mjx,mkzh=mkzh) #dbz will be top-down
print n.shape(poo)
#transpose back
dbz_test=poo[6]
dbz_thomp=n.zeros((ntimes,mkzh,mjx,miy),dtype=n.float32)
for ti in range(ntimes):
for k in range(mkzh):
dbz_thomp[ti,k,:,:]=n.transpose(dbz_test[:,:,k])
self.variable_dict.update({'dbz_thomp':dbz_thomp})
return dbz_thomp
def calculate_dbz_ferrier(self):
"""Calculate simulated radar reflectivity based on Ferrier microphysics
Inputs:
-------
None: will get the variables it needs itself
Returns:
-------
reflectivity fields
Notes:
------
The actual convesion routine is based on a fortran routine stolen from the CALMICT.f90 routine (Brad Ferrier)
If this does not work you may need to recomiple the libary object for your system.
Use the program f2py,
example: f2py -c -m dbzcalc_ferrier_py dbzcalc_ferrier_py.f90
"""
try:
import dbzcalc_ferrier_py
except:
print 'cannot import dbzcalc_ferrier_py, please run f2py on dbzcalc_ferrier_py.f'
print 'reflectivity functions for ferrier scheme will not be available untill you do this'
try:
P1D=self.variable_dict['PRES']*100 # Pressure (PA)
except:
P1D=self.get_var('PRES')*100
try:
T1D=self.variable_dict['TEMP'] # Temperature (K)
except:
T1D=self.get_var('TEMP')
try:
Q1D=self.variable_dict['SPH'] # Specific Humidity (kg/kg)
except:
Q1D=self.get_var('SPH')
try:
C1D=self.variable_dict['CWM'] # Total Condensate (CWM, kg/kg)
except:
C1D=self.get_var('CWM')
try:
QW1=self.variable['QCLOUD'] # QCLOUD
except:
QW1=self.get_var('QCLOUD')
try:
QR1=self.variable['QRAIN'] # QRAIN
except:
QR1=self.get_var('QRAIN')
try:
QI1=self.variable['QSNOW'] # QSNOW
except:
QI1=self.get_var('QSNOW')
if (self.wrf_core == 'ARW'):
try:
FI1D=self.variable_dict['F_ICE_PHY'] # F_ice (fraction of condensate in form of ice)
except:
FI1D=self.get_var('F_ICE_PHY')
try:
FR1D=self.variable_dict['F_RAIN_PHY'] # F_rain (fraction of liquid water in form of rain
except:
FR1D=self.get_var('F_RAIN_PHY')
try:
FS1D=self.variable_dict['F_RIMEF_PHY'] # F_RimeF ("Rime Factor", ratio of total ice growth to deposition growth)
except:
FS1D=self.get_var('F_RIMEF_PHY')
elif (self.wrf_core == 'NMM'):
try:
FI1D=self.variable_dict['F_ICE'] # F_ice (fraction of condensate in form of ice)
except:
FI1D=self.get_var('F_ICE')
try:
FR1D=self.variable_dict['F_RAIN'] # F_rain (fraction of liquid water in form of rain
except:
FR1D=self.get_var('F_RAIN')
try:
FS1D=self.variable_dict['F_RIMEF'] # F_RimeF ("Rime Factor", ratio of total ice growth to deposition growth)
except:
FS1D=self.get_var('F_RIMEF')
else:
print 'microhpysics variables not found, check for F_ICE, FRAIN,F_RIMEF'
return None
# Read in MASSR and MASSI arrays from text files
# The text files are from ETAMPNEW_DATA
# These are used in the MICROINIT.f subroutine of CALMICT.f
fid_massr=open(PYWRFPATH+'/library/eta_tables_massr.txt','r')
fid_massi=open(PYWRFPATH+'/library/eta_tables_massi.txt','r')
MASSR=n.array(fid_massr.readline().split(','),dtype=n.float32)
MASSI=n.array(fid_massi.readline().split(','),dtype=n.float32)
# Set up grid (vertical levels = mkzh, NSdim = y = miy, WEdim = x = mjx, )
if (len(n.shape(FS1D)) == 4):
ntimes=n.shape(FS1D)[0]
mkzh=n.shape(FS1D)[1]
mjx=n.shape(FS1D)[2] # NS-DIMENSION
miy=n.shape(FS1D)[3] # WE-DIMENSION
QS1 =n.zeros((mjx,miy),dtype=n.float32) # "Snow" (precipitation ice) mixing ratio (kg/kg)
Tdbz =n.zeros((ntimes,mkzh,mjx,miy),dtype=n.float32) # output array (currently DBZ1)
Rdbz =n.zeros((ntimes,mkzh,mjx,miy),dtype=n.float32) # output array (currently DBZR)
Idbz =n.zeros((ntimes,mkzh,mjx,miy),dtype=n.float32) # output array (currently DBZI)
DBZ1 =n.zeros((mjx,miy),dtype=n.float32) # Equivalent radar reflectivity factor in dBZ; ie., 10*Log10(Z)
DBZR1 =n.zeros((mjx,miy),dtype=n.float32) # Equivalent radar reflectivity factor from rain in dBZ
DBZI1 =n.zeros((mjx,miy),dtype=n.float32) # Equivalent radar reflectivity factor from ice (all forms) in dBZ
DBZC1 =n.zeros((mjx,miy),dtype=n.float32) # Equivalent radar reflectivity factor from parameterized convection in dBZ
NLICE1 =n.zeros((mjx,miy),dtype=n.float32) # Time-averaged number concentration of large ice
CUREFL =n.zeros((mjx,miy),dtype=n.float32) # Radar reflectivity contribution from convection (mm**6/m**3)
im = mjx
jm = miy
for ti in range(ntimes):
for k in range(mkzh):
#Tdbz[ti,k,:,:], Rdbz[ti,k,:,:], Idbz[ti,k,:,:] = dbzcalc_ferrier_py.calmict(P1D[ti,k,:,:],T1D[ti,k,:,:],Q1D[ti,k,:,:],C1D[ti,k,:,:],FI1D[ti,k,:,:],FR1D[ti,k,:,:],FS1D[ti,k,:,:],CUREFL,QW1[ti,k,:,:],QI1[ti,k,:,:],QR1[ti,k,:,:],QS1,DBZ1,DBZR1,DBZI1,DBZC1,NLICE1,miy,mjx,MASSR,MASSI)
Tdbz[ti,k,:,:] = dbzcalc_ferrier_py.calmict(P1D[ti,k,:,:],T1D[ti,k,:,:],Q1D[ti,k,:,:],C1D[ti,k,:,:],FI1D[ti,k,:,:],FR1D[ti,k,:,:],FS1D[ti,k,:,:],CUREFL,QW1[ti,k,:,:],QI1[ti,k,:,:],QR1[ti,k,:,:],QS1,DBZ1,DBZR1,DBZI1,DBZC1,NLICE1,miy,mjx,MASSR,MASSI,im,jm)
self.variable_dict.update({'dbz_ferrier':Tdbz})
return Tdbz #, Rdbz, Idbz
def compute_height(self):
"""Calculate geopotential height (3d) in meters from surace geopotient
this is based on the hypsometer equation which is
Z_2 = Z_1 + (R_T_v/g)*[log(p_1) - log(p_2)]
and only technicaly valid for hydrostatic balance
use this only for the NMM core case they do not give you geopotential height.
Inputs:
-------
None: will get the variables it needs itself
Returns:
-------
geopotential height in meters (I think)
Notes:
------
Only technicaly valid for hydrostatic balance, I may add further.
Simon change this when you add non-hydro support.
(even if non-hydro just use it for now cause it will be close enough)
"""
try:
#print 'getting the unstaggered version of PINT'
prs=self.niofile.variables['PINT'].get_value()
except:
print 'cannt fint your variable PINT'
try:
ter=self.variable['FIS']/9.81 # Terrain height = surface geopotential height/9.81
except:
ter=self.get_var('FIS')/9.81
try:
vtmk=self.compute_vtmk()
except:
print 'could not calculate virtual temperature'
return None
#using the hypsometer equation which is
# Z_2 - Z_1 = (R*T_v/g)*log(p_1/p_2)
# Z_2 = Z_1 + (R_T_v/g)*[log(p_1) - log(p_2)]
#fix up geopotential height at broken points
ter=n.where(ter < 0,0,ter)
# Set up grid (vertical levels = mkzh, NSdim = y = miy, WEdim = x = mjx, )
if (len(n.shape(prs)) == 4):
ntimes=n.shape(prs)[0]
mkzh=n.shape(prs)[1]-1
mjx=n.shape(prs)[2] # NS-DIMENSION
miy=n.shape(prs)[3] # WE-DIMENSION
log_p=n.zeros((ntimes,mkzh+1,mjx,miy), dtype="float")
base_level=n.zeros((ntimes,mjx,miy), dtype="float")
ght=n.zeros((ntimes,mkzh+1,mjx,miy), dtype="float")
for ti in range(ntimes):
for k in range(mkzh+1):
log_p[ti,k,:,:]=n.log(prs[ti,k,:,:])
rgas=287.04
grav=9.81
for ti in range(ntimes):
ght[ti,0,:,:] = ter[ti,:,:]
for k in range(1, mkzh+1):
tv_average=(vtmk[ti,k-1,:,:]) # not doing average for some reason
ght[ti,k,:,:] = ght[ti,k-1,:,:] + ((rgas*tv_average)/grav)*(log_p[ti,k-1,:,:] - log_p[ti,k,:,:])
#now we have ght on staggared levels, we must destagger
ght_destag=n.zeros((ntimes,mkzh,mjx,miy), dtype="float")
for ti in range(ntimes):
for k in range(mkzh):
ght_destag[ti,k,:,:] = 0.5*( ght[ti,k,:,:] + ght[ti,k+1,:,:] )
self.variable_dict.update({'GHT':ght_destag})
return ght_destag
def compute_extrema(self,mat,mode='wrap',window=10):
from scipy.ndimage.filters import maximum_filter, minimum_filter
"""find the indicies of local extrema (min and max
in the local array. """
mn=minimum_filter(mat,size=window,mode=mode)
mx=maximum_filter(mat,size=window,mode=mode)
return n.nonzero(mat == mn), n.nonzero(mat==mx)
def write_netcdf_file(self,input_variable,var_name,directory='.',filename='new_output', var_dim=('T','BT','SN','WE'), var_type='f'):
"""This is a function to write out a selected field to a netcdf file
Inputs:
-------
input_data (this is an N-dimensional array you want to write)
var_name (the name you want to call your variable)
Optional Inputs:
----------------
directory (the directory where your file will be produced, default is '.'
filename (the name of the netcdf file you want to write, defile is new_output.nc')