def test(self): from netCDF4 import Dataset as NetCDF timeidx = 0 in_wrfnc = NetCDF(wrf_in) if (varname == "interplevel"): ref_ht_850 = _get_refvals(referent, "interplevel", repeat, multi) hts = getvar(in_wrfnc, "z", timeidx=timeidx) p = getvar(in_wrfnc, "pressure", timeidx=timeidx) hts_850 = interplevel(hts, p, 850) nt.assert_allclose(to_np(hts_850), ref_ht_850) elif (varname == "vertcross"): ref_ht_cross = _get_refvals(referent, "vertcross", repeat, multi) hts = getvar(in_wrfnc, "z", timeidx=timeidx) p = getvar(in_wrfnc, "pressure", timeidx=timeidx) pivot_point = CoordPair(hts.shape[-1] // 2, hts.shape[-2] // 2) ht_cross = vertcross(hts, p, pivot_point=pivot_point, angle=90.) nt.assert_allclose(to_np(ht_cross), ref_ht_cross, rtol=.01) elif (varname == "interpline"): ref_t2_line = _get_refvals(referent, "interpline", repeat, multi) t2 = getvar(in_wrfnc, "T2", timeidx=timeidx) pivot_point = CoordPair(t2.shape[-1] // 2, t2.shape[-2] // 2) t2_line1 = interpline(t2, pivot_point=pivot_point, angle=90.0) nt.assert_allclose(to_np(t2_line1), ref_t2_line) elif (varname == "vinterp"): # Tk to theta fld_tk_theta = _get_refvals(referent, "vinterp", repeat, multi) fld_tk_theta = np.squeeze(fld_tk_theta) tk = getvar(in_wrfnc, "temp", timeidx=timeidx, units="k") interp_levels = [200, 300, 500, 1000] field = vinterp(in_wrfnc, field=tk, vert_coord="theta", interp_levels=interp_levels, extrapolate=True, field_type="tk", timeidx=timeidx, log_p=True) tol = 5 / 100. atol = 0.0001 field = np.squeeze(field) nt.assert_allclose(to_np(field), fld_tk_theta, tol, atol)
def get_info(self, wrf_path, fname, vnames): # self.wrf = xr.open_dataset(wrf_path+fname)._file_obj.ds self.ds = Dataset(wrf_path+fname) self.xrds = xr.open_dataset(wrf_path+fname) # check vname and read all of them self.dv = {} if isinstance(vnames, str): self.dv.update({vnames: getvar(self.ds, vnames, timeidx=ALL_TIMES)}) if vnames != 'Times' and 'lon' not in self.dv: self.dv.update({'lat': latlon_coords(self.dv[vnames])[0]}) self.dv.update({'lon': latlon_coords(self.dv[vnames])[1]}) elif isinstance(vnames, list): for index, v in enumerate(vnames): self.dv.update({v: getvar(self.ds, v, timeidx=ALL_TIMES)}) if v != 'Times' and 'lon' not in self.dv: self.dv.update({'lat': latlon_coords(self.dv[v])[0]}) self.dv.update({'lon': latlon_coords(self.dv[v])[1]}) # get proj attrs = self.xrds.attrs i = attrs['WEST-EAST_GRID_DIMENSION'] j = attrs['SOUTH-NORTH_GRID_DIMENSION'] # calculate attrs for area definition shape = (j, i) radius = (i*attrs['DX']/2, j*attrs['DY']/2) # create area as same as WRF area_id = 'wrf_circle' proj_dict = {'proj': wrf_projs[attrs['MAP_PROJ']], 'lat_0': attrs['MOAD_CEN_LAT'], 'lon_0': attrs['STAND_LON'], 'lat_1': attrs['TRUELAT1'], 'lat_2': attrs['TRUELAT2'], 'a': 6370000, 'b': 6370000} center = (0, 0) self.area_def = AreaDefinition.from_circle(area_id, proj_dict, center, radius, shape=shape)
def load_wrfdata2(data_dir, domain): wrf_files = [f for f in os.listdir(data_dir) if f[11] == f'{domain}'] wrflist = [ Dataset(os.path.join(data_dir, wrf_file)) for wrf_file in wrf_files ] # tsk = w.getvar(wrflist, 'T2', timeidx=w.ALL_TIMES, method='cat') lats, lons = w.latlon_coords(tsk) time = tsk.Time.to_index() return tsk, lats, lons, time
def get_height_for_y(model_datetime, y_here): file = get_wrf_file(model_datetime) # base_geopot = file.variables['PHB'].data[:] # pert_geopot = file.variables['PH'].data[:] # height = (base_geopot + pert_geopot) / 9.8ng around detector sire at1 height = getvar(file, 'z', meta=False) temp_height = height[:, y_here, x_lon] # "ground_height" is the minimal considered value of the altitude: it defines "zero-value" of "z" (in metres)the_time_moment_index ground_height = height[0, y_lat, x_lon] for current_index in range(0, len(temp_height)): temp_height[current_index] += -ground_height + 2 return temp_height
def get_wspd_wdir(netcdf_data, key): """ Formats the wind speed and wind direction so it can be merged into an xarray Dataset with all the other variables extracted using getvar :param netcdf_data: :param key: :return: """ var = wrf.getvar(netcdf_data, key, wrf.ALL_TIMES) var = xr.DataArray.reset_coords(var, ['wspd_wdir'], drop=True) var.name = key return var
def chooseData(nc1, nc2, nc3, var, time_index): ################################### ################################### ## Read in data from netCDF using WRF-Python ################################### ################################### import wrf import xarray as xr import numpy as np data1 = wrf.getvar(nc1, var, timeidx=time_index) data2 = wrf.getvar(nc2, var, timeidx=time_index) data3 = wrf.getvar(nc3, var, timeidx=time_index) data1 = TDtrans(data1, nc1, time_index) data2 = TDtrans(data2, nc2, time_index) data3 = TDtrans(data3, nc3, time_index) return data1, data2, data3
def load_wrfdata(data_dir, domain): wrf_files = [f for f in os.listdir(data_dir) if f[11] == f'{domain}'] wrflist = [ Dataset(os.path.join(data_dir, wrf_file)) for wrf_file in wrf_files ] # T_lake3d = w.getvar(wrflist, 'T_LAKE3D', timeidx=w.ALL_TIMES, method='cat') lats, lons = w.latlon_coords(T_lake3d) time = T_lake3d.Time.to_index() return T_lake3d, lats, lons, time
def test(self): #import time #very_start = time.time() #start = time.time() t1 = getvar(ncfiles, varname, 0) #end = time.time() #print ("t1: ", start-end) #start = time.time() t2 = getvar(ncfiles, varname, 0, meta=False) #end = time.time() #print ("t2: ", start-end) #start = time.time() t3 = getvar(ncfiles, varname, ALL_TIMES) #end = time.time() #print ("t3: ", start-end) #start = time.time() t4 = getvar(ncfiles, varname, ALL_TIMES, meta=False) #end = time.time() #print ("t4: ", start-end) #start = time.time() t5 = getvar(ncfiles, varname, ALL_TIMES, method="join") #end = time.time() #print ("t5: ", start-end) #start = time.time() t6 = getvar(ncfiles, varname, ALL_TIMES, method="join", meta=False)
def compute_CAPE2D(filename, inputinf=None): """ Function to calculate CAPE using methods described in: http://wrf-python.readthedocs.io/en/latest/user_api/generated/wrf.cape_2d.html This is NOT CF-compliant in any way. cape2d contains 4 variables distributed by levels: MCAPE [J kg-1], MCIN[J kg-1], LCL[m] and LFC[m] """ ncfile = nc.Dataset(filename, 'r') pres_hpa = wrf.getvar(ncfile, "pressure", wrf.ALL_TIMES) tkel = wrf.getvar(ncfile, "tk", wrf.ALL_TIMES) qv = wrf.getvar(ncfile, "QVAPOR", wrf.ALL_TIMES) z = wrf.getvar(ncfile, "geopotential", wrf.ALL_TIMES) / const.g psfc = wrf.getvar(ncfile, "PSFC", wrf.ALL_TIMES) / 100. #Converto to hPA terrain = wrf.getvar(ncfile, "ter", wrf.ALL_TIMES) ter_follow = True cape2d = wrf.cape_2d(pres_hpa, tkel, qv, z, terrain, psfc, ter_follow, missing=const.missingval, meta=False) atts = { "standard_name": "cape2d_variables", "long_name": "mcape mcin lcl lfc", "units": "SI", } return cape2d, atts
def extraerWrfoutSerie(wrf_file: str, variable: str, x: int, y: int): """ extrae de los arechivos wrfout listados en file_paths para la posicion (x, y) toda la serie de la variable seleccionada""" dfData = pd.DataFrame() t2 = wrf.getvar(wrf_file, variable, timeidx=wrf.ALL_TIMES) t2_loc = t2[:, y, x] dfT2loc = pd.DataFrame(t2_loc.to_pandas(), columns=[variable]) if variable == 'T2': dfT2loc['T2'] = dfT2loc['T2'] - 273.15 tsk = wrf.getvar(wrf_file, 'TSK', timeidx=wrf.ALL_TIMES) tsk_loc = tsk[:, y, x] dfTSKloc = pd.DataFrame(tsk_loc.to_pandas(), columns=[variable]) dfTSKloc['T2'] = dfTSKloc['T2'] - 273.15 dfData = pd.concat([dfData, dfT2loc[9:]]) return dfData
def get_isobaric_variables(data, var_list, plevs, outfile, dtype, compression, complevel): """Gets isobaric variables from a list""" # use wrf-python to get data for each of the variables var_def = get_variables() # get pressure array and attach units p = getvar(data, 'p', ALL_TIMES) p_np = np.array(p.data) * units(p.units) for i in range(len(var_list)): name = var_list[i] var_data = getvar(data, var_def[name][2], ALL_TIMES) iso_data = log_interp(plevs, p_np, var_data.data, axis=1) # write each of the variables to the output file pres_data = outfile.createVariable( var_list[i], dtype, ('time', 'pressure_levels', 'lat', 'lon'), zlib=compression, complevel=complevel) pres_data.units = var_data.units if var_list[i] == 'height': pres_data.decription = 'height [MSL] of isobaric surfaces' elif var_list[i] == 'uwnd': pres_data.description = 'u-wind component on isobaric surfaces' elif var_list[i] == 'vwnd': pres_data.description = 'v-wind component on isobaric surfaces' elif var_list[i] == 'wwnd': pres_data.description = 'w-wind component on isobaric surfaces' elif var_list[i] == 'temp': pres_data.description = 'temperature on isobaric surfaces' elif var_list[i] == 'dewpt': pres_data.description = 'dewpoint temperature on isobaric surfaces' elif var_list[i] == 'avor': pres_data.description = 'absolute vorticity on isobaric surfaces' else: pres_data.description = var_data.description pres_data[:] = iso_data
def compute_THETA(filename, inputinf=None): """ Function to calculate theta """ ncfile = nc.Dataset(filename, 'r') th = wrf.getvar(ncfile, "theta", wrf.ALL_TIMES) #in hPA atts = { "standard_name": "THETA", "long_name": "potential temperature", "units": "K" } return th, atts
def load_t(data_dir, domain, t_name='TSK'): # t_name: 'TSK' or 'T2' or 'T_LAKE3D' wrf_files = [f for f in os.listdir(data_dir) if f[11] == f'{domain}'] wrflist = [ Dataset(os.path.join(data_dir, wrf_file)) for wrf_file in wrf_files ] # t = w.getvar(wrflist, t_name, timeidx=w.ALL_TIMES, method='cat') lats, lons = w.latlon_coords(t) time = t.Time.to_index() return t, lats, lons, time
def verticalwindinterpolationenergy(file, hubheight): ''' Creates an estimated wind speed at the central height of the wind tower Parameters ----------------- arg1: file netcdf data file passsed for data acquistion arg2: hubheight integer designated the hub height for interpolation to ''' #zO was selected due to the coarse domain, selection of roughness lenght #was based upon the fact that for 40km domain most of the surface coverage #of ND is farm land. ''' Roughness length -0.055m - Agricultural area with some houses and 8 m high hedges at a distance of more than 1 km ''' zO = 0.055 #roughness length h1 = 10.0 #wind measured height h2 = hubheight #middle of blade center of wind hub u10 = getvar(file, 'U10') #10meter wind U (east-west) v10 = getvar(file, 'V10') #10meter wind V (north-south) wind10 = np.sqrt(u10**2 + v10**2) #Wind Speed, no dir v2 = wind10 * (np.log(h2 / zO) / np.log(h1 / zO) ) #interpolated windspeed to height (hubheight) wind = v2.to_pandas() windmatrix = wind.as_matrix() for i in range(0, len(windmatrix)): for k in range(0, len(windmatrix[0])): if windmatrix[i, k] < 3.0: windmatrix[i, k] = 0.0 elif windmatrix[i, k] > 22.0: windmatrix[i, k] = 0.0 return windmatrix
def load_wrf_var_from_wrf_file_and_save(file, varname="rh2", savepath=None): """load one wrfvar from wrf file and save it to savepath""" from netCDF4 import Dataset import wrf nc = Dataset(file) from aux_gps import save_ncfile name = file.as_posix().split('/')[-1].split('.')[0] filename = '{}_{}.nc'.format(name, varname) wrfvar = wrf.getvar(wrfin=nc, varname=varname, timeidx=wrf.ALL_TIMES) if savepath is not None: if wrfvar.attrs['projection'] is not None: wrfvar.attrs['projection'] = wrfvar.attrs['projection'].proj4() save_ncfile(wrfvar, savepath, filename) return wrfvar
def compute_THETAE(filename, inputinf=None): """ Function to calculate equivalent potential temperature """ ncfile = nc.Dataset(filename, 'r') theta_e = wrf.getvar(ncfile, "theta_e", wrf.ALL_TIMES) atts = { "standard_name": "theta_e", "long_name": "equivalent potential temperature", "units": "K" } return theta_e, atts
def getWrfData(wrfPath, dx, dy, dz, levs, debug=True): # Open the file perDat = Dataset(wrfPath) refDat = Dataset("/home/iarsenea/trajs/wrfoutREFd01") #print(data.variables) # Pull in the values from the base state that we will add to the perturbations ref_h = getvar(refDat, "height", units="m", timeidx=0) thght = np.asarray(refDat.variables["HGT"])[0] * units.meter lats, lons = latlon_coords(ref_h) # Pull in the values from the perturbation ph = np.asarray(destagger(perDat.variables["PH"][0], 0)) * units('m^2/s^2') phb = np.asarray(destagger(refDat.variables["PHB"][0], 0)) * units('m^2/s^2') ua = np.asarray(destagger(perDat.variables["U"][0], 2)) * units('m/s') va = np.asarray(destagger(perDat.variables["V"][0], 1)) * units('m/s') # Calculate geopotential print("Converting from perturbation height to height AGL...") geo = ph + phb # Convert to height hght = mcalc.geopotential_to_height(geo) # Convert to height_agl h = np.zeros_like(hght) for i in range(hght.shape[0]): h[i] = hght[i] - thght print("Done.\n") # Get the x and y values of the lat and lon coordinates x, y = ll_to_xy(refDat, lats, lons) x = np.arange(0, np.max(x.data) + 1) * dx y = np.arange(0, np.max(y.data) + 1) * dy # Interpolate the winds speeds and temps to the heights specified in levs if debug: print("\nInterpolating wind values to every " + str(dz.m) + " meters... \n") ua_m = metpy.interpolate.interpolate_1d(levs, h, ua) va_m = metpy.interpolate.interpolate_1d(levs, h, va) perDat.close() refDat.close() return h, x, y, ua_m, va_m
def compute_OMEGA(filename, inputinf=None): """ Function to calculate vertical velocity in pressure units """ ncfile = nc.Dataset(filename, 'r') omega = wrf.getvar(ncfile, "omega", wrf.ALL_TIMES) atts = { "standard_name": "omega", "long_name": "vertical windspeed in pressure units", "units": "Pa s-1" } return omega, atts
def compute_PW(filename, inputinf=None): """ Function to calculate precipitable water in the column """ ncfile = nc.Dataset(filename, 'r') pw = wrf.getvar(ncfile, "pw", wrf.ALL_TIMES) atts = { "standard_name": "precipitable_water", "long_name": "column precipitable water", "units": "kg m-2" } return pw, atts
def compute_CLDFRA(filename, inputinf=None): """ Function to calculate cloud fraction at mass full levels as estimated by WRF""" ncfile = nc.Dataset(filename, 'r') cldfra = wrf.getvar(ncfile, "CLDFRA", wrf.ALL_TIMES) atts = { "standard_name": "Cloud_Fraction", "long_name": "cloud fraction at mass levels", "units": "m3 m-3" } return cldfra, atts
def __init__(self, config): """ construct input wrf file names """ self.ncfile = Dataset(config['INPUT']['input_fn']) self.resolution = float( wrf.extract_global_attrs(self.ncfile, 'DX')['DX']) n_radius = int( int(config['INPUT']['vis_radius']) / int(self.resolution)) times_dt64 = wrf.getvar(self.ncfile, 'Times', timeidx=wrf.ALL_TIMES, method="cat").values self.tgt_timeframe = datetime.datetime.strptime( config['INPUT']['vis_timestamp'], '%Y%m%d%H%M%S') print(print_prefix + 'Selected Timeframe:%s' % self.tgt_timeframe.strftime('%Y-%m-%d_%H:%M:%S')) # get idx of the field will be extract tgt_times_dt64 = np.datetime64(self.tgt_timeframe) t_idx = np.where(times_dt64 == tgt_times_dt64)[0][0] print(print_prefix + 'init from single input file for lat2d, lon2d, and hgt') self.xlat = wrf.getvar(self.ncfile, 'XLAT') self.xlon = wrf.getvar(self.ncfile, 'XLONG') print(print_prefix + 'init from single input file for Z4d') self.SLP = wrf.getvar(self.ncfile, 'slp', timeidx=t_idx) self.tc_ix, self.tc_iy = find_tc_center(self.SLP) print(print_prefix + 'init from single input file for Z4d') self.Z = wrf.getvar(self.ncfile, 'z', timeidx=t_idx) print(print_prefix + 'init from single input file for U4d') self.U = wrf.getvar(self.ncfile, 'ua', timeidx=t_idx) print(print_prefix + 'init from single input file for V4d') self.V = wrf.getvar(self.ncfile, 'va', timeidx=t_idx) print(print_prefix + 'init from single input file for W4d') self.W = wrf.getvar(self.ncfile, 'wa', timeidx=t_idx) print(print_prefix + 'init multi files successfully!')
def extraerWrfoutSerie(file_paths: str, x: int, y: int): dfData = pd.DataFrame() for f in file_paths: wrf_temp = Dataset(f) t2 = wrf.getvar(wrf_temp, "T2", timeidx=wrf.ALL_TIMES) wrf_temp.close() t2_ubp = t2[:, y, x] dfT2ubp = pd.DataFrame(t2_ubp.to_pandas(), columns=['T2']) dfT2ubp['T2'] = dfT2ubp['T2'] - 273.15 dfData = pd.concat([dfData, dfT2ubp[9:33]]) return dfData
def load_wrfdata(data_dir): wrf_files = [f for f in os.listdir(data_dir) if f[9] == '2'] wrf_list = [ Dataset(os.path.join(data_dir, wrf_file)) for wrf_file in wrf_files ] var_list = ['U10', 'V10'] u10, v10 = [ w.getvar(wrf_list, var, timeidx=w.ALL_TIMES, method='cat') for var in var_list ] lats, lons = w.latlon_coords(u10) return u10, v10, lats, lons
def getdata(str_id, path): files = [Dataset(path+f) for f in os.listdir(path) \ if f.startswith('wrfout')] X = wrf.getvar(files, str_id, timeidx=wrf.ALL_TIMES, method='join', meta=True) if str_id.startswith('wspd_wdir'): X = X[0, ] #in this case we choose wind speed return X
def load_wind(data_dir, domain): wrf_files = [f for f in os.listdir(data_dir) if f[11] == f'{domain}'] wrf_list = [ Dataset(os.path.join(data_dir, wrf_file)) for wrf_file in wrf_files ] var_list = ['U10', 'V10'] u10, v10 = [ w.getvar(wrf_list, var, timeidx=w.ALL_TIMES, method='cat') for var in var_list ] lats, lons = w.latlon_coords(u10) time = u10.Time.to_index() return u10, v10, lats, lons, time
def load_wrfdata(data_dir): wrf_files = [f for f in os.listdir(data_dir) if f[11]=='2'] wrflist = [Dataset(os.path.join(data_dir, wrf_file)) for wrf_file in wrf_files] # tsk = w.getvar(wrflist, 'TSK', timeidx=w.ALL_TIMES, method='cat') # ### 强制附上salem的grid属性,才能施以salem独有的方法 # tsk.attrs['pyproj_srs'] = salem.open_wrf_dataset(os.path.join(data_dir, wrf_files[0])).attrs['pyproj_srs'] # del tsk.attrs['projection'] # del tsk.attrs['coordinates'] lats, lons = w.latlon_coords(tsk) time = tsk.Time.to_index() return tsk, lats, lons, time
def wrf_ncrcat_output(wrf_dir): """try to read the output of ncrcat using wrf.getvar() This works, but only if the ncrcat output includes the Times *variable*, in addition to the Time *dimension* (which is included by default) """ fname = "HFX_1day_notime.nc" t0 = datetime.datetime.now() print('starting {} read with wrf.getvar() ({})'.format(fname, t0)) bigfile = netCDF4.Dataset(os.path.join(wrf_dir, fname), 'r') wrfv = wrf.getvar(bigfile, 'HFX', wrf.ALL_TIMES) # netcdf4v = bigfile.variables['HFX'][...] bigfile.close() print('done {} ({})'.format(fname, datetime.datetime.now() - t0)) return(wrfv)
def wrf_extract_var_constants(path_to_file,filename,variables): ##path_to_file is a string that either leads to one file or leads to directory that contains many netcdf files ##variables is a list of strings that are variables within the netcdf files. These are case sensitive, and are assumed to be ##constants within the netcdf file (i.e. these do not change throughout the simulation) ##save_label is the hanging label that will be used to save variables: ##variables will be saved as VARNAME_savelabel ##this will delete files that are of the same name in the path_to_save directory ##creates a directory that is called exctracted_vars in the local directory ##returns the location of the new directory where our files are saved ##sets current directory directory_path = os.path.dirname(os.path.realpath(__file__)) print(directory_path) new_directory = directory_path+'/exctracted_vars/' ##attempts to create the new directory try: os.makedirs(new_directory) except OSError: print('%s Directory Failed to Create. May be already present' %new_directory) ####list files in path provided, and append as a dataset (netcdf data set class) file_names = glob.glob(path_to_file+'/' + filename) file_list= [] file_list.append(Dataset(file_names[0])) #loop over variables desired for i,var in enumerate(variables): ##print variable extraction print('------Extracting Variable %s------ '%var) variable = wrf.getvar(file_list,var,timeidx=0,method="cat") variable_np = wrf.to_np(variable) #create variable save name savefile_loop = new_directory + var np.save(savefile_loop,variable_np) print('-----Extract Variables Finished----') return new_directory
def get_plot_element(infile): """get_plot_element .. description: get boxes from geo_em files to draw on plot .. args: infile (str): filename (e.g. geo_em.d01.nc) .. returns: cart_proj xlim ylim """ rootgroup = nc.Dataset(infile, 'r') p = getvar(rootgroup, 'HGT_M') cart_proj = get_cartopy(p) xlim = cartopy_xlim(p) ylim = cartopy_ylim(p) rootgroup.close() return cart_proj, xlim, ylim
def test(self): # Only testing vinterp since other interpolation just use variables if (varname == "vinterp"): for timeidx in (0, None): eth = getvar(wrf_in, "eth", timeidx=timeidx) interp_levels = [850, 500, 5] field = vinterp(wrf_in, field=eth, vert_coord="pressure", interp_levels=interp_levels, extrapolate=True, field_type="theta-e", timeidx=timeidx, log_p=True) else: pass
lat_wrf = nc_wrf.variables['XLAT'][0,:,0] latli = np.argmin(np.abs(lat_wrf-latbounds[1])) latui = np.argmin(np.abs(lat_wrf-latbounds[0])) lonli = np.argmin(np.abs(lon_wrf-lonbounds[0])) lonui = np.argmin(np.abs(lon_wrf-lonbounds[1])) lon_wrf = lon_wrf[lonli:lonui] lat_wrf = lat_wrf[latui:latli] lon_wrf,lat_wrf = np.meshgrid(lon_wrf,lat_wrf) wrf_loop = len(nc_wrf.variables['Times'][168:409]) wrf_lat_len = len(lat_wrf[:,0]) wrf_lon_len = len(lon_wrf[0,:]) orig_def = pyresample.geometry.SwathDefinition(lons=lon_wrf, lats=lat_wrf) targ_def = pyresample.geometry.SwathDefinition(lons=lon_era, lats=lat_era) expected = np.zeros([era_loop,era_lat_len,era_lon_len]) for i in range(0,wrf_loop): slp_wrf = getvar(nc_wrf, "slp", i, units="hPa",meta=False)[latui:latli,lonli:lonui] expected[i,:,:] = pyresample.kd_tree.resample_gauss(orig_def, slp_wrf, targ_def, radius_of_influence=50000, neighbours=10,sigmas=25000, fill_value=None) if dataset == '2': print('Evaluate which WRF-ARW variable? (1) Temperature at 2 meters, (2) Wind Speed at 10m or (3) Sea Level Pressure?') contourf_var = input() if contourf_var=='1': nc_cfsr = netCDF4.Dataset(cfsr_file) lon_cfsr = nc_cfsr.variables['lon'][:] lat_cfsr = nc_cfsr.variables['lat'][:] latli = np.argmin(np.abs(lat_cfsr-latbounds[1])) latui = np.argmin(np.abs(lat_cfsr-latbounds[0])) lonli = np.argmin(np.abs(lon_cfsr-lonbounds[0])) lonui = np.argmin(np.abs(lon_cfsr-lonbounds[1])) lon_cfsr = nc_cfsr.variables['lon'][lonli:lonui] lat_cfsr = nc_cfsr.variables['lat'][latli:latui]
def collect_data(date, para, cuttime, region, region_sn, region_we, path): """ cuts out the defined areas and calculates hourly median daily min / max for all 3 runs used for MIN/MAX box plots Output: sorted list of all areas with runs as dataarray """ import wrf import pandas as pd import xarray as xr import numpy as np from netCDF4 import Dataset from wrf import getvar filename = 'wrfout_d03_' + date + '_18_00_00.nc' ref = 'REF_Run_' + str(pd.to_datetime(date).year) # reference run spr = 'SPR_Run_' + str(pd.to_datetime(date).year) # sprawl run opt = 'OPT_Run_' + str(pd.to_datetime(date).year) # optimized city run ref_filepath = path + ref + '/' spr_filepath = path + spr + '/' opt_filepath = path + opt + '/' ref_ncfile = Dataset(ref_filepath + filename) spr_ncfile = Dataset(spr_filepath + filename) opt_ncfile = Dataset(opt_filepath + filename) times = getvar(ref_ncfile, "Times", timeidx=wrf.ALL_TIMES, meta=False) # FC times in np.datetime64 format - very ugly init = pd.to_datetime(times[0]) # converts the numpy datetime to datetime datetime format init = str(init) # initial time of wrf dataset ref_data = getvar(ref_ncfile, para, timeidx=wrf.ALL_TIMES) spr_data = getvar(spr_ncfile, para, timeidx=wrf.ALL_TIMES) opt_data = getvar(opt_ncfile, para, timeidx=wrf.ALL_TIMES) ref_d={} spr_d={} opt_d={} for i,j in zip(region_sn, region_we): ref_d["{0}".format(i)] = ref_data.isel(south_north=slice(region_sn[i][0],region_sn[i][1]), west_east=slice(region_we[j][0],region_we[j][1])) spr_d["{0}".format(i)] = spr_data.isel(south_north=slice(region_sn[i][0],region_sn[i][1]), west_east=slice(region_we[j][0],region_we[j][1])) opt_d["{0}".format(i)] = opt_data.isel(south_north=slice(region_sn[i][0],region_sn[i][1]), west_east=slice(region_we[j][0],region_we[j][1])) for name in ref_d: for t in cuttime: ref_d["{0}".format(name)] = ref_d["{0}".format(name)].where(ref_d["{0}".format(name)]['Time'].dt.day != t.day, drop=True).rename("{0}".format(name) + '_' + ref[:3]) spr_d["{0}".format(name)] = spr_d["{0}".format(name)].where(spr_d["{0}".format(name)]['Time'].dt.day != t.day, drop=True).rename("{0}".format(name) + '_' + spr[:3]) opt_d["{0}".format(name)] = opt_d["{0}".format(name)].where(opt_d["{0}".format(name)]['Time'].dt.day != t.day, drop=True).rename("{0}".format(name) + '_' + opt[:3]) ref_math={} spr_math={} opt_math={} for name in ref_d: ref_math["{0}_median".format(name)] = ref_d["{0}".format(name)].groupby(ref_d["{0}".format(name)].Time.dt.hour).median() - 273.15 ref_math["{0}_min".format(name)] = ref_d["{0}".format(name)].groupby(ref_d["{0}".format(name)].Time.dt.day).min(axis=0) - 273.15 ref_math["{0}_max".format(name)] = ref_d["{0}".format(name)].groupby(ref_d["{0}".format(name)].Time.dt.day).max(axis=0) - 273.15 spr_math["{0}_median".format(name)] = spr_d["{0}".format(name)].groupby(spr_d["{0}".format(name)].Time.dt.hour).median() - 273.15 spr_math["{0}_min".format(name)] = spr_d["{0}".format(name)].groupby(spr_d["{0}".format(name)].Time.dt.day).min(axis=0) - 273.15 spr_math["{0}_max".format(name)] = spr_d["{0}".format(name)].groupby(spr_d["{0}".format(name)].Time.dt.day).max(axis=0) - 273.15 opt_math["{0}_median".format(name)] = opt_d["{0}".format(name)].groupby(opt_d["{0}".format(name)].Time.dt.hour).median() - 273.15 opt_math["{0}_min".format(name)] = opt_d["{0}".format(name)].groupby(opt_d["{0}".format(name)].Time.dt.day).min(axis=0) - 273.15 opt_math["{0}_max".format(name)] = opt_d["{0}".format(name)].groupby(opt_d["{0}".format(name)].Time.dt.day).max(axis=0) - 273.15 reg_max = {} reg_min = {} reg_med = {} for name in ref_d: reg_max["{0}_max".format(name)] = DataArray_drop_to_Frame(ref_math["{0}_max".format(name)], spr_math["{0}_max".format(name)], opt_math["{0}_max".format(name)]) reg_min["{0}_min".format(name)] = DataArray_drop_to_Frame(ref_math["{0}_min".format(name)], spr_math["{0}_min".format(name)], opt_math["{0}_min".format(name)]) reg_med["{0}_median".format(name)] = DataArray_to_dataframe(ref_math["{0}_median".format(name)], spr_math["{0}_median".format(name)], opt_math["{0}_median".format(name)]) reg_med = sorted(reg_med.items(), key=lambda x: x[0]) reg_min = sorted(reg_min.items(), key=lambda x: x[0]) reg_max = sorted(reg_max.items(), key=lambda x: x[0]) return reg_med, reg_min, reg_max, init
#if not os.path.exists(plot_dir): # os.makedirs(plot_dir) # # #ncfile = Dataset(filepath + filenam) #ncfile1 = Dataset(filepath1 + filenam) #ncfile2 = Dataset(filepath2 + filenam) ##ncfile2 = Dataset(filepath2 + filenam) ##Dimension of domain #data = getvar(ncfile, para, timeidx=wrf.ALL_TIMES) #data_max = (data.max()/10).round()*10 #data_min = (data.min()/10).round()*10 #data1 = getvar(ncfile1, para, timeidx=wrf.ALL_TIMES) #data2 = getvar(ncfile2, para, timeidx=wrf.ALL_TIMES) # times = getvar(ncfile1, "Times", timeidx=wrf.ALL_TIMES, meta=False) # FC times in np.datetime64 format - very ugly #init = pd.to_datetime(times[0]) # converts the numpy datetime to datetime datetime format #init = str(init) # initial time of wrf dataset #spinup = pd.Timedelta('3 days') # spinup time for wrf and espacially TEB Canopy Temperatures times = times[72:] # Spacial selection of reference AREAS # #NO = data.isel(south_north=slice(73,82), west_east=slice(89,98)) #CE = data.isel(south_north=slice(50,59), west_east=slice(80,89)) #RU = data.isel(south_north=slice(57,66), west_east=slice(128,137)) #SA = data.isel(south_north=slice(58,67), west_east=slice(109,118)) #SE = data.isel(south_north=slice(37,46), west_east=slice(99,108)) #SX = data.isel(south_north=slice(24,33), west_east=slice(75,84)) #SI = data.isel(south_north=slice(31,40), west_east=slice(68,77)) #VW = data.isel(south_north=slice(47,56), west_east=slice(64,73)) #WE = data.isel(south_north=slice(62,71), west_east=slice(73,82))
path = '/hp4/Urbania/WRF-TEB/WPS' param = 'LU_INDEX' filepath1 = path + '/' filenam = 'geo_em.d03.nc' plot_dir ='/home/kristofh/projects/Urbania/plots/' + date + '/' + run + '/' if not os.path.exists(plot_dir): os.makedirs(plot_dir) ncfile = Dataset(filepath1 + filenam) #%% #Dimension of domain data = getvar(ncfile, param, timeidx=wrf.ALL_TIMES) data_max = (data.max()/10).round()*10 data_min = (data.min()/10).round()*10 times = getvar(ncfile, "Times", timeidx=wrf.ALL_TIMES, meta=False) # FC times in np.datetime64 format - very ugly init = pd.to_datetime(times[0]) # converts the numpy datetime to datetime datetime format init = str(init) # initial time of wrf dataset #%% for idx, time in enumerate(times): #get vavriable from netCDF file var = getvar(ncfile, param, timeidx=idx) title = var.description
clevs = np.arange(-3,3,0.005) # (min,max,spacing) cxlatlon = 'Longitude' fig_dir = './' fig_name = 'temp2.png' dpi_opt = 300 ################### Don't change above ################### # WRF module # Open the NetCDF file ncfile_wrs = Dataset(filename_wrs) ncfile_wr = Dataset(filename_wr) ncfile_wrf = Dataset(filename_wrf) # Extract the model height and wind speed z_wrs = getvar(ncfile_wrs, "z") temp_wrs = getvar(ncfile_wrs, "tc", timeidx=timeidx) z_wr = getvar(ncfile_wr, "z") temp_wr = getvar(ncfile_wr, "tc", timeidx=timeidx) z_wrf = getvar(ncfile_wrf, "z") temp_wrf = getvar(ncfile_wrf, "tc", timeidx=timeidx) # Compute the vertical cross-section interpolation. Also, include the lat/lon # points along the cross-section. temp_cross_wrs = vertcross(temp_wrs, z_wrs, wrfin=ncfile_wrs, start_point=start_point, end_point=end_point, latlon=True, meta=True,levels=levels)
import numpy as np import matplotlib.pyplot as plt from matplotlib.cm import get_cmap import cartopy.crs as crs from cartopy.feature import NaturalEarthFeature from netCDF4 import Dataset from wrf import to_np, getvar, CoordPair, vertcross # Open the NetCDF file filename = "/home/lnx/MODELS/WRF/3_testdata/Urbania/Tair_d03.nc" ncfile = Dataset(filename) # Extract the model height and wind speed z = getvar(ncfile, "bottom_top") #z = getvar(ncfile, "z") wspd = getvar(ncfile, "Tair", units="kt")[0,:] # Create the start point and end point for the cross section start_point = CoordPair(lat=48.19833, lon=16.36694) end_point = CoordPair(lat=26.76, lon=-77.8) # Compute the vertical cross-section interpolation. Also, include the lat/lon # points along the cross-section. wspd_cross = vertcross(wspd, z, wrfin=ncfile, start_point=start_point, end_point=end_point, latlon=True, meta=True) # Create the figure fig = plt.figure(figsize=(12,6)) ax = plt.axes()
# hgt_cont = bm.contour(x,y,to_np(hgt), levels=heights, colors="magenta", linewidths=0.4, alpha=1) var_cont = bm.contour(x,y,to_np(var), colors="black", levels=levels, linewidths=0.4, alpha=0.5) var_contf = bm.contourf(x,y,to_np(var), levels=levels, cmap=get_cmap("RdBu_r"), extend='both', alpha=0.9) cb_var = fig.colorbar(var_contf, ax=ax, shrink=0.7) cb_var.ax.tick_params(labelsize=8) return """ END defining FUNCTIONS """ ncfile = Dataset(filepath + filenam) ncfile1 = Dataset(filepath1 + filenam) ncfile2 = Dataset(filepath2 + filenam) #Dimension of domain data = getvar(ncfile, para, timeidx=wrf.ALL_TIMES) data_max = (data.max()/10).round()*10 data_min = (data.min()/10).round()*10 data1 = getvar(ncfile1, para, timeidx=wrf.ALL_TIMES) data2 = getvar(ncfile2, para, timeidx=wrf.ALL_TIMES) data.close() data1.close() data2.close() times = getvar(ncfile, "Times", timeidx=wrf.ALL_TIMES, meta=False) # FC times in np.datetime64 format - very ugly init = pd.to_datetime(times[0]) # converts the numpy datetime to datetime datetime format init = str(init) # initial time of wrf dataset ref = data # data is a safetyvariable for attributes spr = data1
import os, sys, string from datetime import datetime, timedelta # Author and script informations. _author_ = 'Ueslei Adriano Sutil' _email_ = '*****@*****.**' _created_ = datetime(2017, 07, 20) _modified_ = datetime(2017, 07, 20) _version_ = "0.1" _status_ = "Development" # Open the NetCDF file. ncfile = Dataset("/media/uesleisutil/Ueslei/INPE/2014/Outputs/wrf_I_t01.nc") # Get the data. slp = getvar(ncfile, "slp", timeidx=78) uvmet10 = getvar(ncfile, "uvmet10", units="km h-1", timeidx=78) u10 = uvmet10[1,:,:] v10 = uvmet10[0,:,:] lh = getvar(ncfile, "LH", timeidx=78) # Smooth the sea level pressure since it tends to be noisy near the mountains. smooth_slp = smooth2d(slp, 5) # Get the latitude and longitude points. lats, lons = latlon_coords(slp) # Get the cartopy mapping object. cart_proj = get_cartopy(slp) # Create a figure.
def area_collect_data_opt_spr(date, para, cuttime, path): import wrf import pandas as pd import xarray as xr import numpy as np from netCDF4 import Dataset from wrf import getvar filename = 'wrfout_d03_' + date + '_18_00_00.nc' ref = 'REF_Run_' + str(pd.to_datetime(date).year) # reference run spr = 'SPR_Run_' + str(pd.to_datetime(date).year) # sprawl run opt = 'OPT_Run_' + str(pd.to_datetime(date).year) # optimized city run ref_filepath = path + ref + '/' spr_filepath = path + spr + '/' opt_filepath = path + opt + '/' ref_ncfile = Dataset(ref_filepath + filename) spr_ncfile = Dataset(spr_filepath + filename) opt_ncfile = Dataset(opt_filepath + filename) times = getvar(ref_ncfile, "Times", timeidx=wrf.ALL_TIMES, meta=False) # FC times in np.datetime64 format - very ugly init = pd.to_datetime(times[0]) # converts the numpy datetime to datetime datetime format init = str(init) # initial time of wrf dataset ref = getvar(ref_ncfile, para, timeidx=wrf.ALL_TIMES) spr = getvar(spr_ncfile, para, timeidx=wrf.ALL_TIMES) opt = getvar(opt_ncfile, para, timeidx=wrf.ALL_TIMES) """ START ELIMINATING unsuseable days like spinup & cloudy days """ for i in cuttime: spr = spr.where(spr['Time'].dt.day != i.day, drop=True).rename('SPR') ref = ref.where(ref['Time'].dt.day != i.day, drop=True).rename('REF') opt = opt.where(opt['Time'].dt.day != i.day, drop=True).rename('OPT') """ END ELIMINATING unsuseable days like spinup & cloudy days """ """ START Calculation of areal median of MIN & MAX for REF SPR OPT """ ref_daily_max = ref.groupby(ref.Time.dt.day).max(axis=0) ref_daily_min = ref.groupby(ref.Time.dt.day).min(axis=0) ref_med_max = ref_daily_max.median(axis=0) - 273.15 ref_med_min = ref_daily_min.median(axis=0) -273.15 ref_med_max = ref_med_max.assign_attrs({'projection': ref.projection, 'description': 'REF Median of MAX '+ref.description, 'units': 'degree Celsius'}) ref_med_min = ref_med_min.assign_attrs({'projection': ref.projection, 'description': 'REF Median of MIN '+ref.description, 'units': 'degree Celsius'}) opt_daily_max = opt.groupby(opt.Time.dt.day).max(axis=0) opt_daily_min = opt.groupby(opt.Time.dt.day).min(axis=0) opt_med_max = opt_daily_max.median(axis=0) - 273.15 opt_med_min = opt_daily_min.median(axis=0) - 273.15 opt_med_max = opt_med_max.assign_attrs({'projection': ref.projection, 'description': 'OPT Median of MAX '+ref.description, 'units': 'degree Celsius'}) opt_med_min = opt_med_min.assign_attrs({'projection': ref.projection, 'description': 'OPT Median of MIN '+ref.description, 'units': 'degree Celsius'}) spr_daily_max = spr.groupby(spr.Time.dt.day).max(axis=0) spr_daily_min = spr.groupby(spr.Time.dt.day).min(axis=0) spr_med_max = spr_daily_max.median(axis=0) - 273.15 spr_med_min = spr_daily_min.median(axis=0) - 273.15 spr_med_max = spr_med_max.assign_attrs({'projection': ref.projection, 'description': 'SPR Median of MAX '+ref.description, 'units': 'degree Celsius'}) spr_med_min = spr_med_min.assign_attrs({'projection': ref.projection, 'description': 'SPR Median of MIN '+ref.description, 'units': 'degree Celsius'}) """ END Calculation of areal median of MIN & MAX """ """ START Calculation of Differences between REF SPR OPT """ spr_max_diff = spr_med_max - ref_med_max spr_min_diff = spr_med_min - ref_med_min opt_max_diff = opt_med_max - ref_med_max opt_min_diff = opt_med_min - ref_med_min opt_spr_min_diff = opt_med_min - spr_med_min opt_spr_max_diff = opt_med_max - spr_med_max spr_max_diff = spr_max_diff.assign_attrs({'projection': ref.projection, 'description': 'Difference SPR - REF of Median of MAX '+ref.description, 'units': 'degree Celsius'}) spr_min_diff = spr_min_diff.assign_attrs({'projection': ref.projection, 'description': 'Difference SPR - REF Median of MIN '+ref.description, 'units': ref.units}) opt_max_diff = opt_max_diff.assign_attrs({'projection': ref.projection, 'description': 'Difference OPT - REF of Median of MAX '+ref.description, 'units': 'degree Celsius'}) opt_min_diff = opt_min_diff.assign_attrs({'projection': ref.projection, 'description': 'Difference OPT - REF Median of MIN '+ref.description, 'units': 'degree Celsius'}) opt_spr_min_diff = opt_spr_min_diff.assign_attrs({'projection': ref.projection, 'description': str(pd.to_datetime(date).year) + ' Difference OPT - SPR Median of MIN '+ref.description, 'units': 'degree Celsius'}) opt_spr_max_diff = opt_spr_max_diff.assign_attrs({'projection': ref.projection, 'description': str(pd.to_datetime(date).year) + ' Difference OPT - SPR Median of MAX '+ref.description, 'units': 'degree Celsius'}) """ END Calculation of Differences between REF SPR OPT """ """ START getting LU_INDEX/HGT and create DIFFS """ hgt = getvar(ref_ncfile, 'HGT') ref_lu = getvar(ref_ncfile, 'LU_INDEX').rename('REF Landuse Category\'s') spr_lu = getvar(spr_ncfile, 'LU_INDEX').rename('SPR Landuse Category\'s') opt_lu = getvar(opt_ncfile, 'LU_INDEX').rename('OPT Landuse Category\'s') spr_lu_diff = spr_lu.where(ref_lu.data != spr_lu.data) opt_lu_diff = opt_lu.where(ref_lu.data != opt_lu.data) opt_spr_lu_diff = spr_lu.where(spr_lu.data != opt_lu.data) """ END getting LU_INDEX and create DIFFS """ return opt_spr_min_diff, opt_spr_max_diff, opt_spr_lu_diff, hgt
var_contf = bm.pcolormesh(x,y,to_np(var), cmap=get_cmap("viridis"), alpha=0.9) cb_var = fig.colorbar(var_contf, ticks=categ[::3], ax=ax, shrink=0.4) cb_var.ax.tick_params(labelsize=8) return ncfile = Dataset(filepath + filenam) ncfile1 = Dataset(filepath1 + filenam) ncfile2 = Dataset(filepath2 + filenam) #var = getvar(ncfile, param, timeidx=wrf.ALL_TIMES) #var.plot(cmap='tab20') hgt = getvar(ncfile, 'HGT_M') ref_lu = getvar(ncfile, 'LU_INDEX').rename('REF Landuse Category\'s') #spr_lu = getvar(ncfile1, 'LU_INDEX').rename('SPR Landuse Category\'s') #opt_lu = getvar(ncfile2, 'LU_INDEX').rename('OPT Landuse Category\'s') #spr_lu_diff = spr_lu.where(ref_lu.data != spr_lu.data) #opt_lu_diff = opt_lu.where(ref_lu.data != opt_lu.data) """ START Plotting routine for SPR """ fig, ax = plt.subplots(figsize=(20,9)) # Get the latitude and longitude points lats, lons = latlon_coords(spr_lu_diff)
if abs(y2-lattarget) < abs(lattarget-y1): titiky = titiky2 else: titiky = titiky1 for i in xrange(len(lonawal[0,:])): if lontarget > lonawal[0,i]: x2 = lonawal[0,i] x1 = lonawal[0,i-1] titikx2 = i titikx1 = i-1 if abs(x2-lontarget) < abs(lontarget-x1): titikx = titikx2 else: titikx = titikx1 omegacnt = [] for i in xrange(starttimestep,endtimestep): omegavar = getvar(dsetwrf, "omg", timeidx = i) omegacnt.append(omegavar[:,titiky,titikx]) #omegacnt = np.append(omegacnt, omegacnt = np.asarray(omegacnt) omegacnt = np.transpose(omegacnt) plt.contourf(waktu, height, omegacnt, 100) plt.colorbar() plt.gca().invert_yaxis() plt.show()
para = 'T2' cuttime = pd.to_datetime(['2069-7-1','2069-7-2','2069-7-3','2069-7-4','2069-7-5', '2069-7-6','2069-7-9']) # day with not usable data filenam = 'wrfout_' + domain + '_' + date + '_18_00_00.nc' plot_dir ='/hp4/Urbania/plots/' + date + '/' if not os.path.exists(plot_dir): os.makedirs(plot_dir) ncfile = Dataset(filepath + filenam) ncfile1 = Dataset(filepath1 + filenam) ncfile2 = Dataset(filepath2 + filenam) #ncfile2 = Dataset(filepath2 + filenam) #Dimension of domain data = getvar(ncfile, para, timeidx=wrf.ALL_TIMES) data_max = (data.max()/10).round()*10 data_min = (data.min()/10).round()*10 data1 = getvar(ncfile1, para, timeidx=wrf.ALL_TIMES) data2 = getvar(ncfile2, para, timeidx=wrf.ALL_TIMES) times = getvar(ncfile1, "Times", timeidx=wrf.ALL_TIMES, meta=False) # FC times in np.datetime64 format - very ugly init = pd.to_datetime(times[0]) # converts the numpy datetime to datetime datetime format init = str(init) # initial time of wrf dataset spinup = pd.Timedelta('3 days') # spinup time for wrf and espacially TEB Canopy Temperatures currtime = pd.to_datetime(times[0]) + spinup # starttime of period which is used #%% # Spacial and temporal selection of reference AREAS NO = data.isel(south_north=slice(73,82), west_east=slice(89,98)) CE = data.isel(south_north=slice(50,59), west_east=slice(80,89))
night.name = name + '_night' # day = xr.concat(spd_day, dire_day, dim='XTIME') # night = xr.concate(spd_night, dire_night, dim='XTIME') return day, night ncfile = Dataset(filepath + filenam) ncfile1 = Dataset(filepath1 + filenam) ncfile2 = Dataset(filepath2 + filenam) #ncfile2 = Dataset(filepath2 + filenam) #Dimension of domain ref_u10 = getvar(ncfile, u10, timeidx=wrf.ALL_TIMES) ref_v10 = getvar(ncfile, v10, timeidx=wrf.ALL_TIMES) spr_u10 = getvar(ncfile1, u10, timeidx=wrf.ALL_TIMES) spr_v10 = getvar(ncfile1, v10, timeidx=wrf.ALL_TIMES) opt_u10 = getvar(ncfile2, u10, timeidx=wrf.ALL_TIMES) opt_v10 = getvar(ncfile2, v10, timeidx=wrf.ALL_TIMES) times = getvar(ncfile1, "Times", timeidx=wrf.ALL_TIMES, meta=False) # FC times in np.datetime64 format - very ugly init = pd.to_datetime(times[0]) # converts the numpy datetime to datetime datetime format init = str(init) # initial time of wrf dataset """ START Calculation of resulting windvector and winddirection """ ref_v = np.sqrt(ref_u10**2 + ref_v10**2) spr_v = np.sqrt(spr_u10**2 + spr_v10**2)