用降水、比湿和温度计算相对湿度(nc版、python)
有时收集到的气象数据为比湿,但模型中需要的输入为相对湿度,我们可以利用降水、比湿和温度进行换算。
转换公式:https://earthscience.stackexchange.com/questions/2360/how-do-i-convert-specific-humidity-to-relative-humidity
比湿转换为相对湿度
def shum_switch_rhum(temp,shum,pres):
'''
利用比湿(specific humidity)计算相对湿度
:param temp: 气温,K
:param shum: 比湿
:param pres: 气压,Pa
:return: rhum,%
'''
rhum = 0.236 * pres * shum * np.exp((17.67 * (temp - 273.16))/(temp - 29.65)) ** (-1)
print(rhum)
return rhum
如果你的数据是nc的,那么你可以尝试用下面的函数进行批量计算
import xarray as xr
import os
import datetime
import numpy as np
import pandas as pd
def Search_File(dirname,suffix):
'''
This function can search all files with the specified suffix in this dir.
:param dirname: string, the path need to be searched
:param suffix: string, the specified suffix need to be seached
:return:
filter_list: list, the path list need to be searched.
'''
filter = [suffix] # 设置过滤后的文件类型 当然可以设置多个类型
filter_list = []
for maindir, subdir, file_name_list in os.walk(dirname):
#print(maindir) #当前主目录
for filename in file_name_list:
apath = os.path.join(maindir, filename)#合并成一个完整路径
portion = os.path.splitext(apath)
ext = portion[1] # 获取文件后缀 [0]获取的是除了文件名以外的内容
if ext in filter:
newname = portion[0] + suffix
filter_list.append((newname,portion[0].split("\\")[-1]))
# print(filter_list)
return filter_list
def batch_shum_to_rhum(pres_path,shum_path,temp_path,output_path,start_year,end_year):
'''
可以利用降水、比湿和温度计算相对湿度,注意数据单位
:param pres_path:
:param shum_path:
:param temp_path:
:param output_path:
:return:
'''
# 批量比湿和相对湿度换算
# 导入数据,压力、比湿以及温度,注意单位
pres_path_list = Search_File(pres_path,".nc")
pres_list = [read_nc_data(path[0]) for path in pres_path_list]
pres = xr.combine_nested(pres_list,concat_dim="time")
temp_path_list = Search_File(temp_path,".nc")
temp_list = [read_nc_data(path[0]) for path in temp_path_list]
temp = xr.combine_nested(temp_list,concat_dim="time")
shum_path_list = Search_File(shum_path, ".nc")
shum_list = [read_nc_data(path[0]) for path in shum_path_list]
shum = xr.combine_nested(shum_list, concat_dim="time")
acc = xr.merge([shum,temp,pres])
rhum_data = shum_switch_rhum(acc["temp"].values,acc["shum"].values,acc["pres"].values)
rhum = xr.Dataset({"rhum": (["time", "lat", "lon"], rhum_data)}, coords=acc.coords,
attrs={"long_name": "relative humidity", "units": "%"})
years = list(range(start_year, end_year + 1))
for year in years:
# 输入年月数据比较方便!!!
out = rhum.sel(time=rhum["time.year"] == year)
out.to_netcdf("{}/rhum_{}.nc".format(output_path,year))
print(out)