def test_interpolate(method, test_coords): r"""Test main interpolate function.""" xp, yp = test_coords xp *= 10 yp *= 10 z = np.array( [0.064, 4.489, 6.241, 0.1, 2.704, 2.809, 9.604, 1.156, 0.225, 3.364]) extra_kw = {} if method == 'cressman': extra_kw['search_radius'] = 200 extra_kw['minimum_neighbors'] = 1 elif method == 'barnes': extra_kw['search_radius'] = 400 extra_kw['minimum_neighbors'] = 1 extra_kw['gamma'] = 1 _, _, img = interpolate(xp, yp, z, hres=10, interp_type=method, **extra_kw) with get_test_data('{0}_test.npz'.format(method)) as fobj: truth = np.load(fobj)['img'] assert_array_almost_equal(truth, img)
def crtanje_m(): to_proj = ccrs.AlbersEqualArea(central_longitude=-1., central_latitude=10.) #load cordinates fname = '/home/martin/Master_rad/PredtandfilaGrid.dat' #col_names = ['index','lon','lat','country','altitude'] ovo koristimo ako nemama definisane imena kolona #load temp df = pd.read_fwf(fname, na_values='MM') lon = df['lon'].values lat = df['lat'].values xp, yp, _ = to_proj.transform_points(ccrs.Geodetic(), lon, lat).T data1 = pd.read_csv('/home/martin/Master_rad/CARPATGRID_TA_M.ser', sep='\s+') y = int(input('Unesite godinu: ' ' ')) m = int(input('Unesite mesec: ' ' ')) x1 = data1.loc[y, m] x_masked, y_masked, t = remove_nan_observations(xp, yp, x1.values) tempx, tempy, temp = interpolate(x_masked, y_masked, t, interp_type='barnes', minimum_neighbors=8, search_radius=150000, hres=30000) temp = np.ma.masked_where(np.isnan(temp), temp) levels = list(range(-20, 20, 1)) cmap = plt.get_cmap('viridis') norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True) fig = plt.figure(figsize=(20, 10)) view = fig.add_subplot(1, 1, 1, projection=to_proj) view.set_extent([27.0, 16.9, 49.5, 44.5]) view.add_feature(cfeature.STATES.with_scale('50m')) view.add_feature(cfeature.OCEAN) view.add_feature(cfeature.COASTLINE.with_scale('50m')) view.add_feature(cfeature.BORDERS, linestyle=':') mmb = view.pcolormesh(tempx, tempy, temp, cmap=cmap, norm=norm) fig.colorbar(mmb, shrink=.4, pad=0.02, boundaries=levels) view.set_title('Srednja temperatura') plt.show()
def test_interpolate(method, test_coords): r"""Test main interpolate function.""" xp, yp = test_coords xp *= 10 yp *= 10 z = np.array([0.064, 4.489, 6.241, 0.1, 2.704, 2.809, 9.604, 1.156, 0.225, 3.364]) extra_kw = {} if method == 'cressman': extra_kw['search_radius'] = 200 extra_kw['minimum_neighbors'] = 1 elif method == 'barnes': extra_kw['search_radius'] = 400 extra_kw['minimum_neighbors'] = 1 extra_kw['gamma'] = 1 _, _, img = interpolate(xp, yp, z, hres=10, interp_type=method, **extra_kw) truth = np.load(get_test_data('{0}_test.npz'.format(method)))['img'] assert_array_almost_equal(truth, img)
########################################### # Project the lon/lat locations to our final projection lon = data['longitude'].values lat = data['latitude'].values xp, yp, _ = to_proj.transform_points(ccrs.Geodetic(), lon, lat).T ########################################### # Remove all missing data from pressure x_masked, y_masked, pres = remove_nan_observations(xp, yp, data['slp'].values) ########################################### # Interpolate pressure using Cressman interpolation slpgridx, slpgridy, slp = interpolate(x_masked, y_masked, pres, interp_type='cressman', minimum_neighbors=1, search_radius=400000, hres=100000) ########################################## # Get wind information and mask where either speed or direction is unavailable wind_speed = (data['wind_speed'].values * units('m/s')).to('knots') wind_dir = data['wind_dir'].values * units.degree good_indices = np.where((~np.isnan(wind_dir)) & (~np.isnan(wind_speed))) x_masked = xp[good_indices] y_masked = yp[good_indices] wind_speed = wind_speed[good_indices] wind_dir = wind_dir[good_indices]
from_proj = ccrs.Geodetic() to_proj = ccrs.AlbersEqualArea(central_longitude=-97.0000, central_latitude=38.0000) levels = list(range(-20, 20, 1)) cmap = plt.get_cmap('magma') norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True) x, y, temp = station_test_data('air_temperature', from_proj, to_proj) x, y, temp = remove_nan_observations(x, y, temp) x, y, temp = remove_repeat_coordinates(x, y, temp) ########################################### # Scipy.interpolate linear # ------------------------ gx, gy, img = interpolate(x, y, temp, interp_type='linear', hres=75000) img = np.ma.masked_where(np.isnan(img), img) view = basic_map(to_proj) mmb = view.pcolormesh(gx, gy, img, cmap=cmap, norm=norm) plt.colorbar(mmb, shrink=.4, pad=0, boundaries=levels) ########################################### # Natural neighbor interpolation (MetPy implementation) # ----------------------------------------------------- # `Reference <https://github.com/Unidata/MetPy/files/138653/cwp-657.pdf>`_ gx, gy, img = interpolate(x, y, temp, interp_type='natural_neighbor', hres=75000) img = np.ma.masked_where(np.isnan(img), img) view = basic_map(to_proj) mmb = view.pcolormesh(gx, gy, img, cmap=cmap, norm=norm) plt.colorbar(mmb, shrink=.4, pad=0, boundaries=levels)
def plot_map(df, date, value, cbarlabel='', title='', cmap="Spectral_r", zmin=0, zmax=100, save=False): cities = [ 'Williston', 'Minot', 'Grand Forks', 'Fargo', 'Bismarck', 'Devils Lake' ] fig, ax = plt.subplots(figsize=(15, 10)) to_plot = df[df["Date"] == date] lon = to_plot['Longitude (deg)'].values lat = to_plot['Latitude (deg)'].values #make basemap map print("Making map...") m = Basemap(llcrnrlon=min(lon), llcrnrlat=min(lat), urcrnrlon=max(lon), urcrnrlat=max(lat), projection='merc', resolution='h') #Convert lon, lat to map coordinates and mask any missing points xp, yp = m(lon, lat) x_masked, y_masked, z = remove_nan_observations(xp, yp, to_plot[value].values) print("Interpolating data...") #Uncomment one of the interpolation methods below. rbf is chosen as a default #linear #gridx, gridy, z = interpolate(x_masked, y_masked, z, interp_type='linear', hres=5000) #rbf gridx, gridy, z = interpolate(x_masked, y_masked, z, interp_type='rbf', hres=5000, rbf_func='linear', rbf_smooth=0) #cressman #gridx, gridy, z = interpolate(x_masked, y_masked, z, interp_type='cressman', minimum_neighbors=1, hres=5000, #search_radius=100000) #barnes #gridx, gridy, z = interpolate(x_masked, y_masked, z, interp_type='barnes', hres=5000, #search_radius=100000) #Natural neighbor #gridx, gridy, z = interpolate(x_masked, y_masked, z, interp_type='natural_neighbor', hres=5000) z = np.ma.masked_where(np.isnan(z), z) #Find max and min of z if not input manually if zmax == 'max': zmax = np.max(z) if zmin == 'min': zmin = np.min(z) #normalize colormap cmap = plt.get_cmap(cmap) norm = Normalize(vmin=zmin, vmax=zmax) #Draw map lines m.drawcoastlines() m.drawcountries() m.drawstates() #Set contour line parameters. must be integers low = int(round(np.min(z))) high = int(round(np.max(z))) step = int(round((high - low) / 10)) #Set step at least 2 so there are not contour lines set for every increase of 1 (unless that's what you want) if step < 2: step = 2 #plot colormesh mmb = m.pcolormesh(gridx, gridy, z, cmap=cmap, norm=norm) cbar = m.colorbar(mmb, location='bottom') cs = m.contour(gridx, gridy, z, colors='k', levels=list(range(low, high, step)), alpha=0.3) plt.clabel(cs, inline=1, fontsize=12, fmt='%i') #Plot city markers geolocator = Nominatim() for city in cities: loc = geolocator.geocode(city) x, y = m(loc.longitude, loc.latitude) m.plot(x, y, marker='o', color='None', markeredgecolor='k', markersize=8) plt.text(x + 10000, y + 5000, city, fontsize=12, alpha=0.7) m.drawcounties() cbar.set_label(cbarlabel) plt.title(title, fontsize=18) if save: # Make sure a directory exists for the gdd data print("Checking for file pathways...") if not os.path.isdir("./maps"): os.mkdir('maps') print("Saving figure...") fig.savefig('./maps/' + str(title) + '.png', format='png') return m
return lon, lat, value ########################################### # Get pressure information using the sample station data xp, yp, pres = station_test_data(['slp'], from_proj, to_proj) ########################################### # Remove all missing data from pressure pres = np.array([p[0] for p in pres]) xp, yp, pres = remove_nan_observations(xp, yp, pres) ########################################### # Interpolate pressure as usual slpgridx, slpgridy, slp = interpolate(xp, yp, pres, interp_type='cressman', minimum_neighbors=1, search_radius=400000, hres=100000) ########################################### # Get wind information x, y, wind = station_test_data(['wind_speed', 'wind_dir'], from_proj, to_proj) ########################################### # Remove bad data from wind information wind_speed = np.array([w[0] for w in wind]) wind_dir = np.array([w[1] for w in wind]) good_indices = np.where((~np.isnan(wind_dir)) & (~np.isnan(wind_speed))) x = x[good_indices] y = y[good_indices] wind_speed = wind_speed[good_indices]
try: proj_points = proj_to.transform_points(proj_from, lon, lat) return proj_points[:, 0], proj_points[:, 1], value except Exception as e: print(e) return None return lon, lat, value from_proj = ccrs.Geodetic() to_proj = ccrs.AlbersEqualArea(central_longitude=-97.0000, central_latitude=38.0000) levels = list(range(-20, 20, 1)) cmap = plt.get_cmap('magma') norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True) x, y, temp = station_test_data('air_temperature', from_proj, to_proj) x, y, temp = remove_nan_observations(x, y, temp) x, y, temp = remove_repeat_coordinates(x, y, temp) gx, gy, img = interpolate(x, y, temp, interp_type='linear', hres=75000) img = np.ma.masked_where(np.isnan(img), img) view = basic_map(to_proj) mmb = view.pcolormesh(gx, gy, img, cmap=cmap, norm=norm) plt.colorbar(mmb, shrink=.4, pad=0, boundaries=levels)
def metpyplot(shpFiles, lonlat, mLon, mLat, mTem): # 初始化 #绘图参数设置 isStationInfoOn = False #站点信息是否标注 isaxInfoOn = False # 坐标轴信息是否标注 cmap = cmaps.BlAqGrYeOrReVi200 #色标选择 http://www.ncl.ucar.edu/Document/Graphics/color_table_gallery.shtml 参考该网址 MPL_YlOrRd amwg256 legendRange = [int(min(mTem)), math.ceil(max(mTem))] fbl = 0.05 #克里金插值空间分辨率 sebiaoNums = 15 #色标个数 picTitle = 'Temperature' zuobiaoSetInter = 0.5 #坐标轴经纬度间隔设置 # shpPath=r'./shp/TJ/' # shpName='TJ_all' ## bjName='TJ_bj' shpFile = shpFiles[0] # bjshp=shpPath+bjName #天津经纬度范围设置 # llat=38.5 # ulat=40.3 # llon=116.7 # ulon=118.05 llon = lonlat[0] ulon = lonlat[1] llat = lonlat[2] ulat = lonlat[3] # fig=plt.figure(figsize=(16,9)) plt.rc('font', size=15, weight='bold') # ax=fig.add_subplot(111) # 底图读取及地图设置 m=Basemap(llcrnrlon=llon,llcrnrlat=llat,urcrnrlon=ulon,urcrnrlat=ulat,\ projection='cyl',resolution='c') # 等距投影 m.readshapefile(shpFile, 'Name', linewidth=1, color='k') # 绘制经纬线 parallels = np.arange(llat, ulat, 0.5) m.drawparallels(parallels, labels=[1, 0, 0, 0], fontsize=10) # 绘制纬线 meridians = np.arange(llon, ulon, 0.5) m.drawmeridians(meridians, labels=[0, 0, 0, 1], fontsize=10) # 绘制经线 # 坐标系经纬度转换 xllon, yllat = m(llon, llat) xulon, yulat = m(ulon, ulat) xmLon, ymLat = m(mLon, mLat) # meshgrid set the grid range gridx = np.arange(xllon, xulon, fbl) gridy = np.arange(yllat, yulat, fbl) Xlon, Ylat = np.meshgrid(gridx, gridy) #插值处理 # OK=OrdinaryKriging(xmLon,ymLat,mTem,variogram_model='linear', # verbose=False,enable_plotting=False) # z,ss=OK.execute('grid',gridx,gridy) gx, gy, img = interpolate(xmLon, ymLat, mTem, \ interp_type='linear', hres=fbl) levels = np.linspace(legendRange[0], legendRange[1], sebiaoNums) cs = m.contourf(gx, gy, img, levels, cmap=cmap) m.colorbar(cs) # cf=m.contourf(Xlon,Ylat,z,levels=levels,cmap=cmap) # m.colorbar(cf,location='right',format='%.1f',size=0.3,\ # ticks=np.linspace(legendRange[0],legendRange[1],sebiaoNums),label='单位:℃') # # 添加站名信息 if isStationInfoOn == True: m.scatter(xmLon, ymLat, c='k', s=10, marker='o') for i in range(0, len(xmLon)): # pass plt.text(xmLon[i], ymLat[i], stationName[i], va='bottom', fontsize=12) # plt.text(xmLon[i],ymLat[i],mTem[i],va='top',fontsize=12) plt.title(picTitle) # 坐标轴标注 if isaxInfoOn == True: lon_label = [] lat_label = [] lon_num = np.arange(xllon, xulon, zuobiaoSetInter) for lon in lon_num: lon_label.append(str(lon) + '°E') lat_num = np.arange(yllat, yulat, zuobiaoSetInter) for lat in lat_num: lat_label.append(str(lat) + '°N') plt.yticks(lat_num, lat_label) plt.xticks(lon_num, lon_label) # 白化 # maskout.shp2clip(cf,ax,bjshp,0.005588) #0.005588为gis图周长信息 # picture introduction plt.show()