我正在使用 jupyter notebook。以下代码使用 metpy 包中定义的一些函数 (dewpoint_from_relative_humidity) 来定义一个新函数“calc”。
import numpy as np
import xarray as xr
from time import time
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d
from metpy.units import units
from metpy.calc import cape_cin, dewpoint_from_relative_humidity, parcel_profile, most_unstable_cape_cin, mixed_layer_cape_cin
from metpy.calc import dewpoint_from_relative_humidity
from multiprocessing import Pool
from pytictoc import TicToc # conda install pytictoc -c ecf
data1 = xr.open_dataset(r'new.nc')
data = data1.sel(latitude = slice (50,45), longitude = slice(-110,-108))
data.r.values = data.r.values/100
data.t.values = data.t.values-273
data.t.attrs['units'] = 'degree_Celsius'
data.r.attrs['units'] = 'dimensionless'
data.level.attrs['units'] = 'hectopascal'
## reversing pressure levels descending
data = data.isel(level=slice(None, None, -1))
p = data.level
#Defining the calc function using the metpy functions: dewpointy_f_R_H and Most_unstabe_cape_cin
def calc(idata):
p1 = idata[0]
t1 = idata[1]
rh1 = idata[2]
td1 = dewpoint_from_relative_humidity(t1,rh1)
cape = most_unstable_cape_cin(p1, t1, td1)
#print(cape)
return cape
SP_emp = data.drop_vars(['t'])
SP_emp['cape'] = SP_emp['r']*0
SP_emp = SP_emp.drop_vars(['r'])
#Dropping 'level' dimension
SP_emp = SP_emp.mean(['level'])
from multiprocess import Pool
from pytictoc import TicToc
if __name__ == '__main__':
pool = Pool(processes = 8)
#num_processors = 4
mucape_res = np.zeros((data.t.time.size, data.t.latitude.size * data.t.longitude.size)) # time * lat * lon
print(mucape_res.shape)
for lat in data.latitude.values:
for lon in data.longitude.values:
for tim in data.time.values:
t = TicToc()
t.tic()
Temp = data.t.sel(time =tim, latitude=lat, longitude = lon)
#print(Temp)
RH = data.r.sel(time =tim, latitude=lat, longitude = lon)
#print(RH)
#print(TD)
sets = p,Temp,RH
out = pool.map(calc,sets)
#out = calc(set)
cape_mag = out.magnitude
SP_emp.cape.loc[dict(time = tim,longitude = lon, latitude = lat)] = cape_mag
t.toc()
#pool.close()
但是当在循环中进一步使用这个定义的函数时,会出现以下错误:
NameError: name 'dewpoint_from_relative_humidity' is not defined
如果之前已经在'calc'中定义了函数,为什么会出现错误,池或在新函数中定义本机函数的方式是否有问题?