import numpy as np
from scipy import interpolate
import pygrib
def rh2q_ppmv(RH,P,T):
'''Conversion reletive humidity to lnq in ppmv
RH-%, P-hPa, T-K'''
t = T-273.15
if T <=233.15:
e_s=6.1078*np.exp(21.8746*(t)/(T-7.66))
elif T>=258.15:
e_s=6.1078*np.exp(17.269*(t)/(T-35.86))
else:
e_s_water=e_s=6.1078*np.exp(17.269*(t)/(T-35.86))
e_s_ice=6.1078*np.exp(21.8746*(t)/(T-7.66))
e_s=0.002*((80+2*t)*e_s_water-(30+2*t)*e_s_ice)
e = RH/100*e_s # hPa
q_ppmv = 1000000*e/P
return q_ppmv
# 指定fnl资料路径
grbs = pygrib.open('/home/xxxxx/Documents/fnl/fnl_20180110_00_00.grib2')
grbs.seek(0)
#for key in grbs:
#print(key)
Temperatures = grbs.select(name='Temperature')[:] # 读取31层温度
RHs = grbs.select(name='Relative humidity')[:] # 读取31层相对湿度
lats, lons = Temperatures[0].latlons() # 读取经纬度
lats, lons = lats[:,0], lons[0,:] # 压缩经纬度到一维
# fnl资料里31层气压值
fnl_P_levels_hpa = [1.0, 2.0, 3.0, 5.0, 7.0, 10.0, 20.0, 30.0, 50.0, 70.0, 100.0, 150.0, 200.0, 250.0, 300.0, 350.0, 400.0, 450.0, 500.0, 550.0, 600.0, 650.0, 700.0, 750.0, 800.0, 850.0, 900.0, 925.0, 950.0, 975.0, 1000.0]
fnl_lnP_levels_hpa = np.log(fnl_P_levels_hpa) # 取对数
fnl_Vertical_T = []
fnl_Vertical_RH = []
fnl_Vertical_q_ppmv = []
for key in range(31):
fx = interpolate.interp2d(lons, lats, Temperatures[key].values, kind='linear')
T = fx(120.5,25.5)# 将fnl31层温度插值到120.5经度,北纬25.5度
fx = interpolate.interp2d(lons, lats, RHs[key].values, kind='linear')
RH = fx(120.5,25.5)# 将fnl31层相对湿度插值到120.5经度,北纬25.5度
q_ppmv_cal = rh2q_ppmv(RH,fnl_P_levels_hpa[key],T)
fnl_Vertical_T.append(float(T))
fnl_Vertical_RH.append(float(RH))
fnl_Vertical_q_ppmv.append(float(q_ppmv_cal))
#print(fnl_Vertical_q_ppmv)
rttov93_P_levels = [0.1, 0.29, 0.69, 1.42, 2.611, 4.407, 6.95, 10.37, 14.81, 20.4, 27.26, 35.51, 45.29, 56.73, 69.97, 85.18, 102.05, 122.04, 143.84, 167.95, 194.36, 222.94, 253.71, 286.6, 321.5, 358.28, 396.81, 436.95, 478.54, 521.46, 565.54, 610.6, 656.43, 702.73, 749.12, 795.09, 839.95, 882.8, 922.46, 957.44, 985.88, 1005.43, 1013.25]
rttov93_lnP_levels = np.log(rttov93_P_levels) # 取对数
fx = interpolate.interp1d(fnl_lnP_levels_hpa, fnl_Vertical_T, kind='linear', fill_value='extrapolate' )
rttov93_Vertical_T = fx(rttov93_lnP_levels) # 温度插值
fx = interpolate.interp1d(fnl_lnP_levels_hpa, fnl_Vertical_q_ppmv, kind='linear', fill_value='extrapolate' )
rttov93_Vertical_q_ppmv = fx(rttov93_lnP_levels) # q_ppmv插值
rttov93_Vertical_lnq_output = np.log(rttov93_Vertical_q_ppmv/1000) # 转化成rttov93的存储格式
# 插值结果
print(rttov93_Vertical_T)
print(rttov93_Vertical_lnq_output)