I am using jupyter notebook. The following code uses some functions defined in the metpy package (dewpoint_from_relative_humidity) to define a new function "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()
But when this defined function is used further in the loop it gives the following error:
NameError: name 'dewpoint_from_relative_humidity' is not defined
Why is the error coming if the function has already been defined previously in 'calc', is there any problem with the pool or the way a native function is defined inside a new function?