def test_2_points_should_work(self): """ Shiftdata should work with 2 points """ bm = Basemap(llcrnrlon=0, llcrnrlat=-80, urcrnrlon=360, urcrnrlat=80, projection='mill') lons_expected = [10, 15, 20] lonsout = bm.shiftdata(lons_expected[:]) assert_almost_equal(lons_expected, lonsout) lonsout_expected = bm.shiftdata([10, 361, 362]) lonsout = bm.shiftdata([10, 361]) assert_almost_equal(lonsout_expected[:len(lonsout)], lonsout)
def test_less_than_n_by_3_points_should_work(self): bm = Basemap(llcrnrlon=0, llcrnrlat=-80, urcrnrlon=360, urcrnrlat=80, projection='mill') lons_expected = self._get_2d_lons([10, 15, 20]) # nothing should change lonsout = bm.shiftdata(lons_expected) assert_almost_equal(lons_expected, lonsout) # shift n x 3 and n x 2 grids and compare results over overlapping region lonsin = self._get_2d_lons([10, 361, 362]) lonsout_expected = bm.shiftdata(lonsin[:])[:, :2] lonsout = bm.shiftdata(lonsin[:, :2]) assert_almost_equal(lonsout_expected, lonsout)
def test_1_point_should_work(self): bm = Basemap(llcrnrlon=0, llcrnrlat=-80, urcrnrlon=360, urcrnrlat=80, projection='mill') # should not fail lonsout = bm.shiftdata([361]) assert_almost_equal(lonsout, [1.0,]) lonsout = bm.shiftdata([10]) assert_almost_equal(lonsout, [10.0,]) lonsin = np.array([361.0]) lonsin.shape = (1, 1) lonsout = bm.shiftdata(lonsin[:]) assert_almost_equal(lonsout.squeeze(), [1.0,])
def plot_global_winds(nt, fig, Uin, Vin, lon1, lat1, datelabel, fname_out=False): print nt fig = plt.figure(figsize=(8, 4.5)) ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) #nframe = 0; n1 = 390 #nt = 0 pos = ax.get_position() l, b, w, h = pos.bounds map = Basemap(projection='cyl',llcrnrlat= -90.,urcrnrlat= 90.,\ resolution='c', llcrnrlon=-180.,urcrnrlon=180.) map.bluemarble() map.drawcoastlines() map.drawcountries() map.drawcoastlines(color='0.15') map.drawparallels(np.arange(-90., 91., 30.), labels=[1, 0, 0, 0], fontsize=10, linewidth=0.001, zorder=0) map.drawmeridians(np.arange(-180., 180., 30.), labels=[0, 0, 0, 1], fontsize=10, linewidth=0.001, zorder=0) clevs = np.arange(0, 50, 5) lonout, uu = map.shiftdata(lon1, Uin, lon_0=0) lonout, vv = map.shiftdata(lon1, Vin, lon_0=0) speed = np.sqrt(uu * uu + vv * vv) yy = np.arange(0, Y4.shape[0], 4) xx = np.arange(0, X4.shape[1], 4) points = np.meshgrid(yy, xx) vectplot = map.quiver(X4[points], Y4[points], uu[points], vv[points], color='lightgray') plt.quiverkey(vectplot, 0.1, -0.1, 10, '10 m/s', fontproperties={'weight': 'bold'}, labelpos='W', color='0.15') #-- position and reference label txt = plt.title('10-m Wind ' + str(datelabel), fontsize=14, fontweight='bold') if fname_out: fig.savefig(fname_out, dpi=100)
def test_shiftdata_on_monotonous_lons(self): """ Test that shiftdata with fix_wrap_around keyword added works as before, when it is True """ bm = Basemap(lon_0=0) lons_in = [120, 140, 160, 180, 200, 220] lons_out_expect = [-160, -140, 120, 140, 160, 180] lons_out = bm.shiftdata(lons_in, fix_wrap_around=True) assert_almost_equal(lons_out, lons_out_expect)
def test_non_monotonous_longitudes(self): """ when called for scatter, the longitudes passed to shiftdata are not necessarily monotonous... """ lons = [179, 180, 180, 0, 290, 10, 320, -150, 350, -250, 250] bm = Basemap(lon_0=0) # before, having several break points would cause the exception, # inside the shiftdata method called from scatter method. self.assertRaises(ValueError, bm.shiftdata, lons, fix_wrap_around=True) lons_new = bm.shiftdata(lons, fix_wrap_around=False) # Check if the modified longitudes are inside of the projection region for lon in lons_new: assert lon >= bm.projparams["lon_0"] - 180 assert lon <= bm.projparams["lon_0"] + 180
def basemap(dat, lat, lon, lat_min=None, lat_max=None, lon_min=None, lon_max=None, res='c', proj='mill', origin=0, shift=0, title="", loc=None, loc1=None, loc2=None, lsmask=False, ms_lat=None, ms_lon=None, lms=0.1, ms_length=None, uwinds=None, vwinds=None, hatch=None, hatch_color='none', gc_lat0=None, gc_lon0=None, gc_lat1=None, gc_lon1=None, gc_lat2=None, gc_lon2=None, gdists=None, gc_lw=.5, gc_color=plt.cm.jet, gc_contours=None, gc_extend='both', gc_cbar=False, font_size=8, asp=None, quiverscale=100, stream=None, dat2=None, dat3=None, dat4=None, dat5=None, dat6=None, area1=None, area2=None, area3=None, area4=None, area5=None, area6=None, area7=None, area8=None, area9=None, area10=None, area11=None, area12=None, area13=None, contours=None, contours2=None, contours3=None, contours4=None, contours5=None, contours6=None, lcontours=None, lcd=None, lclabel=None, clim=None, over=None, extend='neither', shaderelief=False, etopo=False, colors=None, colors2=None, colors3=None, colors4=None, colors5=None, colors6=None, color=plt.cm.gist_stern_r, colorbar=True, cbar_title="", hillshade=False, scale=.1, alpha=1, line_color1=None, line_color2=None, line_color3=None, line_color4=None, line_color5=None, line_color6=None, line_color7=None, line_color8=None, line_color9=None, line_color10=None, line_color11=None, line_color12=None, line_color13=None, line_style1='solid', line_style2='solid', line_style3='solid', line_style4='solid', line_style5='solid', line_style6='solid', line_style7='solid', line_style8='solid', line_style9='solid', line_style10='solid', line_style11='solid', line_style12='solid', line_style13='solid', parallels=np.arange(-90., 90., 20.), meridians=np.arange(0., 360., 20.), plabels=[1, 0, 0, 0], mlabels=[0, 0, 0, 1]): """plots a pcolormesh of 2-dim. dat on a geographical grid corresponding to lon and lat, optionally takes fixed colorlimits climl and climr, and saves the figure as title""" if proj == 'mill' or proj == 'cea' or proj == 'cyl': if lat_min is None: m = Basemap(projection=proj, lat_ts=12, llcrnrlon=lon.min() + shift, urcrnrlon=lon.max() + shift, llcrnrlat=lat.min(), urcrnrlat=lat.max(), resolution=res) else: m = Basemap(projection=proj, lat_ts=12, llcrnrlon=lon_min, urcrnrlon=lon_max, llcrnrlat=lat_min, urcrnrlat=lat_max, resolution=res) # m=Basemap(projection = proj, lat_ts=None,llcrnrlon=10, urcrnrlon=190, llcrnrlat=lat.min(), urcrnrlat=lat.max(),resolution = res) # m=Basemap(projection=proj, lat_0 = 0, lon_0 = shift,resolution = 'c') elif proj == 'ortho': m = Basemap(projection='ortho', lat_0=0., lon_0=0., resolution='c') elif proj == 'moll' or proj == 'hammer' or proj == 'robin': m = Basemap(projection=proj, lon_0=shift, resolution='c') elif proj == 'npstere': m = Basemap(projection=proj, lat_0=0., lon_0=0., boundinglat=40, resolution='c') # dat, lons = shiftgrid(0., dat, lon) # print lon lons, dat = m.shiftdata(lon, dat, lon_0=origin + shift) if lcd is not None: lons, lcd = m.shiftdata(lon, lcd, lon_0=origin + shift) # lons = lon # print lons if loc is not None: xloc, yloc = m(loc[0], loc[1]) m.plot(xloc, yloc, marker='D', color='r', markersize=lms) if loc1 is not None: xloc1, yloc1 = m(loc1[0], loc1[1]) m.plot(xloc1, yloc1, marker='D', color='royalblue') if loc2 is not None: xloc2, yloc2 = m(loc2[0], loc2[1]) m.plot(xloc2, yloc2, marker='D', color='darkorange') # dat, lons = addcyclic(dat, lons) if hatch is not None: lons, hatch = m.shiftdata(lon, hatch, lon_0=origin + shift) if area1 is not None: lons, area1 = m.shiftdata(lon, area1, lon_0=origin + shift) if area2 is not None: lons, area2 = m.shiftdata(lon, area2, lon_0=origin + shift) if area3 is not None: lons, area3 = m.shiftdata(lon, area3, lon_0=origin + shift) if area4 is not None: lons, area4 = m.shiftdata(lon, area4, lon_0=origin + shift) if area5 is not None: lons, area5 = m.shiftdata(lon, area5, lon_0=origin + shift) if area6 is not None: lons, area6 = m.shiftdata(lon, area6, lon_0=origin + shift) if area7 is not None: lons, area7 = m.shiftdata(lon, area7, lon_0=origin + shift) if area8 is not None: lons, area8 = m.shiftdata(lon, area8, lon_0=origin + shift) if area9 is not None: lons, area9 = m.shiftdata(lon, area9, lon_0=origin + shift) if area10 is not None: lons, area10 = m.shiftdata(lon, area10, lon_0=origin + shift) if area11 is not None: lons, area11 = m.shiftdata(lon, area11, lon_0=origin + shift) if area12 is not None: lons, area12 = m.shiftdata(lon, area12, lon_0=origin + shift) if area13 is not None: lons, area13 = m.shiftdata(lon, area13, lon_0=origin + shift) # m=Basemap(projection='mill', lat_0 = 0, lon_0 = 160, resolution = 'c') Lon, Lat = np.meshgrid(lons, lat) x, y = m(Lon, Lat) # m.drawcoastlines(linewidth = .3) if lsmask is True: m.drawlsmask(land_color='.1', ocean_color='1.', resolution='h') else: m.drawcoastlines(linewidth=.3) m.drawcountries(linewidth=.3) m.drawmapboundary() # m.readshapefile('/Users/omarlittle/Desktop/Desktop/PIK/climatenetwork/basemap/10m_physical/ne_10m_coastline', 'scale rank', drawbounds=True) # m.drawmapbound) # m.drawcountries(linewidth = .3) m.drawparallels(parallels, labels=plabels, rotation='90', linewidth=.3, fontsize=font_size, family='times new roman') m.drawmeridians(meridians, labels=mlabels, linewidth=.3, fontsize=font_size, family='times new roman') if etopo is True: m.etopo() if shaderelief is True: m.shadedrelief() if hillshade is True: m.warpimage( image= '/Users/omarlittle/Desktop/Desktop/PIK/climatenetwork/basemap/SR_50M.tif', scale=scale) if contours is None: cs = m.pcolormesh(x, y, dat, cmap=color, alpha=alpha) if clim is not None: cs.set_clim(clim) else: if colors is None: cs = m.contourf(x, y, dat, contours, alpha=alpha, cmap=color, extend=extend) else: cs = m.contourf(x, y, dat, contours, alpha=alpha, colors=colors, extend=extend) if contours2 is not None: csa = m.contourf(x, y, dat2, contours2, alpha=alpha, colors=colors2, extend=extend) if contours3 is not None: csb = m.contourf(x, y, dat3, contours3, alpha=alpha, colors=colors3, extend=extend) if contours4 is not None: csc = m.contourf(x, y, dat4, contours4, alpha=alpha, colors=colors4, extend=extend) if contours5 is not None: csd = m.contourf(x, y, dat5, contours5, alpha=alpha, colors=colors5, extend=extend) if contours6 is not None: cse = m.contourf(x, y, dat6, contours6, alpha=alpha, colors=colors6, extend=extend) if hatch is not None: # hat = m.contourf(x, y, hatch, [-2,0, 2], colors = 'none', hatches = [None, '////']) mpl.rcParams['hatch.linewidth'] = 0.1 hat = m.contourf(x, y, hatch, [-2, 0, 2], colors='none', hatches=[None, '///////']) if lcontours is not None: lc = m.contour(x, y, lcd, lcontours, colors='black', linewidths=.2) if lclabel is True: plt.clabel(lc, inline=1, fontsize=8, fmt='%d') if area1 is not None: cs1 = m.contour(x, y, area1, [0], linestyles=line_style1, linewidths=1., colors=line_color1) if area2 is not None: cs2 = m.contour(x, y, area2, [0], linestyles=line_style2, linewidths=1., colors=line_color2) if area3 is not None: cs3 = m.contour(x, y, area3, [0], linestyles=line_style3, linewidths=1., colors=line_color3) if area4 is not None: cs4 = m.contour(x, y, area4, [0], linestyles=line_style4, linewidths=1., colors=line_color4) if area5 is not None: cs5 = m.contour(x, y, area5, [0], linestyles=line_style5, linewidths=1., colors=line_color5) if area6 is not None: cs6 = m.contour(x, y, area6, [0], linestyles=line_style6, linewidths=1., colors=line_color6) if area7 is not None: cs7 = m.contour(x, y, area7, [0], linestyles=line_style7, linewidths=1., colors=line_color7) if area8 is not None: cs8 = m.contour(x, y, area8, [0], linestyles=line_style8, linewidths=1., colors=line_color8) if area9 is not None: cs9 = m.contour(x, y, area9, [0], linestyles=line_style9, linewidths=1., colors=line_color9) if area10 is not None: cs10 = m.contour(x, y, area10, [0], linestyles=line_style10, linewidths=.5, colors=line_color10) if area11 is not None: cs11 = m.contour(x, y, area11, [0], linestyles=line_style11, linewidths=.5, colors=line_color11) if area12 is not None: cs12 = m.contour(x, y, area12, [0], linestyles=line_style12, linewidths=.5, colors=line_color12) if area13 is not None: cs13 = m.contour(x, y, area13, [0], linestyles=line_style13, linewidths=.5, colors=line_color13) if stream is not None: print "be careful ..." lons, stream[0] = m.shiftdata(lon, stream[0], lon_0=origin + shift) lons, stream[1] = m.shiftdata(lon, stream[1], lon_0=origin + shift) lons, stream[2] = m.shiftdata(lon, stream[2], lon_0=origin + shift) xxs, yys = m.makegrid(stream[0].shape[1], stream[0].shape[0], returnxy=True)[2:4] st = m.streamplot(xxs, yys, stream[1], stream[2], color="w", cmap=plt.cm.spectral, arrowsize=.5, density=3, linewidth=.5) FP = FontProperties() FP.set_family('times new roman') FP.set_size('%d' % font_size) if uwinds is not None: lons, uwinds = m.shiftdata(lon, uwinds, lon_0=origin + shift) lons, vwinds = m.shiftdata(lon, vwinds, lon_0=origin + shift) u = uwinds v = vwinds #ugrid,newlons = shiftgrid(180.,u,lon,start=False) #vgrid,newlons = shiftgrid(180.,v,lon,start=False) # transform vectors to projection grid. #uproj,vproj,xx,yy = m.transform_vector(ugrid,vgrid,newlons,lat,31,31,returnxy=True,masked=True) # now plot. # scale = Q = m.quiver(x[::asp, ::asp], y[::asp, ::asp], u[::asp, ::asp], v[::asp, ::asp], pivot='mid', units='width', scale=quiverscale) # make quiver key # qk = plt.quiverkey(Q, 0.85, 0.05, 5, '5 m/s', coordinates = 'figure', labelpos='W', labelcolor = 'black', fontproperties = {'family':'times new roman', 'size':'10', 'style':'normal'}) if gc_lat0 is not None: for i in xrange(gc_lat1.shape[0]): if gc_color is None: gc = m.drawgreatcircle(gc_lon0, gc_lat0, gc_lon1[i], gc_lat1[i], linewidth=gc_lw, color=plt.cm.jet(.0001), alpha=.02) else: gc = m.drawgreatcircle( gc_lon0, gc_lat0, gc_lon1[i], gc_lat1[i], linewidth=gc_lw, color=gc_color(int(5 * gdists[i] / gdists.max()) / 5., alpha=.02 + gdists[i] / gdists.max())) if gc_lat2 is not None: for i in xrange(gc_lat2.shape[0]): gc = m.drawgreatcircle(gc_lon0, gc_lat0, gc_lon2[i], gc_lat2[i], linewidth=gc_lw, color=plt.cm.jet(.9999), alpha=.3) if loc is not None: xloc, yloc = m(loc[0], loc[1]) m.plot(xloc, yloc, marker='D', color='r', markersize=0.5) if ms_lat is not None: m.drawmapscale(lat=ms_lat, lon=ms_lon, lon0=0., lat0=0., length=ms_length, barstyle='fancy') if colorbar is True: ticks_font = matplotlib.font_manager.FontProperties( family='times new roman', style='normal', size=font_size, weight='normal', stretch='normal') if gc_cbar == True: cs_fake = plt.contourf(x, y, np.ones_like(dat) * -1e7, gc_contours, cmap=gc_color, extend='neither') cbar = m.colorbar(cs_fake, extend=extend, orientation='horizontal') else: cbar = m.colorbar(cs, extend=extend) if cbar_title is not None: cbar.ax.set_ylabel(cbar_title, fontsize=font_size, family='times new roman') for label in cbar.ax.get_yticklabels(): label.set_fontproperties(ticks_font) if over is not None: cs.cmap.set_over(over) plt.title('%s' % title, fontsize=font_size) return cs
def main(): erainterim_075_folder = "/HOME/data/Validation/ERA-Interim_0.75/Offline_driving_data/3h_Forecast" vname = "PR" start_year = 1980 end_year = 2010 season_key = "summer" season_labels = {season_key: "Summer"} season_to_months = OrderedDict([ (season_key, [6, 7, 8]) ]) # Validate temperature and precip model_vars = ["TT", "PR"] obs_vars = ["tmp", "pre"] obs_paths = [ "/HOME/data/Validation/CRU_TS_3.1/Original_files_gzipped/cru_ts_3_10.1901.2009.tmp.dat.nc", "/HOME/data/Validation/CRU_TS_3.1/Original_files_gzipped/cru_ts_3_10.1901.2009.pre.dat.nc" ] model_var_to_obs_var = dict(zip(model_vars, obs_vars)) model_var_to_obs_path = dict(zip(model_vars, obs_paths)) obs_path = model_var_to_obs_path[vname] cru = CRUDataManager(var_name=model_var_to_obs_var[vname], path=obs_path) # Calculate seasonal means for CRU seasonal_clim_fields_cru = cru.get_seasonal_means(season_name_to_months=season_to_months, start_year=start_year, end_year=end_year) # Calculate seasonal mean for erai flist = get_files_for_season(erainterim_075_folder, start_year=start_year, end_year=end_year, months=season_to_months[season_key]) rpf = MultiRPN(flist) date_to_field_erai075 = rpf.get_all_time_records_for_name_and_level(varname=vname, level=-1) # Convert to mm/day era075 = np.mean([field for field in date_to_field_erai075.values()], axis=0) * 24 * 3600 * 1000 lons_era, lats_era = rpf.get_longitudes_and_latitudes_of_the_last_read_rec() seasonal_clim_fields_cru_interp = OrderedDict() # Calculate biases for season, cru_field in seasonal_clim_fields_cru.items(): seasonal_clim_fields_cru_interp[season] = cru.interpolate_data_to(cru_field, lons2d=lons_era, lats2d=lats_era, nneighbours=1) # Do the plotting ------------------------------------------------------------------------------ plot_utils.apply_plot_params() fig = plt.figure() b = Basemap() gs = gridspec.GridSpec(nrows=3, ncols=1) ax = fig.add_subplot(gs[0, 0]) xx, yy = b(cru.lons2d, cru.lats2d) cs = b.contourf(xx, yy, seasonal_clim_fields_cru[season_key], 20) b.drawcoastlines(ax=ax) ax.set_title("CRU") plt.colorbar(cs, ax=ax) ax = fig.add_subplot(gs[1, 0]) lons_era[lons_era > 180] -= 360 lons_era, era075 = b.shiftdata(lons_era, datain=era075, lon_0=0) xx, yy = b(lons_era, lats_era) # mask oceans in the era plot as well era075 = maskoceans(lons_era, lats_era, era075) cs = b.contourf(xx, yy, era075, levels=cs.levels, norm=cs.norm, cmap=cs.cmap, ax=ax) b.drawcoastlines(ax=ax) ax.set_title("ERA-Interim 0.75") plt.colorbar(cs, ax=ax) # differences ax = fig.add_subplot(gs[2, 0]) diff = era075 - seasonal_clim_fields_cru_interp[season_key] delta = np.percentile(np.abs(diff)[~diff.mask], 90) clevs = np.linspace(-delta, delta, 20) cs = b.contourf(xx, yy, diff, levels=clevs, cmap="RdBu_r", extend="both") b.drawcoastlines(ax=ax) ax.set_title("ERA-Interim 0.75 - CRU") plt.colorbar(cs, ax=ax) plt.show() fig.savefig(os.path.join(img_folder, "erai0.75_vs_cru_precip.png"), bbox_inches="tight")
d_u = g_u.mean(axis=0) - w_u.mean(axis=0) for lev in range(0, 44): lev_1 = lev + 1 g_uu = g_u[lev, :, :] w_uu = w_u[lev, :, :] d_uu = g_uu - w_uu ############################################################################################################################################ fig = plt.figure(figsize=(8, 8), dpi=100) ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) m = Basemap(projection='mill', llcrnrlat=lat.min(), urcrnrlat=lat.max(), llcrnrlon=lon.min(), urcrnrlon=lon.max(), resolution='l') lons, data = m.shiftdata(lon, datain=g_uu, lon_0=None) x, y = m(lon, lat) nice_cmap = plt.get_cmap('ocean_r') nice_cmap = plt.get_cmap('RdYlGn') #nice_cmap= plt.get_cmap(mymap) #clevs=[-15,-10,-5,-0,5,10,15,20,25,30,35,40,45,50,55,60,70] clevs = [ -9, -6, -3, -0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51 ] #cs = (m.contourf(x,y,data,leves=clevs,cmap=cmap,norm=norml,extend='both')) cs = (m.contourf(x, y, data, clevs, cmap=nice_cmap, extended='both')) (m.readshapefile('/home/Data/shapeFiles/uae/ARE_adm1', 'uae',
f = nf.Dataset(files, mode='r') lat = (np.squeeze(f.variables['XLAT'][:])) lat1 = np.vstack(lat[:, 0]) lon = (np.squeeze(f.variables['XLONG'][:])) lon1 = np.vstack(lon[0, :]) temp = np.squeeze(f.variables['T2'][:]) - 273.15 fig = plt.figure(figsize=(8, 8), dpi=100) ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) m = Basemap(projection='mill', llcrnrlat=lat.min(), urcrnrlat=lat.max(), llcrnrlon=lon.min(), urcrnrlon=lon.max(), resolution='l') lons, data = m.shiftdata(lon, datain=temp, lon_0=None) x, y = m(lon, lat) #Z=maskoceans(lons,lat,data,inlands=True, resolution='c', grid=2.5) clevs = [1, 5, 10, 15, 18, 21, 22, 23, 24, 25, 26, 27, 28] mymap = mcolors.ListedColormap(['white','lime','limegreen','greenyellow','yellow','gold','orange','indianred','firebrick', \ 'darkred','lightskyblue','deepskyblue','royalblue','blue']) # colors1 = plt.get_cmap('ocean_r') ; colors1=colors1(np.linspace(0., 1, 128)) # colors2 = plt.get_cmap('RdYlGn') ; colors2=colors2(np.linspace(0.,1 , 128)) # colors = np.vstack(( colors1,colors2)) # mymap = mcolors.LinearSegmentedColormap.from_list('my_colormap', colors) nice_cmap = plt.get_cmap(mymap) colors = nice_cmap([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]) cmap, norm = from_levels_and_colors(clevs, colors, extend='both') # #cs=m.pcolormesh(x,y,data, cmap=cmap, norm=norm)
def map_nwp_tracks_per_storm(date, outfile): #lat1 = -2 #lat2 = -40 #lon1=0 #lon2=60 #lat1 = 0 #lat2 = -30 #lon1=20 #lon2=60 lat1 = -10 lat2 = -30 lon1 = 18 lon2 = 55 fig = plt.figure(figsize=(6, 3)) ax = fig.add_axes([0.05, 0.1, 0.9, 0.96]) m = Basemap(llcrnrlon=lon1, llcrnrlat=lat2, urcrnrlon=lon2, urcrnrlat=lat1, projection='mill', resolution='l') RSMClats = [-40, 0, 0, -40] RSMClons = [30, 30, 90, 90] m.drawcoastlines(linewidth=0.5, color='k') #darkgray m.drawcountries(linewidth=0.5, color='k') #darkgray m.fillcontinents(color='silver', alpha=0.25) hurricane = get_hurricane_symbol() eps_data = np.genfromtxt(datadir + date + "_idai_ECMWF_eps_3way_matched_reformatted.txt", dtype=float, skip_header=1, usecols=np.arange(0, 11)) #tid = track id (column 1) in the eps reformatted files #1 = analysis track, 2 = best track, 3 = control, 4 - 53 = ensemble members 1-50 #total length of the file, to loop over and find the individual tracks #probably a better way to do this, but it's friday e = range(4, 54) e.append(3) e.append(2) e.append(1) NP = len(eps_data[:, 0]) print e for tid in e: if tid == 1: c = 'k' ls = '-' lw = 0.7 elif tid == 2: c = 'None' ls = '--' lw = 0.75 elif tid == 3: c = 'None' #'#FF9F1C' ls = '-' lw = 0.75 elif tid >= 4: c = 'lightblue' ls = '-' lw = 0.5 else: print "something went wrong with the tid" #tid = str(tid).zfill(4) #print float(tid) xyi = [] for i in range(NP): #print eps_data[i,0] if eps_data[i, 0] == float(tid): xyi.append(i) #print xyi xs = [] ys = [] for i in xyi: xs.append(eps_data[i, 7]) ys.append(eps_data[i, 8]) if tid == 1: no_points = len(xs) points = np.array([xs, ys]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) #colors = cm.twilight(np.linspace(0.5,1,no_points)) cmap = LinearSegmentedColormap.from_list( 'mycmap', ['lightgrey', 'black', 'dimgrey']) #cmap = LinearSegmentedColormap.from_list('mycmap',['plum','darkmagenta','plum']) colors = cmap(np.linspace(0, 1, no_points)) for p, cl in zip(range(no_points - 1), colors): #put these here so as to not plot the analysis track before the forecast date, just from the fcst date onwards xarr = [] yarr = [] if p < 61: #61 is when it's no longer a TC, 37 is when it became a TC (10th March), I think z = 10 elif p > 61: # z = 9 if p > 37: xarr.append( segments[p][0][0] ) #shift these back an indent if plotting the *whole* analysis track xarr.append(segments[p][1][0]) yarr.append(segments[p][0][1]) yarr.append(segments[p][1][1]) x, y = m(xarr, yarr) m.plot(x, y, linewidth=1.5, color=cl, zorder=z) #zorder=z pp = np.linspace(0, 92, 24) #colors2=cm.twilight(np.linspace(0.5,1,24)) colors2 = cmap(np.linspace(0, 1, 24)) print pp for p, cl in zip(pp, colors2): p = int(p) if p < 61: z = 10 elif p > 61: z = 9 if p < 37: xx, yy = m(xs[p], ys[p]) #m.scatter(xx,yy,marker='o', edgecolors=cl,facecolors=cl, s=8,linewidth=1,zorder=z) elif 37 < p < 61: xx, yy = m(xs[p], ys[p]) m.scatter(xx, yy, marker=hurricane, edgecolors=cl, facecolors='None', s=100, linewidth=1.25, zorder=z) elif p > 61: xx, yy = m(xs[p], ys[p]) m.scatter(xx, yy, marker='o', edgecolors=cl, facecolors='None', s=8, linewidth=1, zorder=z) #xx,yy=m(xs[0],ys[0]) #m.scatter(xx,yy,marker=hurricane, edgecolors=c, facecolors='None',s=25,linewidth=0.6,zorder=10) else: #continue x, y = m.shiftdata(xs, ys) #if tid == 3.: #print xs #print ys #print x,y m.plot(x, y, linewidth=lw, color=c, linestyle=ls, latlon=True) #if tid == 1.: #xx,yy=m(xs[0],ys[0]) #m.scatter(xx,yy,marker=hurricane, edgecolors=c, facecolors='None',s=25,linewidth=0.6,zorder=10) #if tid == 3: #xx,yy=m(xs[0],ys[0]) #m.scatter(xx,yy,marker=hurricane, edgecolors=c, facecolors='None',s=25,linewidth=0.6,zorder=10) mean_file = datadir + date + "_idai_ECMWF_mean_3way_matched_reformatted.txt" if os.path.isfile(mean_file): mean_data = np.genfromtxt(mean_file, dtype=float, skip_header=1, usecols=np.arange(0, 11)) x, y = m.shiftdata(mean_data[:, 7], mean_data[:, 8]) m.plot(x, y, linewidth=0.75, color='mediumblue', latlon=True, linestyle='-', zorder=9) #xx,yy=m(mean_data[0,7],mean_data[0,8]) #m.scatter(xx,yy,marker=hurricane, edgecolors='darkturquoise', facecolors='None',s=25,linewidth=0.6,zorder=10) det_file = datadir + date + "_idai_ECMWF_det_3way_matched_reformatted.txt" if os.path.isfile(det_file): det_data = np.genfromtxt(det_file, dtype=float, skip_header=1, usecols=np.arange(0, 11)) NP = len(det_data[:, 0]) #tid = str(3).zfill(4) tid = 3 xyi = [] for i in range(NP): if det_data[i, 0] == float(tid): xyi.append(i) xs = [] ys = [] for i in xyi: xs.append(det_data[i, 7]) ys.append(det_data[i, 8]) x, y = m.shiftdata(xs, ys) m.plot(x, y, linewidth=0.75, color='#F71735', latlon=True, linestyle='-', zorder=9) #if len(xs)>0: #xx,yy=m(xs[0],ys[0]) #m.scatter(xx,yy,marker=hurricane, edgecolors='#F71735', facecolors='None',s=25,linewidth=0.6,zorder=10) #else: #continue title = "Cyclone Idai ECMWF Forecast\n" + str(date) ib = plt.Line2D((0, 1), (0, 0), color='k', linestyle='--', linewidth=0.5) an = plt.Line2D((0, 1), (0, 0), color='k', linestyle='-', linewidth=0.5) det = plt.Line2D((0, 1), (0, 0), color='#F71735', linewidth=0.5) ctrl = plt.Line2D((0, 1), (0, 0), color='#FF9F1C', linewidth=0.5) mean = plt.Line2D((0, 1), (0, 0), color='medium', linewidth=0.5) eps = plt.Line2D((0, 1), (0, 0), color='lightblue', linewidth=0.5, linestyle=':') #legend = ax.legend((an, det, ctrl, mean, eps), ['Analysis Track', 'Deterministic', 'Control', 'Ensemble Mean', 'Ensembles'],title=title, fontsize=5, loc='lower left') #plt.setp(legend.get_title(), fontsize='5') #legend._legend_box.align = "left" #save and close the plot fig.subplots_adjust(wspace=0) plt.savefig(outfile, bbox_inches='tight', pad_inches=0.05, dpi=500) plt.close()
from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt import numpy as np map = Basemap(projection='sinu', lat_0=0, lon_0=0) lons = np.arange(30, 390, 30) lats = np.arange(0, 100, 10) data = np.indices((lats.shape[0], lons.shape[0])) data = data[0] + data[1] print data print lons lons, data = map.shiftdata(lons, datain = data, lon_0=0) print lons llons, llats = np.meshgrid(lons, lats) x, y = map(llons, llats) map.contourf(x, y, data) map.drawcoastlines() plt.show()
gsi_f=nf.Dataset(gsi_file, mode='r') lat=(np.squeeze(gsi_f.variables['XLAT'][:])) ; lat1=np.vstack(lat[:,0]) ; lon=(np.squeeze(gsi_f.variables['XLONG'][:])) ; lon1=np.vstack(lon[0,:]) wrf_f=nf.Dataset(wrf_file, mode='r') g_qv=np.squeeze(gsi_f.variables['QVAPOR'][:]) ; w_qv=np.squeeze(wrf_f.variables['QVAPOR'][:]) ; d_qv=g_qv.mean(axis=0)-w_qv.mean(axis=0) for lev in range(0,44): lev_1=lev+1 g_qvv=g_qv[lev,:,:] ; w_qvv=w_qv[lev,:,:] ; d_qvv=g_qvv-w_qvv ; ############################################################################################################################################ fig=plt.figure(figsize=(8,8),dpi=100); ax = fig.add_axes([0.1,0.1,0.8,0.8]) ; m = Basemap(projection='mill',llcrnrlat=lat.min(),urcrnrlat=lat.max(),llcrnrlon=lon.min(),urcrnrlon=lon.max(),resolution='l') lons, data = m.shiftdata(lon, datain=g_qvv, lon_0=None) x, y=m(lon,lat) nice_cmap=plt.get_cmap('ocean_r') nice_cmap=plt.get_cmap('RdYlGn') #nice_cmap= plt.get_cmap(mymap) clevs=[0.0, 0.001,0.0015,0.0020,0.0025,0.0030,0.0035,0.0040,0.0045,0.0050,0.0055,0.0060, \ 0.0065,0.0070,0.0075,0.0080, 0.0085, 0.0090, 0.0095, 0.010, 0.0105,0.0110,0.0115,0.0120,0.0125] clevs=[0.0, 0.001,0.0020,0.0030,0.0040,0.0050,0.0060,0.0070,0.0080,0.0090,0.010,0.0110,0.0120,0.0130] #cs = (m.contourf(x,y,data,leves=clevs,cmap=cmap,norm=norml,extend='both')) cs = (m.contourf(x,y,data,clevs,cmap=nice_cmap,extended='both')) (m.readshapefile('/home/Data/shapeFiles/uae/ARE_adm1','uae',drawbounds=True, zorder=None, linewidth=1.0, color='k', antialiased=1, ax=None, default_encoding='utf-8')) m.drawparallels(np.arange(20.,30.,5.), labels=[1,0,0,0])
def main(): erainterim_075_folder = "/HOME/data/Validation/ERA-Interim_0.75/Offline_driving_data/3h_Forecast" vname = "PR" start_year = 1980 end_year = 2010 season_key = "summer" season_labels = {season_key: "Summer"} season_to_months = OrderedDict([(season_key, [6, 7, 8])]) # Validate temperature and precip model_vars = ["TT", "PR"] obs_vars = ["tmp", "pre"] obs_paths = [ "/HOME/data/Validation/CRU_TS_3.1/Original_files_gzipped/cru_ts_3_10.1901.2009.tmp.dat.nc", "/HOME/data/Validation/CRU_TS_3.1/Original_files_gzipped/cru_ts_3_10.1901.2009.pre.dat.nc", ] model_var_to_obs_var = dict(zip(model_vars, obs_vars)) model_var_to_obs_path = dict(zip(model_vars, obs_paths)) obs_path = model_var_to_obs_path[vname] cru = CRUDataManager(var_name=model_var_to_obs_var[vname], path=obs_path) # Calculate seasonal means for CRU seasonal_clim_fields_cru = cru.get_seasonal_means( season_name_to_months=season_to_months, start_year=start_year, end_year=end_year ) # Calculate seasonal mean for erai flist = get_files_for_season( erainterim_075_folder, start_year=start_year, end_year=end_year, months=season_to_months[season_key] ) rpf = MultiRPN(flist) date_to_field_erai075 = rpf.get_all_time_records_for_name_and_level(varname=vname, level=-1) # Convert to mm/day era075 = np.mean([field for field in date_to_field_erai075.values()], axis=0) * 24 * 3600 * 1000 lons_era, lats_era = rpf.get_longitudes_and_latitudes_of_the_last_read_rec() seasonal_clim_fields_cru_interp = OrderedDict() # Calculate biases for season, cru_field in seasonal_clim_fields_cru.items(): seasonal_clim_fields_cru_interp[season] = cru.interpolate_data_to( cru_field, lons2d=lons_era, lats2d=lats_era, nneighbours=1 ) # Do the plotting ------------------------------------------------------------------------------ plot_utils.apply_plot_params() fig = plt.figure() b = Basemap() gs = gridspec.GridSpec(nrows=3, ncols=1) ax = fig.add_subplot(gs[0, 0]) xx, yy = b(cru.lons2d, cru.lats2d) cs = b.contourf(xx, yy, seasonal_clim_fields_cru[season_key], 20) b.drawcoastlines(ax=ax) ax.set_title("CRU") plt.colorbar(cs, ax=ax) ax = fig.add_subplot(gs[1, 0]) lons_era[lons_era > 180] -= 360 lons_era, era075 = b.shiftdata(lons_era, datain=era075, lon_0=0) xx, yy = b(lons_era, lats_era) # mask oceans in the era plot as well era075 = maskoceans(lons_era, lats_era, era075) cs = b.contourf(xx, yy, era075, levels=cs.levels, norm=cs.norm, cmap=cs.cmap, ax=ax) b.drawcoastlines(ax=ax) ax.set_title("ERA-Interim 0.75") plt.colorbar(cs, ax=ax) # differences ax = fig.add_subplot(gs[2, 0]) diff = era075 - seasonal_clim_fields_cru_interp[season_key] delta = np.percentile(np.abs(diff)[~diff.mask], 90) clevs = np.linspace(-delta, delta, 20) cs = b.contourf(xx, yy, diff, levels=clevs, cmap="RdBu_r", extend="both") b.drawcoastlines(ax=ax) ax.set_title("ERA-Interim 0.75 - CRU") plt.colorbar(cs, ax=ax) plt.show() fig.savefig(os.path.join(img_folder, "erai0.75_vs_cru_precip.png"), bbox_inches="tight")
def imshow_Pakistan_hatch(data, lons_sig_arr, lats_sig_arr, vmin=None, vmax=None, norm=None, cmap=None, ticks=None, title=None, fig_name=None): fig = plt.figure() M = Basemap(resolution='l', llcrnrlat=minlat, urcrnrlat=maxlat, llcrnrlon=minlon, urcrnrlon=maxlon) M.fillcontinents(color='#D6D5D5') M.drawmapboundary(fill_color='#80cdc1') M.drawcountries(color='white', linewidth=1.25) lons_map, lats_map = M(lon - 0.25, lat + 0.25) cs = M.pcolormesh(lons_map, lats_map, data[::-1], vmin=vmin, vmax=vmax, norm=norm, cmap=cmap, zorder=4) lons_sig_arr, lats_sig_arr = M.shiftdata(lons_sig_arr, lats_sig_arr) M.scatter(lons_sig_arr, lats_sig_arr, marker='.', s=50, color='coral', latlon=True, zorder=6) M.scatter(67.3695, 24.7854, marker='*', s=200, color='#343837', zorder=5) # Location of powerplant A M.scatter(70.1736, 24.4338, marker='*', s=200, color='#343837', zorder=5) # Location of powerplant B M.scatter(70.3151, 24.8408, marker='*', s=200, color='#343837', zorder=5) # Location of powerplant C M.scatter(70.3151, 24.8408, marker='*', s=200, color='#343837', zorder=5) # Location of powerplant D M.scatter(73.2359, 30.7196, marker='*', s=200, color='#343837', zorder=5) # Location of powerplant E M.scatter(70.1790, 24.6970, marker='*', s=200, color='#343837', zorder=5) # Location of powerplant F M.scatter(66.6944, 24.9057, marker='*', s=200, color='#343837', zorder=5) # Location of powerplant G M.plot(lonlat[:, 0], lonlat[:, 1], lw=1.25, color='k', alpha=0.7, zorder=7) M.drawcoastlines() cbar = M.colorbar(cs, ticks=ticks, location='right', pad="5%", size="3%", extend='both') fig.text(0.14, 0.32, 'Iran', size=18, va="baseline", ha="left", fontweight='medium', color='grey', fontstyle='italic') fig.text(0.2, 0.6, 'Afghanistan', size=18, va="baseline", ha="left", fontweight='medium', color='grey', fontstyle='italic') fig.text(0.6, 0.3, 'India', size=18, va="baseline", ha="left", fontweight='medium', color='grey', fontstyle='italic') fig.text(0.15, 0.15, 'Arabian Sea', size=12, va="baseline", ha="left", fontweight='medium', color='white', fontstyle='italic') fig.text(0.13, 0.8, model.upper(), size=22, va="baseline", ha="left", fontweight='medium', color='#343837') #plt.title(title) plt.savefig('%s/%s_%s.pdf' % (dir_fig, fig_name, model)) plt.show()
fig, ax = plt.subplots(1, 1, figsize=(10, 8)) print(np.nanmin(lon)) map = Basemap(ax=ax, llcrnrlon=np.nanmin(lon) + 1, urcrnrlon=np.nanmax(lon) - 1, llcrnrlat=np.nanmin(lat) + 1, urcrnrlat=np.nanmax(lat) - 1, projection="cyl", fix_aspect=False, resolution='l') map.fillcontinents(color="black", lake_color="black") map.drawparallels(np.arange(-90, 90, 20), labels=[1, 0, 0, 0]) map.drawmeridians(np.arange(-180, 180, 20), labels=[1, 0, 0, 1]) LON, LAT = map.shiftdata(lon, lat) map.plot(LON, LAT, latlon=True) u = floats.u.to_masked_array() v = floats.v.to_masked_array() U = np.sqrt(u**2 + v**2) xbins = np.arange(-80, 0, 0.5) ybins = np.arange(15, 65, 0.5) H = stats.binned_statistic_2d(lon, lat, None, bins=[xbins, ybins], statistic="count") M = stats.binned_statistic_2d(lon,
# convert the sliced data to a pandas dataframe df = hur_lev.to_dataframe() # this is a simple way to rotate the coordinates of longitudes from 0-360 to -180-180 new_lons = ((ds.lon.data + 180) % 360) - 180 lons_greenwich = ((lons_pacific + 180) % 360) - 180 # see also: # basemap shiftdata from mpl_toolkits.basemap import Basemap, addcyclic, shiftgrid m = Basemap( epsg=4326 ) new_arr = np.rollaxis( hur_lev.values.T, -1 ) test = m.shiftdata( xds.lon.data, hur_lev.values[1,...][:].T, lon_0=0.0 ) llons, llats = np.meshgrid( test[0], ds.lat.data ) x, y = m(llons, llats) # m.contourf(x, y, test[1]) # m.drawcoastlines() m.imshow( test[1] ) plt.savefig('test.png') scp [email protected]:/home/malindgren/Documents/hur/test.png ~/Documents # from frank gdalwarp -multi -overwrite -of NetCDF -t_srs WGS84 hur_Amon_GFDL-CM3_historical_r1i1p1_186001-186412.nc test.nc -wo SOURCE_EXTRA=1000 -wo NUM_THREADS=ALL_CPUS --config CENTER_LONG 0 # test file
d_t = g_t.mean(axis=0) - w_t.mean(axis=0) for lev in range(0, 44): lev_1 = lev + 1 g_tt = g_t[lev, :, :] w_tt = w_t[lev, :, :] d_tt = g_tt - w_tt ############################################################################################################################################ fig = plt.figure(figsize=(8, 8), dpi=100) ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) m = Basemap(projection='mill', llcrnrlat=lat.min(), urcrnrlat=lat.max(), llcrnrlon=lon.min(), urcrnrlon=lon.max(), resolution='l') lons, data = m.shiftdata(lon, datain=g_tt, lon_0=None) x, y = m(lon, lat) nice_cmap = plt.get_cmap('ocean_r') nice_cmap = plt.get_cmap('RdYlGn') #nice_cmap= plt.get_cmap(mymap) clevs = [ -25, -20, -15, -10, -5, 0, 5, 10, 25, 50, 75, 100, 125, 150, 175, 200, 225 ] #cs = (m.contourf(x,y,data,leves=clevs,cmap=cmap,norm=norml,extend='both')) cs = (m.contourf(x, y, data, clevs, cmap=nice_cmap, extended='both')) (m.readshapefile('/home/Data/shapeFiles/uae/ARE_adm1', 'uae', drawbounds=True,
from mpl_toolkits.basemap import Basemap from mpl_toolkits.basemap import addcyclic import matplotlib.pyplot as plt import numpy as np map = Basemap(projection='sinu', lat_0=0, lon_0=0) lons = np.arange(30, 390, 30) lats = np.arange(0, 100, 10) data = np.indices((lats.shape[0], lons.shape[0])) data = data[0] + data[1] data, lons = addcyclic(data, lons) lons, data = map.shiftdata(lons, datain=data, lon_0=0) llons, llats = np.meshgrid(lons, lats) x, y = map(llons, llats) map.contourf(x, y, data) map.drawcoastlines() plt.show()
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) lat0 = 5 lon0 = 60 #m = Basemap(projection='ortho',lat_0=lat0,lon_0=lon0, resolution='c',area_thresh = 1000.) m = Basemap(projection='mill', llcrnrlat=-90, urcrnrlat=90, llcrnrlon=-180, urcrnrlon=180, resolution='l') m = Basemap(projection='kav7', lon_0=0, resolution=None) #m = Basemap(projection='ortho',lon_0=lon0,lat_0=lat0,resolution='l', \ # llcrnrx=0.,llcrnry=0.,urcrnrx=m1.urcrnrx/3,urcrnry=m1.urcrnry/3) lons, data = m.shiftdata(lon, datain=temp[0, :, :], lon_0=None) x, y = m(lons, lat) Z = maskoceans(lons, lat, data, inlands=True, resolution='c', grid=2.5) clevs = [-50, -40, -20, -10, 0, 5, 10, 15, 20, 25, 30, 35, 40, 45] cmap = plt.get_cmap('gist_rainbow') #nice_cmap= plt.get_cmap('ocean_r') #colors = nice_cmap([0,8, 16, 40, 60, 80,100,120,140]) #colors = nice_cmap([0,10,20,40,60,80,100,130,160]) #levels = [0, 5, 10, 15, 25,30,35,40] ; #cmap, norm = from_levels_and_colors(levels, colors, extend='both') #cs=m.pcolormesh(x,y,Z, cmap=cmap, norm=norm) cs = (m.contourf(x, y, Z, clevs, cmap=plt.cm.jet)) #m.warpimage(image='venuscyl4.jpg') #(m.readshapefile('ncfiles/subdiv/India_subdiv','ind',drawbounds=True, zorder=None, linewidth=1.0, color='k', antialiased=1, ax=None, default_encoding='utf-8'))
d_vv = g_vv - w_vv g_uu = g_u[lev, :, :] w_uu = w_u[lev, :, :] d_uu = g_uu - w_uu ############################################################################################################################## fig = plt.figure(figsize=(8, 8), dpi=100) ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) m = Basemap(projection='mill', llcrnrlat=lat.min(), urcrnrlat=lat.max(), llcrnrlon=lon.min(), urcrnrlon=lon.max(), resolution='l') lons, data = m.shiftdata(lon, datain=g_wss, lon_0=None) x, y = m(lons, lat) nice_cmap = plt.get_cmap('ocean_r') nice_cmap = plt.get_cmap('RdYlGn') #nice_cmap= plt.get_cmap(mymap) #clevs=[-15,-10,-5,-0,5,10,15,20,25,30,35,40,45,50,55,60,70] clevs = [-9, -6, -3, -0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39] skip = (slice(None, None, 5), slice(None, None, 5)) # #cs = (m.contourf(x,y,data,leves=clevs,cmap=cmap,norm=norml,extend='both')) # kw = dict( color='black', alpha=0.75) # m.quiver(x,y,g_uu,g_vv,width=0.0003, scale=500) # plt.show() cs = (m.contourf(x, y, data, clevs, cmap=nice_cmap, extended='both'))