def test(self): if testid == "xy_out": # Lats/Lons taken from NCL script, just hard-coding for now lats = [-55, -60, -65] lons = [25, 30, 35] xy = ll_to_xy(wrf_in, lats, lons, timeidx=0) xy = ll_to_xy(wrf_in, lats, lons, timeidx=None) else: i_s = np.asarray([10, 100, 150], int) j_s = np.asarray([10, 100, 150], int) ll = xy_to_ll(wrf_in, i_s, j_s, timeidx=0) ll = xy_to_ll(wrf_in, i_s, j_s, timeidx=None)
def sonde_in_wrf(profile, wrf, coords='xy', unique=True): ''' Calculate the sonde location in WRF Output: lon/lat and X/Y ''' # convert sonde lon/lat to X/Y x_y = ll_to_xy(wrf.ds, profile['lat'], profile['lon']).values # check noise X/Y counts = collections.Counter(x_y[0]) noise_x = list(x for x, num in counts.items() if num <= 2) # pair together x_y = np.stack((x_y[0], x_y[1]), axis=-1) if unique: # delete duplicated X/Y x_y = np.unique(x_y, axis=0) # delete noises noise_indices = [i for i, x in enumerate(x_y[:, 0]) if x in noise_x] x_y = np.delete(x_y, noise_indices, 0) if coords == 'xy': return x_y[:, 0], x_y[:, 1] elif coords == 'll': lat_lon = xy_to_ll(wrf.ds, x_y[:, 0], x_y[:, 1]) # print (lat_lon) # x_y = ll_to_xy(wrf.ds, lat_lon[0], lat_lon[1]) # print (x_y) return lat_lon[0].values, lat_lon[1].values # lat, lon
def test(self): from netCDF4 import Dataset as NetCDF timeidx = 0 in_wrfnc = NetCDF(wrf_in) refnc = NetCDF(referent) if testid == "xy": # Since this domain is not moving, the reference values are the # same whether there are multiple or single files ref_vals = refnc.variables["xy"][:] # Lats/Lons taken from NCL script, just hard-coding for now lats = [22.0, 25.0, 27.0] lons = [-90.0, -87.5, -83.75] xy = ll_to_xy(in_wrfnc, lats[0], lons[0]) nt.assert_allclose(to_np(xy), ref_vals) else: # Since this domain is not moving, the reference values are the # same whether there are multiple or single files ref_vals = refnc.variables["ll"][:] # i_s, j_s taken from NCL script, just hard-coding for now # NCL uses 1-based indexing for this, so need to subtract 1 x_s = np.asarray([10, 50, 90], int) y_s = np.asarray([10, 50, 90], int) ll = xy_to_ll(in_wrfnc, x_s[0], y_s[0]) nt.assert_allclose(to_np(ll), ref_vals)
def wrf_to_json(bucket_name, folder, spot_list): dataset = Dataset("20190327_wrfout_d02_2019-03-26_09_00_00") [lat, lon] = [44.469223022461, 1.3882482051849] # [x, y] = ll_to_xy(dataset, lat, lon).values json_out = {} # Variables to extract from the raw wrf file two_d_vars = ["PBLH", "RAINNC", "ter"] three_d_vars = ["z", "U", "V", "CLDFRA", "tc", "td", "p"] # Extract all variables first extracted_vars = {} for variable in two_d_vars: extracted_vars[variable] = getvar(dataset, variable) for variable in three_d_vars: extracted_vars[variable] = getvar(dataset, variable) for x in range(getattr(dataset, "WEST-EAST_GRID_DIMENSION") - 1): for y in range(getattr(dataset, "SOUTH-NORTH_GRID_DIMENSION") - 1): [lat, lon] = xy_to_ll(dataset, x, y) json_out = {"lat": lat, "lon": lon} for variable in two_d_vars: json_out[variable.lower()] = extracted_vars[variable][ y, x].values.tolist() for variable in three_d_vars: json_out[variable.lower( )] = extracted_vars[variable][:, y, x].values.tolist()
def test(self): try: from netCDF4 import Dataset as NetCDF except: pass try: from PyNIO import Nio except: pass if not multi: timeidx = 0 if not pynio: in_wrfnc = NetCDF(wrf_in) else: # Note: Python doesn't like it if you reassign an outer scoped # variable (wrf_in in this case) if not wrf_in.endswith(".nc"): wrf_file = wrf_in + ".nc" else: wrf_file = wrf_in in_wrfnc = Nio.open_file(wrf_file) else: timeidx = None if not pynio: nc = NetCDF(wrf_in) in_wrfnc = [nc for i in xrange(repeat)] else: if not wrf_in.endswith(".nc"): wrf_file = wrf_in + ".nc" else: wrf_file = wrf_in nc = Nio.open_file(wrf_file) in_wrfnc = [nc for i in xrange(repeat)] refnc = NetCDF(referent) if testid == "xy": # Since this domain is not moving, the reference values are the # same whether there are multiple or single files ref_vals = refnc.variables["ij"][:] # Lats/Lons taken from NCL script, just hard-coding for now lats = [-55, -60, -65] lons = [25, 30, 35] # Just call with a single lat/lon if single: xy = ll_to_xy(in_wrfnc, lats[0], lons[0]) xy = xy + 1 # NCL uses fortran indexing ref = ref_vals[:, 0] nt.assert_allclose(to_np(xy), ref) # Next make sure the 'proj' version works projparams = extract_proj_params(in_wrfnc) xy_proj = ll_to_xy_proj(lats[0], lons[0], **projparams) nt.assert_allclose(to_np(xy_proj), to_np(xy - 1)) else: xy = ll_to_xy(in_wrfnc, lats, lons) xy = xy + 1 # NCL uses fortran indexing ref = ref_vals[:] nt.assert_allclose(to_np(xy), ref) # Next make sure the 'proj' version works projparams = extract_proj_params(in_wrfnc) xy_proj = ll_to_xy_proj(lats, lons, **projparams) nt.assert_allclose(to_np(xy_proj), to_np(xy - 1)) else: # Since this domain is not moving, the reference values are the # same whether there are multiple or single files ref_vals = refnc.variables["ll"][:] # i_s, j_s taken from NCL script, just hard-coding for now # NCL uses 1-based indexing for this, so need to subtract 1 i_s = np.asarray([10, 100, 150], int) - 1 j_s = np.asarray([10, 100, 150], int) - 1 if single: ll = xy_to_ll(in_wrfnc, i_s[0], j_s[0]) ref = ref_vals[::-1, 0] nt.assert_allclose(to_np(ll), ref) # Next make sure the 'proj' version works projparams = extract_proj_params(in_wrfnc) ll_proj = xy_to_ll_proj(i_s[0], j_s[0], **projparams) nt.assert_allclose(to_np(ll_proj), to_np(ll)) else: ll = xy_to_ll(in_wrfnc, i_s, j_s) ref = ref_vals[::-1, :] nt.assert_allclose(to_np(ll), ref) # Next make sure the 'proj' version works projparams = extract_proj_params(in_wrfnc) ll_proj = xy_to_ll_proj(i_s, j_s, **projparams) nt.assert_allclose(to_np(ll_proj), to_np(ll))
def test(self): try: from netCDF4 import Dataset as NetCDF except ImportError: pass try: import Nio except ImportError: pass timeidx = 0 if not multi else None pat = os.path.join(dir, pattern) wrf_files = glob.glob(pat) wrf_files.sort() refnc = NetCDF(referent) try: refnc.set_always_mask(False) except AttributeError: pass wrfin = [] for fname in wrf_files: if not pynio: f = NetCDF(fname) try: f.set_auto_mask(False) except AttributeError: pass wrfin.append(f) else: if not fname.endswith(".nc"): _fname = fname + ".nc" else: _fname = fname f = Nio.open_file(_fname) wrfin.append(f) if testid == "xy": # Lats/Lons taken from NCL script, just hard-coding for now lats = [22.0, 25.0, 27.0] lons = [-90.0, -87.5, -83.75] # Just call with a single lat/lon if single: timeidx = 8 ref_vals = refnc.variables["xy2"][:] xy = ll_to_xy(wrfin, lats[0], lons[0], timeidx=timeidx, as_int=True) ref = ref_vals[:, 0] nt.assert_allclose(to_np(xy), ref) # Next make sure the 'proj' version works projparams = extract_proj_params(wrfin, timeidx=timeidx) xy_proj = ll_to_xy_proj(lats[0], lons[0], as_int=True, **projparams) nt.assert_allclose(to_np(xy_proj), to_np(xy)) else: ref_vals = refnc.variables["xy1"][:] xy = ll_to_xy(wrfin, lats, lons, timeidx=None, as_int=False) ref = ref_vals[:] nt.assert_allclose(to_np(xy), ref) if xy.ndim > 2: # Moving nest is_moving = True numtimes = xy.shape[-2] else: is_moving = False numtimes = 1 for tidx in range(9): # Next make sure the 'proj' version works projparams = extract_proj_params(wrfin, timeidx=tidx) xy_proj = ll_to_xy_proj(lats, lons, as_int=False, **projparams) if is_moving: idxs = (slice(None), tidx, slice(None)) else: idxs = (slice(None), ) nt.assert_allclose(to_np(xy_proj), to_np(xy[idxs])) else: # i_s, j_s taken from NCL script, just hard-coding for now # NCL uses 1-based indexing for this, so need to subtract 1 x_s = np.asarray([10, 50, 90], int) y_s = np.asarray([10, 50, 90], int) if single: timeidx = 8 ref_vals = refnc.variables["ll2"][:] ll = xy_to_ll(wrfin, x_s[0], y_s[0], timeidx=timeidx) ref = ref_vals[::-1, 0] nt.assert_allclose(to_np(ll), ref) # Next make sure the 'proj' version works projparams = extract_proj_params(wrfin, timeidx=8) ll_proj = xy_to_ll_proj(x_s[0], y_s[0], **projparams) nt.assert_allclose(to_np(ll_proj), to_np(ll)) else: ref_vals = refnc.variables["ll1"][:] ll = xy_to_ll(wrfin, x_s, y_s, timeidx=None) ref = ref_vals[::-1, :] nt.assert_allclose(to_np(ll), ref) if ll.ndim > 2: # Moving nest is_moving = True numtimes = ll.shape[-2] else: is_moving = False numtimes = 1 for tidx in range(numtimes): # Next make sure the 'proj' version works projparams = extract_proj_params(wrfin, timeidx=tidx) ll_proj = xy_to_ll_proj(x_s, y_s, **projparams) if is_moving: idxs = (slice(None), tidx, slice(None)) else: idxs = (slice(None), ) nt.assert_allclose(to_np(ll_proj), to_np(ll[idxs]))
def make_result_file(opts): infilename = os.path.expanduser( os.path.join(opts.outdir, "ci_test_file.nc")) outfilename = os.path.expanduser( os.path.join(opts.outdir, "ci_result_file.nc")) with Dataset(infilename) as infile, Dataset(outfilename, "w") as outfile: for varname in WRF_DIAGS: var = getvar(infile, varname) add_to_ncfile(outfile, var, varname) for interptype in INTERP_METHS: if interptype == "interpline": hts = getvar(infile, "z") p = getvar(infile, "pressure") hts_850 = interplevel(hts, p, 850.) add_to_ncfile(outfile, hts_850, "interplevel") if interptype == "vertcross": hts = getvar(infile, "z") p = getvar(infile, "pressure") pivot_point = CoordPair(hts.shape[-1] // 2, hts.shape[-2] // 2) ht_cross = vertcross(hts, p, pivot_point=pivot_point, angle=90.) add_to_ncfile(outfile, ht_cross, "vertcross") if interptype == "interpline": t2 = getvar(infile, "T2") pivot_point = CoordPair(t2.shape[-1] // 2, t2.shape[-2] // 2) t2_line = interpline(t2, pivot_point=pivot_point, angle=90.0) add_to_ncfile(outfile, t2_line, "interpline") if interptype == "vinterp": tk = getvar(infile, "temp", units="k") interp_levels = [200, 300, 500, 1000] field = vinterp(infile, field=tk, vert_coord="theta", interp_levels=interp_levels, extrapolate=True, field_type="tk", log_p=True) add_to_ncfile(outfile, field, "vinterp") for latlonmeth in LATLON_METHS: if latlonmeth == "xy": # Hardcoded values from other unit tests lats = [-55, -60, -65] lons = [25, 30, 35] xy = ll_to_xy(infile, lats[0], lons[0]) add_to_ncfile(outfile, xy, "xy") else: # Hardcoded from other unit tests i_s = np.asarray([10, 100, 150], int) - 1 j_s = np.asarray([10, 100, 150], int) - 1 ll = xy_to_ll(infile, i_s[0], j_s[0]) add_to_ncfile(outfile, ll, "ll")
# usando um arquivo da PCWRF para obter pontos de grade arq = nc.Dataset('../saidas/20200520_00/membro01/wrfout_d01_2020-05-20_00') # obtendo pontos de grade mais próximos das coordenadas LON,LAT fornecidas # estacoes_met_wrf[0,...] -> valores X (oeste-leste) # estacoes_met_wrf[1,...] -> valores Y (sul-norte) estacoes_met_wrf = wrf.ll_to_xy( arq, # coordenadas (X,Y) das estações INMET estacoes_met.iloc[:, 1].tolist(), estacoes_met.iloc[:, 2].tolist()) # obtendo LON,LAT dos pontos de grade obtidos acima # lat_lon_gridpoints[0,...] -> valores latitude # lat_lon_gridpoints[1,...] -> valores longitude lat_lon_gridpoints = wrf.xy_to_ll(arq, estacoes_met_wrf[0, :], estacoes_met_wrf[1, :]) # criando mapa com pontos de grade usados para extração e coordenadas das estações INMET projWRF = wrf.get_cartopy(wrfin=arq) estados = cfeature.NaturalEarthFeature(category='cultural', scale='50m', facecolor='none', name='admin_1_states_provinces_shp') # limites X e Y das coordenadas projetadas xlims = wrf.cartopy_xlim(wrfin=arq) ylims = wrf.cartopy_ylim(wrfin=arq) # criando gráfico ax = plt.axes(projection=projWRF) ax.coastlines('50m', linewidth=0.8)
from __future__ import print_function from netCDF4 import Dataset from wrf import getvar, interpline, CoordPair, xy_to_ll, ll_to_xy ncfile = Dataset("coa_I_t01.nc") lat_lon = xy_to_ll(ncfile, [400,105], [200,205]) print(lat_lon) x_y = ll_to_xy(ncfile, lat_lon[0,:], lat_lon[1,:]) print (x_y)
def convertLatLon(xs, ys): # Convert the launch points to lat/lon refDat = Dataset("/home/iarsenea/trajs/wrfoutREFd01") lats, lons = xy_to_ll(refDat, np.asarray(xs), np.asarray(ys)) return (lats, lons)