Beispiel #1
0
def w_0():
	wind_files = sorted(glob.glob("../data/binary_w/*.ads60"))
	lon = latlon_ex.Lon
	lat = latlon_ex.Lat
	lon = np.array(lon)
	lat = np.array(lat)

	dirs = "../result/test_wind/"
	try:
		os.makedirs(dirs)
	except:
		print('directory {} already exists'.format(dirs))

	for item in tqdm(wind_files):
		dt = np.dtype([("u","<f"), ("v","<f"), ("slp","<f")])
		fd = open(item, "r")
		result = np.fromfile(fd, dtype=dt, count=-1)
		data = result.tolist()
		data1 = np.array([list(data[i]) for i in range(len(data))])

		w_u = data1[:,0]
		w_v = data1[:,1]
		w_speed = np.sqrt(w_u**2+w_v**2)

		m = Basemap(lon_0=180, boundinglat=50, resolution='l', projection='npstere')
		fig = plt.figure(figsize=(7, 7))
		x, y = m(lon, lat)

		m.drawcoastlines(color = '0.15')
		m.quiver(x, y, w_u, w_v, w_speed)

		save_name = dirs + item[17:26] + ".png"

		plt.savefig(save_name, dpi=450)
		plt.close()
Beispiel #2
0
def vec_plot_south_america(lons, lats, sa_mask, data_x, data_y, ax=None):
    if ax == None:
	ax = plt.gca()
    #print(sa_mask.shape)
    #print(data_x.shape)
    #print(data_y.shape)
    #data_x_masked = np.ma.array(data_x, mask=sa_mask)
    #data_y_masked = np.ma.array(data_y, mask=sa_mask)
    plot_lons, plot_x_data = extend_data(lons, lats, data_x)
    plot_lons, plot_y_data = extend_data(lons, lats, data_y)

    lons, lats = np.meshgrid(plot_lons, lats)

    m = Basemap(ax=ax, projection='cyl', resolution='c', llcrnrlat=-60, urcrnrlat=15, llcrnrlon=-85, urcrnrlon=-32)
    x, y = m(lons, lats)

    mag = np.sqrt(plot_x_data**2 + plot_y_data**2)
    vmin, vmax = mag.min(), mag.max()
    m.contourf(x[:-1,:], y[:-1,:], mag, ax=ax)
    #m.pcolormesh(x, y, mag, vmin=vmin, vmax=vmax, ax=ax)
    m.quiver(x, y, plot_x_data, plot_y_data, scale=40, ax=ax)

    m.drawcoastlines(ax=ax)
    m.drawparallels(np.arange(-60.,15.,10.), labels=[1, 0, 0, 0], fontsize=10, ax=ax)
    m.drawmeridians(np.arange(-90.,-30.,10.), labels=[0, 0, 0, 1], fontsize=10, ax=ax)

    m.colorbar(location='right', pad='5%', ax=ax)
    plt.show()
Beispiel #3
0
def visual_wind(wind_file_name, latlon145_file_name, points, show=True):
    """
	地溝風の可視化
	"""
    w_u1, w_v1, w_speed1 = read_wind(wind_file_name, reshape=True)
    lon, lat = read_lonlat(latlon145_file_name)

    m = Basemap(lon_0=180,
                boundinglat=50,
                resolution='l',
                projection='npstere')
    fig = plt.figure(figsize=(6, 6))

    x, y = m(lon, lat)
    x = np.reshape(x, (145, 145), order='F')
    y = np.reshape(y, (145, 145), order='F')

    m.drawcoastlines(color='0.15')

    #風の描画
    m.quiver(x[points], y[points], w_u1[points], w_v1[points],
             w_speed1[points])

    if show == True:
        plt.show()
Beispiel #4
0
def plot_map_multi(data_wind, data_non_wind, **kwargs):
    show = kwargs["show"]
    save_name = kwargs["save_name"]
    vmax = kwargs["vmax"]

    m = Basemap(lon_0=180,
                boundinglat=50,
                resolution='i',
                projection='npstere')
    fig = plt.figure(figsize=(6.5, 6.5))
    m.drawcoastlines(color='0.15')

    x, y = m(lon, lat)
    x1 = np.reshape(x, (145, 145), order='F')
    y1 = np.reshape(y, (145, 145), order='F')

    data_wind = np.array(data_wind)
    vector_u = np.ma.masked_invalid(data_wind[:, 0])
    vector_v = np.ma.masked_invalid(data_wind[:, 1])
    vector_speed = np.ma.masked_invalid(data_wind[:, 2])

    data_non_wind = np.array(data_non_wind)
    data_non_wind = np.ma.masked_invalid(data_non_wind)
    data1 = np.reshape(data_non_wind, (145, 145), order='F')

    m.quiver(x, y, vector_u, vector_v, vector_speed)
    #m.quiver(x, y, vector_u, vector_v, vector_speed, angles='xy', scale_units='xy')
    m.pcolormesh(x1, y1, data1, cmap=plt.cm.jet, vmax=vmax)
    m.colorbar(location='bottom')
Beispiel #5
0
    def plotQuiver(self, proj='mill', res='i', instant=0, Dline=5, density=1):
        """
        to plot whole earth params should be close to res='c',Dline=100,density=10
        """
        # Plot the field using Basemap.  Start with setting the map
        # projection using the limits of the lat/lon data itself:
        plt.figure()


        m=Basemap(projection=proj,lat_ts=10,llcrnrlon=self.lon.min(), \
          urcrnrlon=self.lon.max(),llcrnrlat=self.lat.min(),urcrnrlat=self.lat.max(), \
          resolution=res)

        x, y = m(*np.meshgrid(self.lon, self.lat))

        m.pcolormesh(x, y, self.wMag[instant], shading='flat', cmap=plt.cm.jet)
        m.quiver(x[0:-1:density, 0:-1:density], y[0:-1:density, 0:-1:density],
                 self.u[instant, 0:-1:density, 0:-1:density],
                 self.v[instant, 0:-1:density, 0:-1:density])
        m.colorbar(location='right')
        m.drawcoastlines()
        m.fillcontinents()
        m.drawmapboundary()
        m.drawparallels(self.lat[0:-1:Dline], labels=[1, 0, 0, 0])
        m.drawmeridians(self.lon[0:-1:Dline], labels=[0, 0, 0, 1])
        plt.title('Wind amplitude and direction in [m/s] at time : ' +
                  str(self.time[instant]) + ' days')
        plt.show()

        return plt
Beispiel #6
0
def vec_plot_on_earth(lons, lats, x_data, y_data, vmin=-4, vmax=12, ax=None):
    if ax == None:
	ax = plt.gca()
    plot_lons, plot_x_data = extend_data(lons, lats, x_data)
    plot_lons, plot_y_data = extend_data(lons, lats, y_data)

    lons, lats = np.meshgrid(plot_lons, lats)

    m = Basemap(ax=ax, projection='cyl', resolution='c', llcrnrlat=-90, urcrnrlat=90, llcrnrlon=-180, urcrnrlon=180)
    x, y = m(lons, lats)

    mag = np.sqrt(plot_x_data**2 + plot_y_data**2)
    vmin, vmax = mag.min(), mag.max()
    m.contourf(x[:-1,:], y[:-1,:], mag, ax=ax)
    #m.pcolormesh(x, y, mag, vmin=vmin, vmax=vmax)
    #m.quiver(x, y, plot_x_data, plot_y_data)
    skip = 5
    m.quiver(x[::skip, ::skip], y[::skip, ::skip], plot_x_data[::skip, ::skip], plot_y_data[::skip, ::skip], ax=ax)

    m.drawcoastlines(ax=ax)
    m.drawparallels(np.arange(-90.,90.,45.), labels=[1, 0, 0, 0], fontsize=10, ax=ax)
    m.drawmeridians(np.arange(-180.,180.,60.), labels=[0, 0, 0, 1], fontsize=10, ax=ax)


    m.colorbar(location='bottom', pad='7%', ax=ax)
    plt.show()
def displayWindMapPlot(vdata,udata, lons, lats,):
    """ TODO add a docstring! """
    #plt.clf()
    #pc = plt.contourf(lons, lats, data, 20)
    #plt.colorbar(pc, orientation='horizontal')
    #plt.title(title)
    #plt.xlabel("longitude (degrees east)")
    #plt.ylabel("latitude (degrees north)")
    #plt.show()
    fig, ax = plt.subplots()
    # Do the plot code
    # make orthographic basemap.
    m = Basemap(projection='cyl',llcrnrlat=-40,urcrnrlat=0,\
            llcrnrlon=-20,urcrnrlon=60,resolution='l')

    X,Y=np.meshgrid(lons, lats)
    x,y=m(X,Y) #Convert to map coordinates
    #m.barbs(x,y,vdata,udata,20)
    m.quiver(x,y,vdata,udata,10)
    plt.streamplot(x,y,vdata,udata,10)
    #plt.colorbar(pc,orientation='horizontal')
    m.drawmapboundary()
    m.drawcountries()
    
    m.drawcoastlines(linewidth=1.5)
    
    fig.savefig('myimage.svg', format='svg', dpi=1200)
    plt.show()
    #m.drawparallels(parallels)
    #m.drawmeridians(meridians)
    
    
    """ Contains code for displaying data """
Beispiel #8
0
def vec_plot_polar(lons, lats, data_x, data_y, pole, ax=None):
    if ax == None:
	ax = plt.gca()
    plot_lons, plot_x_data = extend_data(lons, lats, data_x)
    plot_lons, plot_y_data = extend_data(lons, lats, data_y)

    lons, lats = np.meshgrid(plot_lons, lats)

    if pole == 'N':
	m = Basemap(ax=ax, resolution='c',projection='stere',lat_0=90.,lon_0=0, width=12000000,height=8000000)
    elif pole == 'S':
	m = Basemap(ax=ax, resolution='c',projection='stere',lat_0=-90.,lon_0=0, width=12000000,height=8000000)
    x, y = m(lons, lats)

    mag = np.sqrt(plot_x_data**2 + plot_y_data**2)
    vmin, vmax = mag.min(), mag.max()
    m.contourf(x[:-1,:], y[:-1,:], mag, ax=ax)
    #m.pcolormesh(x, y, mag, vmin=vmin, vmax=vmax, ax=ax)
    skip = 5
    m.quiver(x[::5, ::5], y[::5, ::5], plot_x_data[::5, ::5], plot_y_data[::5, ::5], scale=50, ax=ax)

    m.drawcoastlines(ax=ax)
    m.drawparallels(np.arange(-60.,15.,10.), labels=[1, 0, 0, 0], fontsize=10, ax=ax)
    m.drawmeridians(np.arange(-180.,180.,10.), fontsize=10, ax=ax)

    m.colorbar(location='right', pad='5%', ax=ax)
    plt.show()
Beispiel #9
0
def basemap_barbs_mercator(u, v, lat, lon):

    # lon/lat extents
    lons = (np.amin(lon), np.amax(lon))
    lats = (np.amin(lat), np.amax(lat))

    # construct spherical mercator projection for region of interest
    m = Basemap(projection='merc',
                llcrnrlat=lats[0],
                urcrnrlat=lats[1],
                llcrnrlon=lons[0],
                urcrnrlon=lons[1])

    #vmin,vmax = np.nanmin(grid),np.nanmax(grid)
    fig = plt.figure(frameon=False, figsize=(12, 8), dpi=72 * 4)
    plt.axis('off')
    m.quiver(lon, lat, u, v, latlon=True)

    str_io = StringIO()
    plt.savefig(str_io,
                bbox_inches='tight',
                format='png',
                pad_inches=0,
                transparent=True)
    plt.close()

    numpy_bounds = [(lons[0], lats[0]), (lons[1], lats[0]), (lons[1], lats[1]),
                    (lons[0], lats[1])]
    float_bounds = [(float(x), float(y)) for x, y in numpy_bounds]
    return str_io.getvalue(), float_bounds
Beispiel #10
0
def plot_robinson_rossby(model,vec,val,m,l):
	E = model.physical_constants['E']
	Nk = model.Nk
	Nl = model.Nl
	th = model.th

	## Plot Robinson vector field
	#### Display waves on a Spherical Map Projection
	projtype = 'robin'

	## Create full vector grid in theta and phi
	u_1D = model.getVariable(vec,'uph')[0][0]
	v_1D = model.getVariable(vec,'uth')[0][0]
	Nph = 2*Nl
	ph = np.linspace(-180.,180.-360./Nph,Nph)
	lon_grid, lat_grid = np.meshgrid(ph,th[1:-1]*180./np.pi-90.,)
	v = (np.exp(1j*m*lon_grid*np.pi/180.).T*v_1D).T
	u = (np.exp(1j*m*lon_grid*np.pi/180.).T*u_1D).T
	absu=u**2 + v**2
	Nvec = np.floor(Nl/20.)

	### Plot Robinson Projection
	plt.figure(figsize=(10,10))
	## Set up map
	bmap = Basemap(projection=projtype,lon_0=0.)
	bmap.drawparallels(np.arange(-90.,90.,15.))
	bmap.drawmeridians(np.arange(0.,360.,15.))
	## Convert Coordinates to those used by basemap to plot
	lon,lat = bmap(lon_grid,lat_grid)
	bmap.contourf(lon,lat,absu,15,cmap=plt.cm.Reds,alpha=0.5)
	bmap.quiver(lon[::Nvec,::Nvec],lat[::Nvec,::Nvec],u[::Nvec,::Nvec].real,v[::Nvec,::Nvec].real)
	plt.title('{0} Projection Vector Field for m={1}, l={2}'.format('Robinson',m,l))
	plt.savefig('./output/m={1}/{0}VectorField_m={1}_l={2}.png'.format('Robinson',m,l))
def _vec_plot_on_earth(lons, lats, x_data, y_data, vmin=-4, vmax=12, loc=None, colorbar=False):
    plot_lons, plot_x_data = _extend_data(lons, lats, x_data)
    plot_lons, plot_y_data = _extend_data(lons, lats, y_data)

    lons, lats = np.meshgrid(plot_lons, lats)

    if not loc:
        m = Basemap(projection='cyl', resolution='c',
                    llcrnrlat=-90, urcrnrlat=90, llcrnrlon=-180, urcrnrlon=180)
    else:
        m = Basemap(projection='cyl', resolution='c', **loc)
    x, y = m(lons, lats)

    mag = np.sqrt(plot_x_data**2 + plot_y_data**2)
    vmin, vmax = mag.min(), mag.max()
    m.contourf(x, y, mag)
    # m.pcolormesh(x, y, mag, vmin=vmin, vmax=vmax)
    # m.quiver(x, y, plot_x_data, plot_y_data)
    skip = 1
    m.quiver(x[::skip, ::skip], y[::skip, ::skip],
             plot_x_data[::skip, ::skip], plot_y_data[::skip, ::skip], scale=500)

    m.drawcoastlines()
    m.drawparallels(np.arange(-90., 90., 45.), labels=[1, 0, 0, 0], fontsize=10)
    m.drawmeridians(np.arange(-180., 180., 60.), labels=[0, 0, 0, 1], fontsize=10)

    if colorbar:
        m.colorbar(location='right', pad='7%')
    return m
Beispiel #12
0
def plot_mollyweide_rossby(model,vec,val,m,l):
	E = model.E
	Nk = model.Nk
	Nl = model.Nl
	th = model.th

	## Calculate vector field and contour field for plotting with basemap
	## Create full vector grid in theta and phi
	u_1D = model.getVariable(vec,'uph')[0][0]
	v_1D = model.getVariable(vec,'uth')[0][0]
	Nph = 2*Nl
	ph = np.linspace(-180.,180.-360./Nph,Nph)
	lon_grid, lat_grid = np.meshgrid(ph,th[1:-1]*180./np.pi-90.,)
	v = (np.exp(1j*m*lon_grid*np.pi/180.).T*v_1D).T
	u = (np.exp(1j*m*lon_grid*np.pi/180.).T*u_1D).T
	absu=u**2 + v**2
	Nvec = np.floor(Nl/20.)

	### Plot Mollweide Projection
	plt.figure(figsize=(10,10))
	## Set up map
	bmap = Basemap(projection='moll',lon_0=0.)
	bmap.drawparallels(np.arange(-90.,90.,15.))
	bmap.drawmeridians(np.arange(0.,360.,15.))
	## Convert Coordinates to those used by basemap to plot
	lon,lat = bmap(lon_grid,lat_grid)
	bmap.contourf(lon,lat,absu,15,cmap=plt.cm.Reds,alpha=0.5)
	bmap.quiver(lon[::Nvec,::Nvec],lat[::Nvec,::Nvec],u[::Nvec,::Nvec].real,v[::Nvec,::Nvec].real)
	plt.title('Mollweide Projection Vector Field for m={0}, l={1}'.format(m,l))
	plt.savefig('./output/m={1}/MollweideVectorField_m={1}_l={2}.png'.format(val.imag,m,l))
Beispiel #13
0
def visual_ice_wind(ice_file_name, latlon145_file_name, points, show=True):
	"""
	氷の速度データの可視化
	"""
	u_true, v_true, speed_true = read_ice_v(ice_file_name, reshape=True)
	lon, lat = read_lonlat(latlon145_file_name)

	m = Basemap(lon_0=180,boundinglat=50,
	            resolution='l',projection='npstere')
	fig=plt.figure(figsize=(6,6))

	#グリッドの描画
	"""
	lons, lats = m(lon,lat,inverse=False)
	m.plot(lons,lats,'bo', markersize=0.3)
	"""
	x, y = m(lon, lat)
	x = np.reshape(x, (145,145), order='F')
	y = np.reshape(y, (145,145), order='F')

	m.drawcoastlines(color = '0.15')

	m.quiver(x[points], y[points], 
	    u_true[points], v_true[points], speed_true[points])
	"""
	import numpy.ma as ma
	Zm = ma.masked_where(np.isnan(speed_true),speed_true)

	m.pcolormesh(x[points], y[points], Zm[points], cmap=plt.cm.jet)
	m.colorbar(location='bottom', format='%.2f')
	"""
	
	if show==True:
		plt.show()
Beispiel #14
0
def contourMap(grdROMS, tlon, tlat, mydata1, mydata2, mydata3, var, mytype, currentdate):

    plt.figure(figsize=(10,10), frameon=False)
    
    map = Basemap(lon_0=25,boundinglat=50,
                      resolution='l',area_thresh=100.,projection='npstere')
    
    x, y = list(map(tlon,tlat))

    map.drawcoastlines()
    map.fillcontinents(color='grey')
    map.drawcountries()

    if var=='wind':
        levels = np.arange(np.min(mydata3),np.max(mydata3),0.1)
   
        CS1 = map.contourf(x, y, mydata3, levels, cmap=cm.get_cmap('RdYlBu_r',len(levels)-1) )#,alpha=0.5)
        plt.colorbar(CS1, orientation='vertical', extend='both', shrink=0.5)
            
        if mytype=="REGSCEN":
          step=8
        else:
          step=1
        map.quiver(x[0:-1:step,0:-1:step],y[0:-1:step,0:-1:step],
            mydata1[0:-1:step,0:-1:step],mydata2[0:-1:step,0:-1:step],
            scale=400)
   
  #  plt.title('Var:%s - depth:%s - time:%s'%(var,grdROMS.time))
    plotfile='figures/'+str(var)+'_'+str(mytype)+'_time_'+str(currentdate)+'.png'
    if not os.path.exists('figures'):
        os.makedirs('figure')
    plt.savefig(plotfile)
    print("Saved figure: %s"%(plotfile))
Beispiel #15
0
def plot_grid(EIC_grid,sat_track,sat_krig,title):
    '''
    This function plots a scatter map of the EICS grid and its horizontal components, and the krigged value for the
    satellite.

    :param EIC_grid: The EICS grid
    :param satPos: The position of the satellite
    :param ptz_u: The krigged u component of the satellite
    :param ptz_v: The krigged v component of the satllite
    :param title: Timestamp of the satellite
    :return: The figure
    '''

    # Define the size of the figure in inches
    plt.figure(figsize=(18,18))

    # The horizontal components of the Ionospheric current from the EICS grid
    u = EIC_grid[:,2]
    v = EIC_grid[:,3]

    '''
    The m variable defines the basemap of area that is going to be displayed.
    1) width and height is the area in pixels of the area to be displayed.
    2) resolution is the resolution of the boundary dataset being used 'c' for crude and 'l' for low
    3) projection is type of projection of the basemape, in this case it is a Lambert Azimuthal Equal Area projection
    4) lat_ts is the latitude of true scale,
    5) lat_0 and lon_0 is the latitude and longitude of the central point of the basemap
    '''
    m = Basemap(width=8000000, height=8000000, resolution='l', projection='lcc',\
             lat_0=60,lon_0=-100.)

    m.drawcoastlines() #draw the coastlines on the basemap

    # draw parallels and meridians and label them
    m.drawparallels(np.arange(-80.,81.,20.),labels=[1,0,0,0],fontsize=10)
    m.drawmeridians(np.arange(-180.,181.,20.),labels=[0,0,0,1],fontsize=10)

    # Project the inputted grid into x,y values defined of the projected basemap parameters
    x,y =m(EIC_grid[:,1],EIC_grid[:,0])
    satx,saty = m(sat_track[::10,7],sat_track[::10,6])
    satkrigx,satkrigy = m(sat_krig[1],sat_krig[0])


    '''
    Plot the inputted grid as a quiver plot on the basemap,
    1) x,y are the projected latitude and longitude coordinates of the grid
    2) u and v are the horizontal components of the current
    3) the EICS grid values are plotted in blue color where as the satellite krigged values are in red
    '''
    eic = m.quiver(x,y,u,v,width = 0.004, scale=10000,color='#0000FF')
    satkrig = m.quiver(satkrigx,satkrigy,sat_krig[2],sat_krig[3],color='#FF0000',width=0.004, scale = 10000)
    satpos = m.scatter(satx,saty,s=100,marker='.',c='#009933',edgecolors='none',label='Satellite Track')
    sat_halo = m.scatter(satkrigx,satkrigy,s=400,facecolors='none',edgecolors='#66FF66',linewidth='5')

    plt.title(title)
    plt.legend([satpos],['Satellite Track'],loc='upper right',scatterpoints=1)
    plt.quiverkey(satkrig,0.891,0.948,520,u'\u00B1' +'520 mA/m',labelpos='E')

    plt.savefig('EICS_20110311_002400.png',bbox_inches='tight',pad_inches=0.2)
Beispiel #16
0
def visual_all_by_map(data, data_type, lonlat_data, points):
    #quiver, pcolormesh全てできるようにする
    lon, lat = lonlat_data[0], lonlat_data[1]
    m = Basemap(lon_0=180,
                boundinglat=50,
                resolution='l',
                projection='npstere')
    fig = plt.figure(figsize=(7.5, 7.5))

    x, y = m(lon, lat)
    x1 = np.reshape(x, (145, 145), order='F')
    y1 = np.reshape(y, (145, 145), order='F')

    m.drawcoastlines(color='0.15')

    if data_type == "type_wind":
        #data column: ["data_idx", "w_u", "w_v", "w_speed", "Label", "Name"]
        data[data.data_idx == 0.] = np.nan

        vector_u = np.array(data.iloc[:, 1])
        vector_v = np.array(data.iloc[:, 2])
        vector_speed = np.array(data.iloc[:, 3])

        vector_u = np.ma.masked_invalid(vector_u)
        vector_v = np.ma.masked_invalid(vector_v)
        vector_speed = np.ma.masked_invalid(vector_speed)

        vector_u1 = np.reshape(vector_u, (145, 145), order='F')
        vector_v1 = np.reshape(vector_v, (145, 145), order='F')
        vector_speed1 = np.reshape(vector_speed, (145, 145), order='F')

        #風の描画
        m.quiver(x1[points], y1[points], vector_u1[points], vector_v1[points],
                 vector_speed1[points])

    elif data_type == "type_non_wind":
        #data column: ["data_idx", "ic0_145", "Label", "Name"]
        data[data.data_idx == 0.] = np.nan

        plot_data = np.array(data.iloc[:, 1])
        #ここに微調整を書く
        #plot_data[plot_data>=0.05] = np.nan
        #plot_data = np.absolute(plot_data)
        #plot_data[(plot_data>50) | (plot_data<-50)] = np.nan
        #print(set(plot_data.tolist()))

        plot_data = np.ma.masked_invalid(plot_data)

        plot_data1 = np.reshape(plot_data, (145, 145), order='F')

        m.pcolormesh(x1, y1, plot_data1, cmap=plt.cm.jet)
        m.colorbar(location='bottom')

    else:
        plot_data = np.array(data.iloc[:, 1])
        plot_data = np.ma.masked_invalid(plot_data)
        m.scatter(x, y, marker='o', color="b", s=1.2, alpha=0.9)
Beispiel #17
0
def test():
    plt.figure()
    b = Basemap()
    u = np.array([1, ])
    v = np.array([1, ])
    lon, lat = np.array([-90, ]), np.array([45, ])
    xx, yy = b(lon, lat)
    print(xx.shape)
    b.quiver(xx, yy, u, v, color="r")

    urot, vrot = b.rotate_vector(u, v, lon, lat)
    b.quiver(xx, yy, urot, vrot, color="g")

    b.drawcoastlines()



    # Plot the same in rotpole projection

    HL_LABEL = "CRCM5_HL"
    NEMO_LABEL = "CRCM5_NEMO"

    sim_label_to_path = OrderedDict(
        [(HL_LABEL, "/RESCUE/skynet3_rech1/huziy/CNRCWP/C5/2016/2-year-runs/coupled-GL+stfl_oneway/Samples"),
         (NEMO_LABEL, "/HOME/huziy/skynet3_rech1/CNRCWP/C5/2016/2-year-runs/coupled-GL+stfl/Samples")]
    )

    # get a coord file ...
    coord_file = ""
    found_coord_file = False
    for mdir in os.listdir(sim_label_to_path[HL_LABEL]):

        mdir_path = os.path.join(sim_label_to_path[HL_LABEL], mdir)
        if not os.path.isdir(mdir_path):
            continue

        for fn in os.listdir(mdir_path):
            print(fn)
            if fn[:2] not in ["pm", "dm", "pp", "dp"]:
                continue

            coord_file = os.path.join(mdir_path, fn)
            found_coord_file = True

        if found_coord_file:
            break

    bmp, lons, lats = nemo_hl_util.get_basemap_obj_and_coords_from_rpn_file(path=coord_file)


    plt.figure()
    urot, vrot = bmp.rotate_vector(u, v, lon, lat)
    xx, yy = bmp(lon, lat)

    bmp.quiver(xx, yy, urot, vrot, color="b")
    bmp.drawcoastlines()
    plt.show()
Beispiel #18
0
def ocean_with_colorbar(num):
	if num == 1:
		dirs = "../result_h_1day_delay/mean_vector/ocean_currents/"
	else:
		dirs = "../result_nc_1day_delay/mean_vector/ocean_currents/"
	if not os.path.exists(dirs):
		os.makedirs(dirs)

	y_list = ["03", "04", "05", "06", "07", "08", "09", "10", "13", "14", "15", "16"]
	month_list = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"]
	for year in y_list:
		for month in month_list:
			print(year + month)
			if num == 1:
				file = "../data/csv_Helmert_30_1day_delay/Helmert_30_1day_delay_20" + year + month + ".csv"
			else:
				file = "../data/csv_Helmert_30_netcdf4_1day_delay/Helmert_30_netcdf4_1day_delay_20" + year + month + ".csv"
			df = pd.read_csv(file)
			data_vec = [np.array(df["ocean_u"]), np.array(df["ocean_v"])]

			m = Basemap(lon_0=180, boundinglat=50, resolution='l', projection='npstere')
			m.drawcoastlines(color = '0.15')
			m.fillcontinents(color='#555555')
			lon = np.array(latlon_ex.Lon)
			lat = np.array(latlon_ex.Lat)
			x, y = m(lon, lat)
			x1 = np.reshape(x, (145,145), order='F')
			y1 = np.reshape(y, (145,145), order='F')
			dx1 = (x1[1,0]-x1[0,0])/2
			dy1 = (y1[0,1]-y1[0,0])/2

			x2 = np.linspace(x1[0,0], x1[144,0], 145)
			y2 = np.linspace(y1[0,0], y1[0,144], 145)
			xx, yy = np.meshgrid(x2, y2)
			xx, yy = xx.T, yy.T

			vector_u = np.ma.masked_invalid(data_vec[0])
			vector_v = np.ma.masked_invalid(data_vec[1])
			vector_speed = np.sqrt(vector_u*vector_u + vector_v*vector_v)

			data_non_wind = vector_speed
			data_non_wind = np.ma.masked_invalid(data_non_wind)
			data1 = np.reshape(data_non_wind, (145,145), order='F')

			xx = np.hstack([xx, xx[:,0].reshape(145,1)])
			xx_ex = np.vstack([xx, (xx[144,:] + (xx[1,0]-xx[0,0]))])
			yy = np.vstack([yy, yy[0,:]])
			yy_ex = np.hstack([(yy[:,0].reshape(146,1) + (yy[0,0]-yy[0,1])), yy])

			m.pcolormesh(xx_ex-dx1, yy_ex+dy1, data1, cmap=cm_ocean_current, vmax=0.2, vmin=0)
			m.colorbar(location='bottom')
			m.quiver(x, y, vector_u, vector_v, color="k")
			save_name = dirs + "ocean_" + year + month + ".png"
			print(save_name)
			plt.savefig(save_name, dpi=350)
			plt.close()
Beispiel #19
0
    def do_fig(figsize):
        fig = plt.figure(figsize=figsize, dpi=dpi)
        ax = fig.add_axes([0, 0, 1, 1])
        ax.axis('off')

        my_map = Basemap(projection='cyl',
                         llcrnrlat=min(lats),
                         lon_0=np.median(longs),
                         llcrnrlon=min(longs),
                         urcrnrlat=max(lats),
                         urcrnrlon=max(longs),
                         resolution='c',
                         fix_aspect=False)
        xx, yy = np.meshgrid(longs, lats)
        x_map, y_map = my_map(xx, yy)
        my_map.drawcoastlines(color=[0.5, 0.5, 0.5])

        my_map.contour(x_map,
                       y_map,
                       d,
                       line,
                       cmap=my_cmap,
                       vmax=v_max,
                       vmin=v_min)
        my_map.contour(x_map,
                       y_map,
                       d3,
                       line2,
                       cmap=my_cmap4,
                       vmax=v_max3,
                       vmin=v_min3)
        my_map.contourf(x_map,
                        y_map,
                        d2,
                        64,
                        cmap=my_cmap2,
                        vmax=v_max2,
                        vmin=v_min2)
        if u_wind is not None and v_wind is not None:
            wind_speed = np.sqrt(u_wind**2 + v_wind**2)
            my_map.quiver(x_map[::20, ::20],
                          y_map[::20, ::20],
                          u_wind[::20, ::20],
                          v_wind[::20, ::20],
                          wind_speed[::20, ::20],
                          alpha=0.5,
                          cmap=my_cmap3)

        if (not land):
            my_map.fillcontinents(alpha=0.5)
        mask_ex = plt.gcf()
        mask_ex.savefig(namedir + "/" + plt_title,
                        dpi=dpi,
                        quality=100,
                        pad_inches=0)
        plt.clf()
Beispiel #20
0
def plot_grid(EIC_grid,sat_latlon,ptz_u,ptz_v,title):
    '''
    This function plots a scatter map of the EICS grid and its horizontal components, and the krigged value for the
    satellite.

    :param EIC_grid: The EICS grid
    :param satPos: The position of the satellite
    :param ptz_u: The krigged u component of the satellite
    :param ptz_v: The krigged v component of the satllite
    :param title: Timestamp of the satellite
    :return: The figure
    '''

    # Define the size of the figure in inches
    plt.figure(figsize=(18,18))

    # The horizontal components of the Ionospheric current from the EICS grid
    u = EIC_grid[:,2]
    v = EIC_grid[:,3]

    '''
    The m variable defines the basemap of area that is going to be displayed.
    1) width and height is the area in pixels of the area to be displayed.
    2) resolution is the resolution of the boundary dataset being used 'c' for crude and 'l' for low
    3) projection is type of projection of the basemape, in this case it is a Lambert Azimuthal Equal Area projection
    4) lat_ts is the latitude of true scale,
    5) lat_0 and lon_0 is the latitude and longitude of the central point of the basemap
    '''
    m = Basemap(width=8000000, height=8000000, resolution='l', projection='laea',\
                lat_ts=min(EIC_grid[:,0]), lat_0=np.median(EIC_grid[:,0]),lon_0=-100.)

    m.drawcoastlines() #draw the coastlines on the basemap

    # draw parallels and meridians and label them
    m.drawparallels(np.arange(-80.,81.,20.),labels=[1,0,0,0],fontsize=10)
    m.drawmeridians(np.arange(-180.,181.,20.),labels=[0,0,0,1],fontsize=10)

    # Project the inputted grid into x,y values defined of the projected basemap parameters
    x,y =m(EIC_grid[:,1],EIC_grid[:,0])
    satx,saty = m(sat_latlon[0,1],sat_latlon[0,0])

    '''
    Plot the inputted grid as a quiver plot on the basemap,
    1) x,y are the projected latitude and longitude coordinates of the grid
    2) u and v are the horizontal components of the current
    3) the EICS grid values are plotted in blue color where as the satellite krigged values are in red
    '''
    m.quiver(x,y,u,v,width = 0.004, scale=10000,color='#0000FF')
    m.quiver(satx,saty,ptz_u[0],ptz_v[0],color='#FF0000',width=0.004, scale = 10000)
    m.scatter(satx,saty,s=400,facecolors='none',edgecolors='#66FF66',linewidth='5')

    plt.title(title)
    plt.savefig('/home/sonal/EICS_201104/figs/'+title+'.png',bbox_inches='tight',pad_inches=0.1)
    #plt.show()
    plt.clf()
Beispiel #21
0
def plot_robinson(model,
                  vec,
                  m,
                  v_scale=1.0,
                  dir_name='./',
                  title='Velocity and Divergence at CMB'):
    from mpl_toolkits.basemap import Basemap
    E = model.E
    Nk = model.Nk
    Nl = model.Nl
    th = model.th[0, :]

    ## Plot Robinson vector field
    #### Display waves on a Spherical Map Projection
    projtype = 'robin'
    ## Create full vector grid in theta and phi
    u_1D = model.get_variable(vec, 'vph')[0][-1, :]
    v_1D = model.get_variable(vec, 'vth')[0][-1, :]
    Nph = 2 * Nl
    ph = np.linspace(-180., 180. - 360. / Nph, Nph)
    lon_grid, lat_grid = np.meshgrid(
        ph,
        th * 180. / np.pi - 90.,
    )
    v = (np.exp(1j * m * lon_grid * np.pi / 180.).T * v_1D).T
    u = (np.exp(1j * m * lon_grid * np.pi / 180.).T * u_1D).T
    absu = u**2 + v**2

    div = np.zeros(u.shape)
    for x in range(Nph):
        for y in range(1, model.Nl - 1):
            div[y, x] = u[y, x] * m * 1j + (v[y + 1, x] -
                                            v[y - 1, x]) / (2. * model.dth)
    ### Plot Robinson Projection
    plt.figure(figsize=(10, 10))
    ## Set up map
    bmap = Basemap(projection=projtype, lon_0=0.)
    bmap.drawparallels(np.arange(-90., 90., 15.))
    bmap.drawmeridians(np.arange(0., 360., 15.))
    ## Convert Coordinates to those used by basemap to plot
    lon, lat = bmap(lon_grid, lat_grid)
    bmap.contourf(lon, lat, div.real, 15, cmap=plt.cm.RdBu, alpha=0.5)
    Nvec = np.floor(Nl / 20.)
    bmap.quiver(lon[::Nvec, ::Nvec],
                lat[::Nvec, ::Nvec],
                u[::Nvec, ::Nvec].real,
                v[::Nvec, ::Nvec].real,
                scale=v_scale)
    plt.title(title)
    #    plt.show()
    plt.savefig(dir_name + title + '.png')
def plot_flow_directions():
    data = read_binary(BASE_PATH + os.path.sep + "5minfdr.img")

    print data[:, 0]

    return
    data = data[::100, ::100]

    print data.shape

    #    plot_flow_directions(data)
    lons, lats = get_graham_grid(the_shape=data.shape, lower_left_point=GeoPoint(-80, 45)).get_lons_lats_2d()
    #    plt.contourf(lons, lats, data)

    m = Basemap(llcrnrlon=-80.0, llcrnrlat=45, urcrnrlon=0, urcrnrlat=90)
    lons, lats = m(lons, lats)

    scale = 1.0

    get_u_coord_vec = np.vectorize(get_u_coordinate, otypes=["float"])
    get_v_coord_vec = np.vectorize(get_v_coordinate, otypes=["float"])

    flat_data = data.ravel()

    u = get_u_coord_vec(flat_data, scale)
    v = get_v_coord_vec(flat_data, scale)

    u, v = u.reshape(data.shape), v.reshape(data.shape)

    inches_per_pt = 1.0 / 72.27  # Convert pt to inch
    golden_mean = (sqrt(5) - 1.0) / 2.0  # Aesthetic ratio
    fig_width = 700 * inches_per_pt  # width in inches
    fig_height = fig_width * golden_mean  # height in inches
    fig_size = [fig_width, fig_height]

    params = {
        "axes.labelsize": 14,
        "text.fontsize": 14,
        "legend.fontsize": 14,
        "xtick.labelsize": 16,
        "ytick.labelsize": 16,
        "figure.figsize": fig_size,
    }

    pylab.rcParams.update(params)

    m.quiver(lons, lats, u, v, width=0.002, scale=50)
    m.drawcoastlines()

    plt.savefig("fdr5min.png")
Beispiel #23
0
def testOneShot(ncfile):
    myCMEMSdata = xr.open_dataset(ncfile).resample(time='3H').reduce(np.mean)

    # time 
    lastDate =myCMEMSdata.time.values[myCMEMSdata.time.values.size-1]
    startDate = myCMEMSdata.time.values[0]

    print(startDate," - ", lastDate)
    print(myCMEMSdata.time.values.size)

    plt.figure(figsize=(20.48, 10.24))
    plt.clf()

    # projection, lat/lon extents and resolution of polygons to draw
    # resolutions: c - crude, l - low, i - intermediate, h - high, f - full
    map = Basemap(projection='merc', llcrnrlon=-10.,
                  llcrnrlat=30., urcrnrlon=36.5, urcrnrlat=46.)
    #map.etopo()
    map.shadedrelief(scale=0.65)


    X, Y = np.meshgrid(myCMEMSdata.longitude.values,
                       myCMEMSdata.latitude.values)
    x, y = map(X, Y)

    waveH = myCMEMSdata.VHM0.values
    wDir = myCMEMSdata.VMDR.values
    del myCMEMSdata
 

    my_cmap = plt.get_cmap('rainbow')
    onde = map.pcolormesh(x, y, waveH[0,:,:], cmap=my_cmap, norm=matplotlib.colors.LogNorm(vmin=0.07, vmax=4.,clip=True))
    
    #plt.colorbar();

    # waves direction
    # reduce arrows density (1 out of 15)
    yy = np.arange(0, y.shape[0], 15)
    xx = np.arange(0, x.shape[1], 15)
    points = np.meshgrid(yy,xx)

    wDir = wDir[0,:,:]
    
    map.quiver(x[points],y[points],np.cos(np.deg2rad(270-wDir[points])),np.sin(np.deg2rad(270-wDir[points])),
    	edgecolor='lightgray', minshaft=4,  width=0.007, headwidth=3., headlength=4., linewidth=.5)

    plt.show()
    plt.savefig("prova_s065.jpg", quality=75)
    plt.close()
Beispiel #24
0
def getMaps(ncfile):
    myCMEMSdata = xr.open_dataset(ncfile).resample(time='3H').reduce(np.mean)

    # projection, lat/lon extents and resolution of polygons to draw
    # resolutions: c - crude, l - low, i - intermediate, h - high, f - full
    map = Basemap(projection='merc', llcrnrlon=-10.,
                  llcrnrlat=30., urcrnrlon=36.5, urcrnrlat=46.)


    X, Y = np.meshgrid(myCMEMSdata.longitude.values,
                       myCMEMSdata.latitude.values)
    x, y = map(X, Y)

    # reduce arrows density (1 out of 15)
    yy = np.arange(0, y.shape[0], 15)
    xx = np.arange(0, x.shape[1], 15)
    points = np.meshgrid(yy,xx)

    #cycle time to save maps
    i=0
    while i < myCMEMSdata.time.values.size:
        fig=plt.figure(figsize=(20.48, 10.24))
        map.shadedrelief(scale=0.65)
        #waves height
        waveH = myCMEMSdata.VHM0.values[i, :, :]
        my_cmap = plt.get_cmap('rainbow')
        map.pcolormesh(x, y, waveH, cmap=my_cmap, norm=matplotlib.colors.LogNorm(vmin=0.07, vmax=4.,clip=True))
        # waves direction
        wDir = myCMEMSdata.VMDR.values[i, :, :]
        map.quiver(x[tuple(points)],y[tuple(points)],np.cos(np.deg2rad(270-wDir[tuple(points)])),np.sin(np.deg2rad(270-wDir[tuple(points)])),
            edgecolor='lightgray', minshaft=4,  width=0.007, headwidth=3., headlength=4., linewidth=.5)
        # save plot
        filename = pd.to_datetime(myCMEMSdata.time[i].values).strftime("%Y-%m-%d_%H")
        #plt.show()
        plt.savefig(TEMPDIR+filename+".jpg", quality=75)
        plt.clf()
        del wDir
        del waveH
        del my_cmap
        plt.close("all")
        del fig
        i += 1

    #out of loop
    del map
    myCMEMSdata.close()
    del myCMEMSdata
    gc.collect()
Beispiel #25
0
def plot_map_once(data, **kwargs):
	data_type = kwargs["data_type"]
	show = kwargs["show"]
	save_name = kwargs["save_name"]
	vmax = kwargs["vmax"]
	vmin = kwargs["vmin"]

	m = Basemap(lon_0=180, boundinglat=50, resolution='i', projection='npstere')
	fig = plt.figure(figsize=(6.5, 6.5))
	m.drawcoastlines(color = '0.15')
	m.fillcontinents(color='#555555')

	x, y = m(lon, lat)
	x1 = np.reshape(x, (145,145), order='F')
	y1 = np.reshape(y, (145,145), order='F')

	if data_type == "type_wind":
		print(data.columns)
		data = np.array(data)
		vector_u = np.ma.masked_invalid(data[:, 0])
		vector_v = np.ma.masked_invalid(data[:, 1])
		vector_speed = np.sqrt(vector_u*vector_u + vector_v*vector_v)
		m.quiver(x, y, vector_u, vector_v, vector_speed)
		#m.quiver(x, y, vector_u, vector_v, angles='xy', scale_units='xy')
		#m.quiver(x, y, vector_u, vector_v)

	elif data_type == "type_non_wind":
		data = np.array(data)
		#ここに微調整を書く
		#plot_data[plot_data>=0.05] = np.nan
		#plot_data = np.absolute(plot_data)
		#plot_data[(plot_data>50) | (plot_data<-50)] = np.nan
		data = np.ma.masked_invalid(data)
		data1 = np.reshape(data, (145,145), order='F')
		m.pcolormesh(x1, y1, data1, cmap=plt.cm.jet, vmax=vmax, vmin=vmin)
		#m.pcolormesh(x1, y1, data1, cmap=cm, vmax=vmax, vmin=vmin)
		#m.pcolormesh(x1, y1, data1, cmap=plt.cm.jet)
		m.colorbar(location='bottom')

	else:
		data = np.ma.masked_invalid(data)
		m.scatter(x, y, marker='o', color = "b", s=1.2, alpha=0.9)

	if show == True:
		plt.show()
	if save_name is not None:
		plt.savefig(save_name, dpi=1200)
	plt.close()
Beispiel #26
0
    def XVsY2DWindMap(self,
                      ax,
                      xVal,
                      yVal,
                      uVal,
                      vVal,
                      title=None,
                      xlabel=None,
                      xlim=None,
                      ylabel=None,
                      ylim=None,
                      zlabel=None,
                      zMax=None,
                      zMin=None):

        m = Basemap(llcrnrlon=self.glonlim[0],
                    llcrnrlat=self.glatlim[0],
                    urcrnrlon=self.glonlim[-1],
                    urcrnrlat=self.glatlim[-1],
                    resolution='l')

        m.drawcoastlines()

        # Lines at constant "latitude"
        parallelsLim = self._RoundLim([yVal[0], yVal[-1]])
        m.drawparallels(arange(parallelsLim[0], parallelsLim[1], 20.),
                        labels=[True, False, False, True])

        # Lines at constant "longitude"
        meridiansLim = self._RoundLim([xVal[0], xVal[-1]])
        m.drawmeridians(arange(meridiansLim[0], meridiansLim[1], 30.),
                        labels=[True, False, False, True])

        X, Y = meshgrid(xVal, yVal)
        totalWind = (uVal**2 + vVal**2)**.5

        ipc = m.quiver(X, Y, transpose(uVal), transpose(vVal), transpose(totalWind), \
            alpha=.5, angles='uv', cmap=cm.jet, pivot='middle', units='xy')
        ipc2 = m.quiver(X, Y, transpose(uVal), transpose(vVal), \
            angles='uv', edgecolor='k', facecolor='None', linewidth=.5, pivot='middle', \
            units='xy')

        ax.set_xlim(xlim)
        ax.set_ylim(ylim)
        ax.set_title(title)

        cbpn = m.colorbar(ipc)
        cbpn.set_label(zlabel)
Beispiel #27
0
 def plot (self, basemap = None, alpha=1, color='red') :
     if basemap == None :
         from mpl_toolkits.basemap import Basemap
         basemap = Basemap(
                 projection = 'nplaea',
                 boundinglat = 30,
                 lon_0 = 0,
                 round = True)
         basemap.drawcoastlines()
     """
     basemap.plot(*basemap(self.lons, self.lats),
             linewidth=2, color=color, alpha=0.3)
     """
     x, y = basemap(self.lons, self.lats)
     basemap.quiver(x[:-1], y[:-1], x[1:]-x[:-1], y[1:]-y[:-1],
         scale_units='xy', angles='xy', scale=1, width=3e-3, color=color, alpha=alpha)
Beispiel #28
0
    def play_scenario(self, idsc=0, interactive=True):
        interp_u = np.zeros((len(self.times), len(self.lats), len(self.lons)))
        interp_v = np.zeros((len(self.times), len(self.lats), len(self.lons)))
        mag = np.zeros((len(self.times), len(self.lats), len(self.lons)))

        for t, time in enumerate(self.times):
            for ii, lat in enumerate(self.lats):
                for j, lon in enumerate(self.lons):
                    query_pt = [time, lat, lon]
                    interp_u[t][ii][j] = self.uWindAvg(query_pt)
                    interp_v[t][ii][j] = self.vWindAvg(query_pt)
                    mag[t][ii][j] = (interp_u[t][ii][j]**2 +
                                     interp_v[t][ii][j]**2)**0.5

        # %% PLOT
        font = {'family': 'normal', 'weight': 'bold', 'size': 22}
        proj = 'mill'
        res = 'i'
        Dline = 5
        density = 1
        matplotlib.rc('font', **font)
        fig = plt.figure(figsize=(8, 5))

        m = Basemap(projection=proj, lat_ts=10, llcrnrlon=self.lons.min(), \
                    urcrnrlon=self.lons.max(), llcrnrlat=self.lats.min(), urcrnrlat=self.lats.max(), \
                    resolution=res)

        x, y = m(*np.meshgrid(self.lons, self.lats))
        contour = m.pcolormesh(x, y, mag[0], shading="flat", cmap=plt.cm.jet)
        cbar = m.colorbar(location='right')
        quiv = m.quiver(x, y, interp_u[0], interp_v[0], color='black')
        cbar.ax.set_ylabel('Wind magnitude m/s')

        m.drawcoastlines()
        m.fillcontinents()
        m.drawmapboundary()
        m.drawparallels(self.lats[0::Dline], labels=[1, 0, 0, 0])
        m.drawmeridians(self.lons[0::Dline], labels=[0, 0, 0, 1])
        tit = plt.title('Scenario ' + str(idsc) + ' at time : ' +
                        str(self.times[0]) + ' days')

        ### using this class is as easy as using FuncAnimation:

        def update(i):
            contour.set_array(mag[i][:-1, :-1].ravel())
            quiv.set_UVC(interp_u[i], interp_v[i])
            tit.set_text('Scenario ' + str(idsc) + ' at time : ' +
                         str(self.times[i]) + ' days')
            cbar.set_clim(vmin=mag[i].min(), vmax=mag[i].max())
            cbar.draw_all()

        if interactive:
            ani = Player(fig, update, maxi=len(interp_v) - 1)
        else:
            ani = animation.FuncAnimation(fig,
                                          update,
                                          frames=len(interp_v),
                                          interval=600)
        plt.show()
        return ani
def plot_global_vector_map(uwind,
                           vwind,
                           lon,
                           lat,
                           figure_file,
                           yskip=10,
                           xskip=20):
    lons, lats = np.meshgrid(lon, lat)
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    m = Basemap(ax=ax,
                projection='eck4',
                lon_0=0,
                llcrnrlat=lat.min(),
                urcrnrlat=lat.max(),
                llcrnrlon=lon.min(),
                urcrnrlon=lon.max(),
                resolution='l',
                fix_aspect=True)
    x, y = m(lons, lats)
    m.drawcoastlines(linewidth=1)
    m.drawcountries(linewidth=.75)
    N = ma.mean(
        np.sqrt(uwind[::yskip, ::xskip]**2 + vwind[::yskip, ::xskip]**2))
    max = m.quiver(x[::yskip, ::xskip],
                   y[::yskip, ::xskip],
                   uwind[::yskip, ::xskip] / N,
                   vwind[::yskip, ::xskip] / N,
                   color='blue',
                   pivot='middle',
                   headwidth=3)
    fig.savefig(figure_file, dpi=600, bbox_inches='tight')
    plt.show()
Beispiel #30
0
def plot_gini_grid_vectors(gini_grid, box = [-110, -70, 20, 52], resolution = 'l',
                   parallels = None,
                   meridians = None,
                   vmin = None, vmax = None,
                   fld = 'IR', title = None,
                   degrade = 5, u='u', v='v', scale = 200):
    m = Basemap(llcrnrlon = box[0] ,llcrnrlat = box[2] , urcrnrlon = box[1],
                   urcrnrlat = box[3] , projection = 'mill', area_thresh =1000 ,
                   resolution = resolution)
    
    x, y = m(gini_grid.fields['lon']['data'], gini_grid.fields['lat']['data'])
    # create figure.
    if parallels == None:
        parallels = np.linspace(10,50, 9)
    if meridians == None:
        meridians = np.linspace(-110, -80,7)
    m.drawparallels(parallels, labels=[1,1,0,0])
    m.drawmeridians(meridians,labels=[0,0,0,1]) 
    pc = m.pcolormesh(x, y , gini_grid.fields[fld]['data'][0,:], cmap=plt.get_cmap('gray'),
                      vmin = vmin, vmax = vmax)
    qq = m.quiver(x[::degrade,::degrade], y[::degrade,::degrade], 
                  gini_grid.fields[u]['data'][0,::degrade,::degrade], 
                  gini_grid.fields[v]['data'][0,::degrade,::degrade], scale=scale)

    plt.title(title)
    m.drawcoastlines(linewidth=1.25)
    m.drawstates()
    plt.colorbar(mappable=pc, label = 'Counts')
Beispiel #31
0
def main():

    plot_utils.apply_plot_params(width_cm=20, height_cm=20, font_size=10)

    high_hles_years = [1993, 1995, 1998]
    low_hles_years = [1997, 2001, 2006]
    data_path = "/BIG1/skynet1_rech1/diro/sample_obsdata/eraint/eraint_uvslp_years_198111_201102_NDJmean_ts.nc"





    with xr.open_dataset(data_path) as ds:
        print(ds)


        u = get_composit_for_name(ds, "u10", high_years_list=high_hles_years, low_years_list=low_hles_years)
        v = get_composit_for_name(ds, "v10", high_years_list=high_hles_years, low_years_list=low_hles_years)
        msl = get_composit_for_name(ds, "msl", high_years_list=high_hles_years, low_years_list=low_hles_years)

        lons = ds["longitude"].values
        lats = ds["latitude"].values

        print(lats)
        print(msl.shape)
        print(lons.shape, lats.shape)


        lons2d, lats2d = np.meshgrid(lons, lats)


    fig = plt.figure()

    map = Basemap(llcrnrlon=-130, llcrnrlat=22, urcrnrlon=-28,
                  urcrnrlat=65, projection='lcc', lat_1=33, lat_2=45,
                  lon_0=-95, resolution='i', area_thresh=10000)


    clevs = np.arange(-11.5, 12, 1)
    cmap = cm.get_cmap("bwr", len(clevs) - 1)
    bn = BoundaryNorm(clevs, len(clevs) - 1)

    x, y = map(lons2d, lats2d)
    im = map.contourf(x, y, msl / 100, levels=clevs, norm=bn, cmap=cmap) # convert to mb (i.e hpa)
    map.colorbar(im)


    stride = 2
    ux, vy = map.rotate_vector(u, v, lons2d, lats2d)
    qk = map.quiver(x[::stride, ::stride], y[::stride, ::stride], ux[::stride, ::stride], vy[::stride, ::stride],
               scale=10, width=0.01, units="inches")
    plt.quiverkey(qk, 0.5, -0.1, 2, "2 m/s", coordinates="axes")


    map.drawcoastlines(linewidth=0.5)
    map.drawcountries()
    map.drawstates()
    #plt.show()

    fig.savefig("hles_wind_compoosits.png", bbox_inches="tight", dpi=300)
Beispiel #32
0
def drawcurrents(lats, lons, ust, vst, mod, total, title, time, boundary_box):
    """

    :return:
    """

    import matplotlib.pyplot as plt
    import matplotlib.spines as spn
    from mpl_toolkits.basemap import Basemap

    fig = plt.figure(figsize=(15, 15))
    ax = fig.add_subplot(1, 1, 1)
    for child in ax.get_children():
        if isinstance(child, spn.Spine):
            child.set_color('#eeeeee')

    dx = 0.1
    middle_lon = boundary_box.middle_lon()
    middle_lat = boundary_box.middle_lat()
    m = Basemap(llcrnrlon=boundary_box.lon_min - dx,
                llcrnrlat=boundary_box.lat_min - dx,
                urcrnrlon=boundary_box.lon_max + dx,
                urcrnrlat=boundary_box.lat_max + dx,
                resolution='i',
                projection='tmerc',
                lon_0=middle_lon,
                lat_0=middle_lat)

    m.drawcoastlines()
    m.fillcontinents(color='grey', lake_color='aqua')

    if total:
        lon, lat = np.meshgrid(lons, lats)
        x, y = m(lon, lat)
    else:
        x, y = m(lons, lats)

    # draw coloured vectors.
    cs = m.quiver(x, y, ust, vst, mod, clim=[0, 0.7], scale=5)

    # add colorbar.
    cbar = m.colorbar(cs, location='bottom', pad="5%")
    cbar.ax.tick_params(labelsize=9)
    cbar.set_label('sea water velocity (m/s)', fontsize=9)

    name_fig = 'imaxe1.png'
    fig.savefig(name_fig,
                dpi=300,
                facecolor='w',
                edgecolor='w',
                format='png',
                transparent=False,
                pad_inches=0.1,
                bbox_inches='tight')

    plt.clf()
    plt.close('all')

    return
Beispiel #33
0
    def animateTraj(self, windAvg, states, trajSteps=3, proj='mill', res='i', instant=0, Dline=5, density=1):
        """
        Animates the trajectory corresponding to the list of states.

        :param Weather windAvg: The weather object corresponding to the trajectory.
        :param list states: List of boat states along its trajectory.
        :param int trajSteps: State step for the animation (a plot update corresponds to trajSteps covered states)
        :param str proj: Projection to be used. Refer to `Basemap <https://matplotlib.org/basemap/api/basemap_api.html#module-mpl_toolkits.basemap>`_
        :param str res: Plot resolution. Refer to `Basemap <https://matplotlib.org/basemap/api/basemap_api.html#module-mpl_toolkits.basemap>`_
        :param int instant: Initial instant of the animation.
        :param int Dline: Lat and lon steps to plot parallels and meridians.
        :param int density: Lat and lon steps to plot quiver.
        :return: Animation function.
        :rtype: `FuncAnimation <https://matplotlib.org/api/_as_gen/matplotlib.animation.FuncAnimation.html>`_

        """
        # to plot whole earth params should be close to res='c',Dline=100,density=10
        # Plot the field using Basemap.  Start with setting the map
        # projection using the limits of the lat/lon data itself:
        fig = plt.figure()
        m = Basemap(projection=proj, lat_ts=10, llcrnrlon=windAvg.lon.min(), \
                    urcrnrlon=windAvg.lon.max(), llcrnrlat=windAvg.lat.min(), urcrnrlat=windAvg.lat.max(), \
                    resolution=res)

        xquiv, yquiv = m(*np.meshgrid(windAvg.lon, windAvg.lat))

        Q = m.quiver(xquiv[0::density, 0::density], yquiv[0::density, 0::density],
                     windAvg.u[instant, 0::density, 0::density], windAvg.v[instant, 0::density, 0::density])

        states = np.array(states)
        posLat = states[:, 1]
        posLon = states[:, 2]
        x, y = m(posLon, posLat)

        T = m.plot(x[0:instant * 3], y[0:instant * 3], linewidth=4)[0]

        m.drawcoastlines()
        m.fillcontinents()
        m.drawmapboundary()
        m.drawparallels(windAvg.lat[0::Dline], labels=[1, 0, 0, 0])
        m.drawmeridians(windAvg.lon[0::2 * Dline], labels=[0, 0, 0, 1])

        def update_quiver(t, Q, T, windAvg):
            """method required to animate quiver and contour plot
            A FAIRE
            """
            Q.set_UVC(windAvg.u[instant + t, 0::density, 0::density * 2],
                      windAvg.v[instant + t, 0::density, 0::density * 2])
            T.set_data(x[0:instant + t * 3], y[0:instant + t * 3])
            plt.title('time : ' + str(windAvg.time[instant + t] - windAvg.time[0]) + ' days')
            return plt

        anim = animation.FuncAnimation(fig, update_quiver, frames=range(int(len(states) / trajSteps)),
                                       fargs=(Q, T, windAvg))

        plt.show()

        return anim
Beispiel #34
0
def contourMap(grdROMS, tlon, tlat, mydata1, mydata2, mydata3, var, mytype,
               currentdate):

    plt.figure(figsize=(10, 10), frameon=False)

    map = Basemap(lon_0=25,
                  boundinglat=50,
                  resolution='l',
                  area_thresh=100.,
                  projection='npstere')

    x, y = map(tlon, tlat)

    map.drawcoastlines()
    map.fillcontinents(color='grey')
    map.drawcountries()

    if var == 'wind':
        levels = np.arange(np.min(mydata3), np.max(mydata3), 0.1)

        CS1 = map.contourf(x,
                           y,
                           mydata3,
                           levels,
                           cmap=cm.get_cmap('RdYlBu_r',
                                            len(levels) - 1))  #,alpha=0.5)
        plt.colorbar(CS1, orientation='vertical', extend='both', shrink=0.5)

        if mytype == "REGSCEN":
            step = 8
        else:
            step = 1
        map.quiver(x[0:-1:step, 0:-1:step],
                   y[0:-1:step, 0:-1:step],
                   mydata1[0:-1:step, 0:-1:step],
                   mydata2[0:-1:step, 0:-1:step],
                   scale=400)

#  plt.title('Var:%s - depth:%s - time:%s'%(var,grdROMS.time))
    plotfile = 'figures/' + str(var) + '_' + str(mytype) + '_time_' + str(
        currentdate) + '.png'
    if not os.path.exists('figures'):
        os.makedirs('figure')
    plt.savefig(plotfile)
    print "Saved figure: %s" % (plotfile)
Beispiel #35
0
def plotear(lllat, urlat, lllon, urlon, dist_lat, dist_lon, Lon, Lat, mapa, bar_min, bar_max, unds, titulo, path, C_T='k', wind=False, mapa_u=None, mapa_v=None): 
    
	# lllat (low-left-lat)   : float con la latitud de la esquina inferior izquierda
	# urlat (uper-right-lat) : float con la latitud de la esquina superior derecha
	# lllon (low-left-lon)   : float con la longitud de la esquina inferior izquierda en coordenas negativas este
	# urlon (uper-right-lon) : float con la longitud de la esquina superior derecha en coordenas negativas este
	# dist_lat               : entero que indica cada cuanto dibujar las lineas de los paralelos
	# dist_lon               : entero que indica cada cuanto dibujar las lineas de los meridianos
	# Lon                    : array de numpy con las longitudes del mapa a plotearse en coordenadas negativas este
	# Lat                    : array de numpy con las longitudes del mapa a plotearse 
	# mapa                   : array de numpy 2D a plotearse con contourf
	# bar_min                : mínimo valor del mapa a plotearse
	# bar_max                : máximo valor del mapa a plotearse
	# unds                   : string de las unidades de la variable que se va a plotear 
	# titulo                 : string del titulo que llevará el mapa
	# path                   : 'string de la dirección y el nombre del archivo que contendrá la figura a generarse'
	# wind                   : boolean que diga si se quiere pintar flechas de viento (corrientes), donde True es que sí se va a hacer
	# mapa_u                 : array de numpay 2D con la componente en x de la velocidad y que será utilizado para pintar las flechas. Este tomara algun valor siempre y cuando wind=True
	# mapa_v                 : array de numpay 2D con la componente en y de la velocidad y que será utilizado para pintar las flechas. Este tomara algun valor siempre y cuando wind=True


	# return                 : gráfica o mapa  

	fig = plt.figure(figsize=(8,8), edgecolor='W',facecolor='W')
	ax = fig.add_axes([0.1,0.1,0.8,0.8])

	map = Basemap(projection='merc', llcrnrlat=lllat, urcrnrlat=urlat, llcrnrlon=lllon, urcrnrlon=urlon, resolution='i')
	map.drawcoastlines(linewidth = 0.8)
	map.drawcountries(linewidth = 0.8)
	map.drawparallels(np.arange(lllat, urlat, dist_lat), labels=[1,0,0,1])
	map.drawmeridians(np.arange(lllon, urlon, dist_lon), labels=[1,0,0,1])

	lons,lats = np.meshgrid(Lon,Lat)
	x,y = map(lons,lats)

	bounds = np.linspace(bar_min, bar_max, 20)
	bounds = np.around(bounds, decimals=2) 

	if wind == False:
		CF1 = map.contourf(x,y,mapa, 20, norm=MidpointNormalize(midpoint=0), cmap= plt.cm.RdYlBu_r, levels=bounds, extend='max')#plt.cm.rainbow , plt.cm.RdYlBu_r
		CF2 = map.contourf(x,y,mapa, 20, norm=MidpointNormalize(midpoint=0), cmap= plt.cm.RdYlBu_r, levels=bounds, extend='min')#plt.cm.rainbow, plt.cm.RdYlBu_r
	else:
		CF1 = map.contourf(x,y,mapa, 20, cmap= plt.cm.jet, levels=bounds, extend='max')#plt.cm.rainbow , plt.cm.RdYlBu_r
		CF2 = map.contourf(x,y,mapa, 20, cmap= plt.cm.jet, levels=bounds, extend='min')#plt.cm.rainbow, plt.cm.RdYlBu_r

	cb1 = plt.colorbar(CF1, orientation='horizontal', pad=0.05, shrink=0.8, boundaries=bounds)
	cb1.set_label(unds)
	cb1.ax.tick_params(labelsize=9) 
	ax.set_title(titulo, size='15', color = C_T)

	if wind == True:
		Q = map.quiver(x[::2,::2], y[::2,::2], mapa_u[::2,::2], mapa_v[::2,::2], scale=150)
		plt.quiverkey(Q, 0.93, 0.05, 10, '10 m/s' )

	#map.fillcontinents(color='white')
	plt.savefig(path+'.png', bbox_inches='tight', dpi=300)
	plt.close('all')
Beispiel #36
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)
Beispiel #37
0
    def plotmap(self):
        '''
        plot stations on map with error ellipses
        ''' '''
        plot the pole on a map
        '''
        #get center of stations
        lons, lats, x, y, = [], [], [], []
        for sta in self.stations:
            if sta.position[0] < 0.0:
                lons.append(sta.position[0] + 360.0)
            else:
                lons.append(sta.position[0])
            lats.append(sta.position[1])
            x.append(sta.velocity[0])
            y.append(sta.velocity[1])
        meanLat = np.mean(lats)
        meanLon = np.mean(lons)
        # set up orthographic map projection
        # use low resolution coastlines.

        map = Basemap(projection='ortho',
                      lat_0=meanLat,
                      lon_0=meanLon,
                      resolution='l')
        # draw coastlines, country boundaries, fill continents.
        map.drawcoastlines(linewidth=0.25)
        map.drawcountries(linewidth=0.25)
        map.fillcontinents(color='coral', lake_color='aqua')
        # draw the edge of the map projection region (the projection limb)
        map.drawmapboundary(fill_color='aqua')
        # draw lat/lon grid lines every 30 degrees
        map.quiver(lons,
                   lats,
                   x,
                   y,
                   angles='uv',
                   scale_units='xy',
                   scale=1E-4,
                   latlon=True,
                   color='k')
        #if self.modeled != None:
        #map.quiver(lons,lats,self.modeled[0:len(self.stations)-1],self.modeled[len(self.stations):-1],angles='uv', scale_units='xy', scale=1E-4,latlon = True,color = 'r')
        plt.show()
Beispiel #38
0
    def plotMultipleQuiver(self,
                           otherWeather,
                           proj='mill',
                           res='i',
                           instant=0,
                           Dline=5,
                           density=1):
        """
        Pretty much the same than :func:`plotQuiver` but to superimpose two quivers.

        :param Weather otherWeather: Second forecasts to be plotted with the one calling the method.
        """
        # Plot the field using Basemap.  Start with setting the map
        # projection using the limits of the lat/lon data itself:
        plt.figure()

        m = Basemap(projection=proj, lat_ts=10, llcrnrlon=self.lon.min(), \
                    urcrnrlon=self.lon.max(), llcrnrlat=self.lat.min(), urcrnrlat=self.lat.max(), \
                    resolution=res)

        x, y = m(*np.meshgrid(self.lon, self.lat))

        m.quiver(x[0::density, 0::density],
                 y[0::density, 0::density],
                 self.u[instant, 0::density, 0::density],
                 self.v[instant, 0::density, 0::density],
                 color='black')

        x, y = m(*np.meshgrid(otherWeather.lon, otherWeather.lat))
        m.quiver(x[0::density, 0::density],
                 y[0::density, 0::density],
                 otherWeather.u[instant, 0::density, 0::density],
                 otherWeather.v[instant, 0::density, 0::density],
                 color='red')
        m.drawcoastlines()
        m.fillcontinents()
        m.drawmapboundary()
        m.drawparallels(self.lat[0::Dline], labels=[1, 0, 0, 0])
        m.drawmeridians(self.lon[0::Dline], labels=[0, 0, 0, 1])
        plt.title('Wind amplitude and direction in [m/s] at time : ' +
                  str(self.time[instant]) + ' days')
        plt.show()

        return plt
Beispiel #39
0
class OceanVelocityFrame(VelocityFrame):
  """ This class extends the Scientific.IO.NetCDFFile library and uses the
  basemap libraries for plotting NetCDF files from NOAA"""
  def __init__(self,filename,mode):
    super(OceanVelocityFrame,self).__init__(filename,mode)  

  def velocities(self):
    mask = -32768
    u = self.masked_array('u',mask)
    v = self.masked_array('v',mask)
    x = self.variables()['lon'][:]
    y = self.variables()['lat'][:]
    return x,y,u[0],v[0]

  def barb_plot_frame(self):
    x,y,u,v = self.__set_map()
    self.__basemap.barbs(x,y,u,v)
    self.__basemap.drawcoastlines()

  def __set_map(self):
    attr = self.nc_attributes()
    lat_min = attr['geospatial_lat_min'][0]
    lat_max = attr['geospatial_lat_max'][0]
    lon_min = attr['geospatial_lon_min'][0]
    lon_max = attr['geospatial_lon_max'][0]

    self.__basemap = Basemap(projection='cyl',
			    llcrnrlat = lat_min,
			    urcrnrlat = lat_max,
			    llcrnrlon = lon_min,
			    urcrnrlon = lon_max,
			    resolution = 'l')

    x,y,u,v = self.velocities()
    x,y = np.meshgrid(x,y)
    return x,y,u,v

  def quiver_plot_frame(self):
    x,y,u,v = self.__set_map()
    self.__basemap.quiver(x,y,u,v)
    self.__basemap.drawcoastlines()
Beispiel #40
0
def plotWind(U200,V200,latitude, longitude, start, stop, yr, year,ens):
    """
    Produces LENS 200mb wind plots that can be used for animations
    
    
    Parameters
    ----------
    temps : historical or future temperature arrays
    latitude : latitude array 
    longitude : longitude array
    start : doy for starting plot
    stop : doy for ending plot
    yr : yr in LENS for plotting
    year : actual year for figure caption
    ens : ensemble member for figure caption
    
    Attributes
    ----------
    climoMarch : function to read in climatologies for temperatures from CESM
    """   
    lons, lats = np.meshgrid(longitude,latitude)
    doy = np.arange(start,stop,1)
    time = ['1','2','3','4','5','6','7','8','9','10']

    meanU = np.mean(U200)
    
    U200 = U200[yr,doy,:,:]    
    V200 = V200[yr,doy,:,:]
    
    speed = np.sqrt(U200**2 + V200**2)
    
    speeds = speed - meanU
    
    for i in xrange(len(doy)):
        plt.figure()
        plt.title('LENS Historic Year %s, Days %s' % (year,doy[i]))
        m = Basemap(projection='merc',llcrnrlon=235.5,llcrnrlat=26,urcrnrlon=298,
            urcrnrlat=54,resolution='l')           
        m.drawstates()
        m.drawcountries()
        m.drawmapboundary(fill_color = 'white')
        m.drawcoastlines(color='black',linewidth=0.5)
        m.drawlsmask(land_color='grey',ocean_color='w')
        x,y = m(lons,lats)
        cs = m.contourf(x,y,speeds[i,:,:],xrange(0,71,1))
        U200s = U200[i,:,:]
        V200s = V200[i,:,:]
        cs1 = m.quiver(x[::3,::3],y[::3,::3],U200s[::3,::3],V200s[::3,::3],scale=450) 
        cbar = m.colorbar(cs,location='bottom',pad='5%')
        cs.set_cmap('gist_ncar')
        cbar.set_label('knots')
        cbar.set_ticks(np.arange(0,80,10))
        plt.savefig('/volumes/eas-shared/ault/ecrl/spring-indices/LENS_SpringOnset/Results/lens_wind_%s.png' % (time[i]), dpi=300)
Beispiel #41
0
def plot_mollyweide(model, vec, val, m, l, v_scale=1.0):
    from mpl_toolkits.basemap import Basemap

    E = model.E
    Nk = model.Nk
    Nl = model.Nl
    th = model.th[0, :]
    ## Calculate vector field and contour field for plotting with basemap
    ## Create full vector grid in theta and phi
    u_1D = model.get_variable(vec, 'vph')[0][0]
    v_1D = model.get_variable(vec, 'vth')[0][0]
    Nph = 2 * Nl
    ph = np.linspace(-180., 180. - 360. / Nph, Nph)
    lon_grid, lat_grid = np.meshgrid(
        ph,
        th * 180. / np.pi - 90.,
    )
    v = ((np.exp(1j * m * lon_grid * np.pi / 180.).T * v_1D).T).real
    u = ((np.exp(1j * m * lon_grid * np.pi / 180.).T * u_1D).T).real
    absu = u.real**2 + v.real**2
    Nvec = np.floor(Nl / 20.)
    ### Plot Mollweide Projection
    plt.figure(figsize=(10, 10))
    ## Set up map
    bmap = Basemap(projection='moll', lon_0=0.)
    bmap.drawparallels(np.arange(-90., 90., 15.))
    bmap.drawmeridians(np.arange(0., 360., 15.))
    ## Convert Coordinates to those used by basemap to plot
    lon, lat = bmap(lon_grid, lat_grid)
    bmap.contourf(lon, lat, absu, 15, cmap=plt.cm.Reds, alpha=0.5)
    bmap.quiver(lon[::Nvec, ::Nvec],
                lat[::Nvec, ::Nvec],
                u[::Nvec, ::Nvec],
                v[::Nvec, ::Nvec],
                scale=v_scale)
    plt.title('MAC, Mollweide Projection Vector Field for m={0}, l={1}'.format(
        m, l))
    plt.savefig(
        './output/m={1}/MAC_MollweideVectorField_m={1}_l={2}.png'.format(
            val.imag, m, l))
Beispiel #42
0
    def plotQuiver(self, proj='mill', res='i', instant=0, Dline=5, density=1):
        """
        Plots a quiver of the :any:`Weather` object's wind for a given instant. Basemap projection using the lat/lon limits of the data itself.


        :param str proj: `Basemap <https://matplotlib.org/basemap/api/basemap_api.html#module-mpl_toolkits.basemap>`_ projection method.
        :param str res: `Basemap <https://matplotlib.org/basemap/api/basemap_api.html#module-mpl_toolkits.basemap>`_ resolution.
        :param int instant: Time index at which the wind should be displayed.
        :param int Dline: Lat and lon steps to plot parallels and meridians.
        :param int density: Lat and lon steps to plot quiver.

        :return: Plot framework.
        :rtype: `pyplot <https://matplotlib.org/api/pyplot_api.html>`_

        """

        # Start with setting the map.
        # projection using the limits of the lat/lon data itself:
        plt.figure()

        m = Basemap(projection=proj, lat_ts=10, llcrnrlon=self.lon.min(), \
                    urcrnrlon=self.lon.max(), llcrnrlat=self.lat.min(), urcrnrlat=self.lat.max(), \
                    resolution=res)

        x, y = m(*np.meshgrid(self.lon, self.lat))

        m.quiver(x[0::density, 0::density], y[0::density, 0::density],
                 self.u[instant, 0::density,
                        0::density], self.v[instant, 0::density, 0::density])
        m.drawcoastlines()
        m.fillcontinents()
        m.drawmapboundary()
        m.drawparallels(self.lat[0::Dline], labels=[1, 0, 0, 0])
        m.drawmeridians(self.lon[0::Dline], labels=[0, 0, 0, 1])

        plt.title('Wind amplitude and direction in [m/s] at time : ' +
                  str(self.time[instant]) + ' days')
        plt.show()

        return m
Beispiel #43
0
def map_velocity(xr, yr, u, v, variable_name, title, option, name_file):
    # map all Atlantic and Arctic Ocean
    # colorbar under the map:
    # Ice thickness, Temperature or Salinity
    # year: age of the data
    # time: month? yearly mean?
    m = Basemap(projection='lcc',
                resolution='l',
                lon_0=-20,
                lat_0=90,
                lat_1=89.999,
                lat_2=50,
                width=0.4E7,
                height=0.4E7)

    x, y = m(xr, yr)

    plt.figure(figsize=(10, 6))
    plt.rc('text', usetex=True)
    plt.rc('font', family='serif')
    fig, ax = plt.subplots()

    m.drawcoastlines(linewidth=0.5)
    m.fillcontinents(color='0.8')

    yy = np.arange(0, y.shape[0], 4)
    xx = np.arange(0, x.shape[1], 4)

    points = np.meshgrid(yy, xx)
    speed = np.sqrt(u**2 + v**2)
    m.quiver(x[points], y[points],\
     u[points], v[points], speed[points],\
     cmap=plt.cm.autumn, scale=1)

    plt.title(str(title))
    plt.savefig(
        str(variable_name) + '/' + str(name_file.replace(".", "")) + '.png')
    plt.close(fig)
    return
Beispiel #44
0
def basemap_barbs_mercator(u,v,lat,lon):

    # lon/lat extents
    lons = (np.amin(lon), np.amax(lon))
    lats = (np.amin(lat), np.amax(lat))

    # construct spherical mercator projection for region of interest
    m = Basemap(projection='merc',llcrnrlat=lats[0], urcrnrlat=lats[1],
                llcrnrlon=lons[0],urcrnrlon=lons[1])

    #vmin,vmax = np.nanmin(grid),np.nanmax(grid)
    fig = plt.figure(frameon=False,figsize=(12,8),dpi=72*4)
    plt.axis('off')
    m.quiver(lon,lat,u,v,latlon=True)

    str_io = StringIO.StringIO()
    plt.savefig(str_io,bbox_inches='tight',format='png',pad_inches=0,transparent=True)
    plt.close()

    numpy_bounds = [ (lons[0],lats[0]),(lons[1],lats[0]),(lons[1],lats[1]),(lons[0],lats[1]) ]
    float_bounds = [ (float(x), float(y)) for x,y in numpy_bounds ]
    return str_io.getvalue(), float_bounds
Beispiel #45
0
    def plotColorQuiver(self,
                        proj='mill',
                        res='i',
                        instant=0,
                        Dline=5,
                        density=1):
        """
        Pretty much the same than :func:`plotQuiver` but on a contour plot of wind magnitude.
        """
        # Plot the field using Basemap.  Start with setting the map
        # projection using the limits of the lat/lon data itself:

        font = {'family': 'normal', 'weight': 'bold', 'size': 22}

        matplotlib.rc('font', **font)
        plt.figure()

        m = Basemap(projection=proj, lat_ts=10, llcrnrlon=self.lon.min(), \
                    urcrnrlon=self.lon.max(), llcrnrlat=self.lat.min(), urcrnrlat=self.lat.max(), \
                    resolution=res)

        x, y = m(*np.meshgrid(self.lon, self.lat))
        m.pcolormesh(x, y, self.wMag[instant], shading='flat', cmap=plt.cm.jet)
        m.quiver(x[0::density, 0::density], y[0::density, 0::density],
                 self.u[instant, 0::density,
                        0::density], self.v[instant, 0::density, 0::density])
        cbar = m.colorbar(location='right')
        cbar.ax.set_ylabel('wind speed m/s')
        m.drawcoastlines()
        m.fillcontinents()
        m.drawmapboundary()
        m.drawparallels(self.lat[0::Dline], labels=[1, 0, 0, 0])
        m.drawmeridians(self.lon[0::Dline], labels=[0, 0, 0, 1])
        plt.title('Wind amplitude and direction in [m/s] at time : ' +
                  str(self.time[instant]) + ' days')
        plt.show()

        return plt
Beispiel #46
0
    def polar_quiver_wind(self, ax, ns='N'):
        # Wind vector in lat-long coordinates.
        # For different map projections, the arithmetics to calculate xywind
        # are different
        if self.empty:
            return
        from mpl_toolkits.basemap import Basemap
        from apexpy import Apex
        # Creat polar coordinates
        projection,fc = ('npstere',1) if ns=='N' else ('spstere',-1)
        m = Basemap(projection=projection,boundinglat=fc*40,lon_0=0,resolution='l')
        m.drawcoastlines(color='gray',zorder=1)
        m.fillcontinents(color='lightgray',zorder=0)
        dt = self.index.min() + (self.index.max()-self.index.min())/2
        m.nightshade(dt,zorder=2)
        #m.drawparallels(np.arange(-80,81,20))
        #m.drawmeridians(np.arange(-180,181,60),labels=[1,1,1,1])

        # Calculate mlat and mlon
        lat_grid = np.arange(-90,91,10)
        lon_grid = np.arange(-180,181,10)
        lon_grid, lat_grid = np.meshgrid(lon_grid, lat_grid)
        gm = Apex(date=2005)
        mlat,mlon = gm.convert(lat_grid,lon_grid,'geo','apex')
        hc1 = m.contour(lon_grid,lat_grid,mlat,levels=np.arange(-90,91,10),
                        colors='k', zorder=3, linestyles='dashed',
                        linewidths=1, latlon=True)
        # hc2 = m.contour(lon_grid,lat_grid,mlon,levels=np.arange(-180,181,45),
        #                 colors='k', zorder=3, linestyles='dashed', latlon=True)
        plt.clabel(hc1,inline=True,colors='k',fmt='%d')
        # plt.clabel(hc2,inline=True,colors='k',fmt='%d')

        # Calculate and plot x and y winds
        lat = self.lat
        lon = self.long
        wind = self.wind
        winde1 = self.winde
        winde = winde1*wind
        windn1 = self.windn
        windn = windn1*wind
        # only appropriate for the npstere and spstere
        xwind = fc*winde*np.cos(lon/180*np.pi)-windn*np.sin(lon/180*np.pi)
        ywind = winde*np.sin(lon/180*np.pi)+fc*windn*np.cos(lon/180*np.pi)
        hq = m.quiver(np.array(lon),np.array(lat),xwind,ywind,color='blue',
                      scale=300, scale_units='inches',zorder=3, latlon=True)
        #plt.quiverkey(hq,1.05,1.05,100,'100 m/s',coordinates='axes',labelpos='E')
        #m.scatter(np.array(lon),np.array(lat),
        #          s=50, c=self.index.to_julian_date(),linewidths=0, zorder=4,latlon=True)
        return m
Beispiel #47
0
def spatial_plot(profiles, levels, llcrnrlat, urcrnrlat,
            llcrnrlon, urcrnrlon, title=None):
    """
    Make a spatial plot with stacked
    Parameters
    ----------
    profiles - list of vad objects to plot
    levels - dict with levels to plot as key and color to plot for that level as the item
    title - Title to put on plot

    Returns
    -------

    """

    handles = []

    # Set up base map
    m = Basemap(projection='merc', llcrnrlat=llcrnrlat, urcrnrlat=urcrnrlat,
                llcrnrlon=llcrnrlon, urcrnrlon=urcrnrlon)
    m.drawcoastlines()
    m.drawstates()

    for level, color in levels.iteritems():
        lats = []
        lons = []
        u = []
        v = []

        for profile in profiles:
            lats.append(profile.lat)
            lons.append(profile.lon)

            u_tmp, v_tmp = profile.get_data_nearest_height(level)
            u.append(u_tmp)
            v.append(v_tmp)

            del u_tmp, v_tmp
        try:
            # h = m.barbs(lons, lats, u, v, latlon=True, color=color, label=level, length=10)
            h = m.quiver(lons, lats, u, v, units='inches', scale=20, scale_units='inches',
                         latlon=True, color=color, label=level, width=.02)
            handles.append(h)
        except IndexError:
            pass

    return handles
Beispiel #48
0
def reconstruction_plot_pcolor(lats, lons, data_cube, lvl_num, parm, u, v,w, angs, mask, **kwargs):
	ber_loc=[-12.4, 130.85] #location of Berrimah radar
	gp_loc=[-12.2492,  131.0444]#location of CPOL at Gunn Point
	box=kwargs.get('box',[130.0, 132.0, -13.0, -11.5])#box for the plot
	bquiver=kwargs.get('bquiver', [0.1, 0.75])
	ksp=kwargs.get('ksp', 0.05)
	#Set up the map and projection
	mapobj= Basemap(projection='merc',lat_0=(box[2]+box[3])/2.0, lon_0=(box[0]+box[1])/2.0,llcrnrlat=box[2], llcrnrlon=box[0], urcrnrlat=box[3] , urcrnrlon=box[1], resolution='l',area_thresh=1., lat_ts=(box[2]+box[3])/2.0)
	#map.drawmapboundary()
	um=M.masked_where(M.array(mask) < 0.5, M.array(u))
	vm=M.masked_where(M.array(mask) < 0.5, M.array(v))
	mag=M.array(sqrt(u**2+v**2))
	magm=M.masked_where(M.array(mask)<0.5, mag)
	fig_name=kwargs.get('fig_name', 'recon_'+parm+'_.png')
	longr, latgr=meshgrid(lons,lats)
	xx, yy = mapobj(longr, latgr)
	mapobj.drawmapboundary()
	mapobj.readshapefile(getenv('HOME')+'/bom_mds/shapes/cstntcd_r','coast',drawbounds=True, linewidth=0.5,color='k',antialiased=1,ax=None)
	mapobj.readshapefile(getenv('HOME')+'/bom_mds/shapes/cstqldmd_r', 'qcoast',drawbounds=True, linewidth=0.5,color='k',antialiased=1,ax=None)
	#mapobj.drawmeridians(array([130,130.5, 131, 131.5, 132]), labels=[1,0,0,1])
	#mapobj.drawparallels(array([-13,-12.5,-12,-11.5,-11]), labels=[1,0,0,1])
	data=M.masked_where(M.array(mask) < 0.5, M.array(data_cube[parm][:,:,lvl_num]))
	if parm in ['diff']:
		data=M.masked_where(M.array(mask) < 0.5, M.array(data))
	comp_levs=linspace(-1.,1., 30)
	levs_dict={'VR':linspace(-25,25,51), 'CZ': linspace(-8,64,10), 'i_comp':comp_levs,'j_comp':comp_levs,'k_comp':comp_levs,'diff':linspace(-15,15,31), 'VE':linspace(-25,25,51)}
	titles_dict={'VR': 'Radial velocity m/s', 'CZ':'Corrected Reflectivity dBz', 'TEST':'TEST', 'i_comp':'i component','j_comp':'j component','k_comp':'k component', 'diff':'diff', 'VE':'Edited velocity'}
	mapobj.pcolor(xx,yy,data, vmin=levs_dict[parm].min(), vmax=levs_dict[parm].max())
	colorbar()
	#mapobj.quiver(xx,yy,u/sqrt(u**2+v**2),v/sqrt(u**2+v**2), scale=50)
	qq=mapobj.quiver(xx,yy,um,vm, scale=kwargs.get('qscale', 200))
	quiverkey(qq, bquiver[0], bquiver[1]+2.*ksp, 10, '10 m/s', coordinates='figure',fontproperties={'size':rcParams['xtick.labelsize']})
	print bquiver[0], bquiver[1]+2.*ksp
	quiverkey(qq, bquiver[0], bquiver[1]+ksp, 5, '5 m/s', coordinates='figure',fontproperties={'size':rcParams['xtick.labelsize']})
	quiverkey(qq, bquiver[0], bquiver[1], 2, '2 m/s', coordinates='figure',fontproperties={'size':rcParams['xtick.labelsize']})
	cobject=mapobj.contour(xx,yy,w, colors=['k'], levels=linspace(-10,10,6))
	fon = { 'fontname':'Tahoma', 'fontsize':5 }
	clabel(cobject, fmt="%1.1f", **fon)
	mapobj.contour(xx,yy,angs, levels=[30.0, 150.0],colors=['r']) 
	mapobj.readshapefile(getenv('HOME')+'/bom_mds/shapes/nt_coast','coast',drawbounds=True, linewidth=0.5,color='k',antialiased=1,ax=None)
	mapobj.drawmeridians(linspace(0,4,41)+130., labels=[1,0,0,1], fontsize=rcParams['xtick.labelsize'])
	mapobj.drawparallels(linspace(0,4,41)-15.0, labels=[1,0,0,1], fontsize=rcParams['ytick.labelsize'])
	return mapobj
             plt_v = np.ma.masked_outside(mean_var[:,:,-(s+1)], clevpt_max+20,  clevpt_min-20)

             cs_col = m.contourf(x,y, plt_v,  np.linspace(clevpt_min, clevpt_max), cmap=plt.cm.RdBu_r, extend='both')
             cbar = m.colorbar(cs_col,location='bottom',pad="5%", format = '%d')  
             cbar.set_label('K')  
             plt.suptitle('Height, Potential Temperature and Wind Vectors at %s hPa'% (p), fontsize=10)  

        elif plot_diag=='sp_hum':
             plt_v = np.ma.masked_outside(mean_var[:,:,-(s+1)], clevsh_max+20,  clevsh_min-20)

             cs_col = m.contourf(x,y, plt_v,  np.linspace(clevsh_min, clevsh_max), cmap=plt.cm.RdBu_r, extend='both')
             cbar = m.colorbar(cs_col,location='bottom',pad="5%", format = '%.3f') 
             cbar.set_label('kg/kg')
             plt.suptitle('Height, Specific Humidity and Wind Vectors at %s hPa'% (p), fontsize=10) 

        wind = m.quiver(x_w,y_w, u, v, scale=400, color='#262626')
        qk = plt.quiverkey(wind, 0.1, 0.1, 5, '5 m/s', labelpos='W')
                
        plt.clabel(cs_lin, fontsize=10, fmt='%d', color='black')

        #plt.title('%s\n%s' % (m_title, model_name_convert_title.main(experiment_id)), fontsize=10)
        plt.title('\n'.join(wrap('%s' % (model_name_convert_title.main(experiment_id)), 80)), fontsize=10)

        plt.show()  
        if not os.path.exists('/nfs/a90/eepdw/Mean_State_Plot_Data/Figures/%s/%s'  % (experiment_id, plot_diag)): os.makedirs('/nfs/a90/eepdw/Mean_State_Plot_Data/Figures/%s/%s'  % (experiment_id, plot_diag))
        #plt.savefig('/nfs/a90/eepdw/Mean_State_Plot_Data/Figures/%s/%s/geop_height_%shPa_%s_%s.png' % (experiment_id, plot_diag, p, experiment_id, plot_diag), format='png', bbox_inches='tight')




if __name__ == '__main__':
Beispiel #50
0
    def show_velocity(self, **kwargs):
        # time at which to plot velocity
        t = kwargs.get('t', None)
        if t is None:
            t = self.particles[0].time
        # flag to drawing land on plot
        land = kwargs.get('land', False)
        # plot domain latitude longitude parameters
        latN = kwargs.get('latN', np.nan)
        latS = kwargs.get('latS', np.nan)
        lonE = kwargs.get('lonE', np.nan)
        lonW = kwargs.get('lonW', np.nan)
        # maximum speed for vector coloring
        vmax = kwargs.get('vmax', None)
        # filename to saving to
        savefile = kwargs.get('savefile', None)

        if isinstance(t, datetime):
            t = (t - self.grid.U.time_origin).total_seconds()
        if isinstance(t, delta):
            t = t.total_seconds()

        if not np.isnan(latN):
            latN = nearest_index(self.grid.U.lat, latN)
            latS = nearest_index(self.grid.U.lat, latS)
            lonE = nearest_index(self.grid.U.lon, lonE)
            lonW = nearest_index(self.grid.U.lon, lonW)
            lon = self.grid.U.lon[lonW:lonE]
            lat = self.grid.U.lat[latS:latN]
        else:
            lon = self.grid.U.lon
            lat = self.grid.U.lat

        # time interpolation of velocity field
        idx = self.grid.U.time_index(t)
        U = np.array(self.grid.U.temporal_interpolate_fullfield(idx, t))
        V = np.array(self.grid.V.temporal_interpolate_fullfield(idx, t))
        if not np.isnan(latN):
            U = U[latS:latN, lonW:lonE]
            V = V[latS:latN, lonW:lonE]

        # configuring plot
        lat_median = np.median(lat)
        lon_median = np.median(lon)
        plt.figure()
        m = Basemap(projection='merc', lat_0=lat_median, lon_0=lon_median,
                    resolution='h', area_thresh=100,
                    llcrnrlon=lon[0], llcrnrlat=lat[0],
                    urcrnrlon=lon[-1], urcrnrlat=lat[-1])
        if land:
            m.drawcoastlines()
            m.fillcontinents(color='burlywood')
        parallels = np.arange(lat[0], lat[-1], abs(lat[0]-lat[-1])/5)
        parallels = np.around(parallels, 2)
        m.drawparallels(parallels, labels=[1, 0, 0, 0])
        meridians = np.arange(lon[0], lon[-1], abs(lon[0]-lon[-1])/5)
        meridians = np.around(meridians, 2)
        m.drawmeridians(meridians, labels=[0, 0, 0, 1])

        # formating velocity data for quiver plotting
        U = np.array([U[y, x] for x in range(len(lon)) for y in range(len(lat))])
        V = np.array([V[y, x] for x in range(len(lon)) for y in range(len(lat))])
        speed = np.sqrt(U**2 + V**2)
        normU = U/speed
        normV = V/speed
        x = np.repeat(lon, len(lat))
        y = np.tile(lat, len(lon))

        # plotting velocity vector field
        vecs = m.quiver(x, y, normU, normV, speed, cmap=plt.cm.gist_ncar, clim=[0, vmax], scale=50, latlon=True)
        cb = m.colorbar(vecs, "right", size="5%", pad="2%")
        plon = [p.lon for p in self]
        plat = [p.lat for p in self]
        xs, ys = m(plon, plat)
        # plotting particle data
        m.scatter(xs, ys, color='black')

        if(self.grid.U.time_origin == 0):
            plt.title(delta(seconds=t))
        else:
            plt.title(netCDF4.num2date(t, 'seconds since '+str(self.grid.U.time_origin)))

        if savefile is None:
            plt.show()
        else:
            plt.savefig(savefile)
            plt.close()
Beispiel #51
0
 CS = m.contour(x, y, slp[nt, :, :], clevs, linewidths=0.5, colors="k", animated=True)
 CS = m.contourf(x, y, slp[nt, :, :], clevs, cmap=plt.cm.RdBu_r, animated=True)
 # plot wind vectors on lat/lon grid.
 # rotate wind vectors to map projection coordinates.
 # urot,vrot = m.rotate_vector(u[nt,:,:],v[nt,:,:],lons,lats)
 # plot wind vectors over map.
 # Q = m.quiver(x,y,urot,vrot,scale=500)
 # plot wind vectors on projection grid (looks better).
 # first, shift grid so it goes from -180 to 180 (instead of 0 to 360
 # in longitude).  Otherwise, interpolation is messed up.
 ugrid, newlons = shiftgrid(180.0, u[nt, :, :], longitudes, start=False)
 vgrid, newlons = shiftgrid(180.0, v[nt, :, :], longitudes, start=False)
 # transform vectors to projection grid.
 urot, vrot, xx, yy = m.transform_vector(ugrid, vgrid, newlons, latitudes, 51, 51, returnxy=True, masked=True)
 # plot wind vectors over map.
 Q = m.quiver(xx, yy, urot, vrot, scale=500)
 # make quiver key.
 qk = plt.quiverkey(Q, 0.1, 0.1, 20, "20 m/s", labelpos="W")
 # draw coastlines, parallels, meridians, title.
 m.drawcoastlines(linewidth=1.5)
 m.drawparallels(parallels)
 m.drawmeridians(meridians)
 plt.title("SLP and Wind Vectors " + str(date))
 if nt == 0:  # plot colorbar on a separate axes (only for first frame)
     cax = plt.axes([l + w - 0.05, b, 0.03, h])  # setup colorbar axes
     fig.colorbar(CS, drawedges=True, cax=cax)  # draw colorbar
     cax.text(0.0, -0.05, "mb")
     plt.axes(ax)  # reset current axes
 plt.draw()  # draw the plot
 # save first and last frame n1 times
 # (so gif animation pauses at beginning and end)
def main():
    def unrotate_pole(rotated_lons, rotated_lats, pole_lon, pole_lat):
     """
      Convert rotated-pole lons and lats to unrotated ones.

      Example::

      lons, lats = unrotate_pole(grid_lons, grid_lats, pole_lon, pole_lat)

      .. note:: Uses proj.4 to perform the conversion.

      """
     src_proj = ccrs.RotatedGeodetic(pole_longitude=pole_lon,
                                    pole_latitude=pole_lat)
     target_proj = ccrs.Geodetic()
     res = target_proj.transform_points(x=rotated_lons, y=rotated_lats,
                                       src_crs=src_proj)
     unrotated_lon = res[..., 0]
     unrotated_lat = res[..., 1]

     return unrotated_lon, unrotated_lat

# Set rotated pole longitude and latitude, not ideal but easier than trying to find how to get iris to tell me what it is.

    plot_levels = [925, 850, 700, 500] 
    #plot_levels = [925] 
    experiment_id = 'djznw'

    p_levels = [1000, 950, 925, 850, 700, 500, 400, 300, 250, 200, 150, 100, 70, 50, 30, 20, 10]
    expmin1 = experiment_id[:-1]

    plot_type='mean'

#    for  pl in plot_diags:
    plot_diag='temp'
    fname_h = '/projects/cascade/pwille/temp/408_pressure_levels_interp_pressure_%s_%s' % (experiment_id, plot_type)
    fname_d = '/projects/cascade/pwille/temp/%s_pressure_levels_interp_%s_%s' % (plot_diag, experiment_id, plot_type)
    print fname_h
    print fname_d
#  Height data file
    with h5py.File(fname_h, 'r') as i:
        mh = i['%s' % plot_type]
        mean_heights = mh[. . .]
    print mean_heights.shape
    with h5py.File(fname_d, 'r') as i:
        mh = i['%s' % plot_type]
        mean_var = mh[. . .]
    print mean_var.shape
    
    #lon_low= 60
    #lon_high = 105
    #lat_low = -10
    #lat_high = 30

    f_oro =  '/projects/cascade/pwille/moose_retrievals/%s/%s/33.pp' % (expmin1, experiment_id)
    oro = iris.load_cube(f_oro)

    print oro
    for i, coord in enumerate (oro.coords()):
        if coord.standard_name=='grid_latitude':
            lat_dim_coord_oro = i
        if coord.standard_name=='grid_longitude':
            lon_dim_coord_oro = i

    fu = '/projects/cascade/pwille/moose_retrievals/%s/%s/30201_mean.pp' % (expmin1, experiment_id)
       
    u_wind,v_wind = iris.load(fu)
    
# Wind may have different number of grid points so need to do this twice 

    lat_w = u_wind.coord('grid_latitude').points
    lon_w = u_wind.coord('grid_longitude').points
    p_levs = u_wind.coord('pressure').points

    lat = oro.coord('grid_latitude').points
    lon = oro.coord('grid_longitude').points
    
    cs_w = u_wind.coord_system('CoordSystem')
    cs = oro.coord_system('CoordSystem')

    if isinstance(cs_w, iris.coord_systems.RotatedGeogCS):
        print ' Wind - %s - Unrotate pole %s' % (experiment_id, cs_w)
        lons_w, lats_w = np.meshgrid(lon_w, lat_w)
        lons_w,lats_w = unrotate_pole(lons_w,lats_w, cs_w.grid_north_pole_longitude, cs_w.grid_north_pole_latitude)
        
        lon_w=lons_w[0]
        lat_w=lats_w[:,0]

        csur_w=cs_w.ellipsoid

        for i, coord in enumerate (u_wind.coords()):
            if coord.standard_name=='grid_latitude':
                lat_dim_coord_uwind = i
            if coord.standard_name=='grid_longitude':
                lon_dim_coord_uwind = i
       
        u_wind.remove_coord('grid_latitude')
        u_wind.remove_coord('grid_longitude')
        u_wind.add_dim_coord(iris.coords.DimCoord(points=lat_w, standard_name='grid_latitude', units='degrees', coord_system=csur_w),lat_dim_coord_uwind )
        u_wind.add_dim_coord(iris.coords.DimCoord(points=lon_w, standard_name='grid_longitude', units='degrees', coord_system=csur_w), lon_dim_coord_uwind)

        v_wind.remove_coord('grid_latitude')
        v_wind.remove_coord('grid_longitude')
        v_wind.add_dim_coord(iris.coords.DimCoord(points=lat_w, standard_name='grid_latitude', units='degrees', coord_system=csur_w), lat_dim_coord_uwind)
        v_wind.add_dim_coord(iris.coords.DimCoord(points=lon_w, standard_name='grid_longitude', units='degrees', coord_system=csur_w),lon_dim_coord_uwind )
        
    if isinstance(cs, iris.coord_systems.RotatedGeogCS):
        print ' 33.pp  - %s - Unrotate pole %s' % (experiment_id, cs)
        lons, lats = np.meshgrid(lon, lat)      
        
        lon_low= np.min(lons)
        lon_high = np.max(lons)
        lat_low = np.min(lats)
        lat_high = np.max(lats)

        lon_corners, lat_corners = np.meshgrid((lon_low, lon_high), (lat_low, lat_high))
        lons,lats = unrotate_pole(lons,lats, cs.grid_north_pole_longitude, cs.grid_north_pole_latitude)
        lon_corner_u,lat_corner_u = unrotate_pole(lon_corners, lat_corners, cs.grid_north_pole_longitude, cs.grid_north_pole_latitude)
        #lon_highu,lat_highu = unrotate_pole(lon_high, lat_high, cs.grid_north_pole_longitude, cs.grid_north_pole_latitude)

        lon=lons[0]
        lat=lats[:,0]

        lon_low = lon_corner_u[0,0]
        lon_high = lon_corner_u[0,1]
        lat_low = lat_corner_u[0,0]
        lat_high = lat_corner_u[1,0]

        for i, coord in enumerate (oro.coords()):
            if coord.standard_name=='grid_latitude':
                lat_dim_coord_oro = i
            if coord.standard_name=='grid_longitude':
                lon_dim_coord_oro = i

        csur=cs.ellipsoid     
        oro.remove_coord('grid_latitude')
        oro.remove_coord('grid_longitude')
        oro.add_dim_coord(iris.coords.DimCoord(points=lat, standard_name='grid_latitude', units='degrees', coord_system=csur), lat_dim_coord_oro)
        oro.add_dim_coord(iris.coords.DimCoord(points=lon, standard_name='grid_longitude', units='degrees', coord_system=csur), lon_dim_coord_oro)

    else:

        lons, lats = np.meshgrid(lon, lat)
        lons_w, lats_w = np.meshgrid(lon_w, lat_w)

        lon_low= np.min(lons)
        lon_high = np.max(lons)
        lat_low = np.min(lats)
        lat_high = np.max(lats)


######## Regrid to global, and difference  #######
############################################################################
##  Heights
    f_glob_h = '/projects/cascade/pwille/temp/408_pressure_levels_interp_pressure_djznw_%s' % (plot_type)
    f_glob_d = '/projects/cascade/pwille/temp/%s_pressure_levels_interp_djznw_%s' % (plot_diag, plot_type)

    with h5py.File(f_glob_h, 'r') as i:
        mh = i['%s' % plot_type]
        mean_heights_global = mh[. . .]
    with h5py.File(f_glob_d, 'r') as i:
        mh = i['%s' % plot_type]
        mean_var_global = mh[. . .]

# Wind
    fw_global = '/projects/cascade/pwille/moose_retrievals/djzn/djznw/30201_mean.pp'
    fo_global = '/projects/cascade/pwille/moose_retrievals/djzn/djznw/33.pp'
    
    u_global,v_global = iris.load(fw_global)
    oro_global = iris.load_cube(fo_global)
    
# Unrotate global coordinates

    cs_glob = u_global.coord_system('CoordSystem')
    cs_glob_v = v_global.coord_system('CoordSystem')

    cs_glob_oro = oro_global.coord_system('CoordSystem')

    lat_g = u_global.coord('grid_latitude').points
    lon_g = u_global.coord('grid_longitude').points

    lat_g_oro = oro_global.coord('grid_latitude').points
    lon_g_oro = oro_global.coord('grid_longitude').points
    
    if cs_glob!=cs_glob_v:
        print 'Global model u and v winds have different poles of rotation'

# Unrotate global winds

    if isinstance(cs_glob, iris.coord_systems.RotatedGeogCS):
        print ' Global Model - Winds - djznw - Unrotate pole %s' % cs_glob
        lons_g, lats_g = np.meshgrid(lon_g, lat_g)
        lons_g,lats_g = unrotate_pole(lons_g,lats_g, cs_glob.grid_north_pole_longitude, cs_glob.grid_north_pole_latitude)
        
        lon_g=lons_g[0]
        lat_g=lats_g[:,0]

        for i, coord in enumerate (u_global.coords()):
            if coord.standard_name=='grid_latitude':
                lat_dim_coord_uglobal = i
            if coord.standard_name=='grid_longitude':
                lon_dim_coord_uglobal = i

        csur_glob=cs_glob.ellipsoid
        u_global.remove_coord('grid_latitude')
        u_global.remove_coord('grid_longitude')
        u_global.add_dim_coord(iris.coords.DimCoord(points=lat_g, standard_name='grid_latitude', units='degrees', coord_system=csur_glob), lat_dim_coord_uglobal)
        u_global.add_dim_coord(iris.coords.DimCoord(points=lon_g, standard_name='grid_longitude', units='degrees', coord_system=csur_glob), lon_dim_coord_uglobal)

        #print u_global
    
        v_global.remove_coord('grid_latitude')
        v_global.remove_coord('grid_longitude')
        v_global.add_dim_coord(iris.coords.DimCoord(points=lat_g, standard_name='grid_latitude', units='degrees', coord_system=csur_glob),  lat_dim_coord_uglobal)
        v_global.add_dim_coord(iris.coords.DimCoord(points=lon_g, standard_name='grid_longitude', units='degrees', coord_system=csur_glob),  lon_dim_coord_uglobal)
    
        #print v_global
# Unrotate global model

    if isinstance(cs_glob_oro, iris.coord_systems.RotatedGeogCS):
        print ' Global Model - Orography - djznw - Unrotate pole %s - Winds and other diagnostics may have different number of grid points' % cs_glob_oro
        lons_go, lats_go = np.meshgrid(lon_g_oro, lat_g_oro)
        lons_go,lats_go = unrotate_pole(lons_go,lats_go, cs_glob_oro.grid_north_pole_longitude, cs_glob_oro.grid_north_pole_latitude)
        
        lon_g_oro=lons_go[0]
        lat_g_oro=lats_go[:,0]

        for i, coord in enumerate (oro_global.coords()):
            if coord.standard_name=='grid_latitude':
                lat_dim_coord_og = i
            if coord.standard_name=='grid_longitude':
                lon_dim_coord_og = i 

        csur_glob_oro=cs_glob_oro.ellipsoid
        oro_global.remove_coord('grid_latitude')
        oro_global.remove_coord('grid_longitude')
        oro_global.add_dim_coord(iris.coords.DimCoord(points=lat_g_oro, standard_name='grid_latitude', units='degrees', coord_system=csur_glob_oro), lat_dim_coord_og)
        oro_global.add_dim_coord(iris.coords.DimCoord(points=lon_g_oro, standard_name='grid_longitude', units='degrees', coord_system=csur_glob_oro), lon_dim_coord_og)
    

############## Regrid and Difference #################################

  # Regrid Height and Temp/Specific humidity to global grid
    h_regrid = np.empty((len(lat_g_oro), len(lon_g_oro), len(p_levels)))
    v_regrid = np.empty((len(lat_g_oro), len(lon_g_oro), len(p_levels)))

    for y in range(len(p_levels)):
   
        h_regrid[:,:,y] = scipy.interpolate.griddata((lats.flatten(),lons.flatten()),mean_heights[:,:,y].flatten() , (lats_go,lons_go),method='cubic')
 

        v_regrid[:,:,y] = scipy.interpolate.griddata((lats.flatten(),lons.flatten()),mean_var[:,:,y].flatten() , (lats_go,lons_go),method='cubic')
   
# Difference heights

    mean_heights = np.where(np.isnan(h_regrid), np.nan, h_regrid - mean_heights_global)

#Difference temperature/specific humidity
   
    mean_var = np.where(np.isnan(v_regrid), np.nan, v_regrid - mean_var_global)

# Difference winds

    u_wind_regrid = iris.analysis.interpolate.regrid(u_wind, u_global, mode='bilinear')
    v_wind_regrid = iris.analysis.interpolate.regrid(v_wind, v_global, mode='bilinear')
    u_wind=u_wind_regrid-u_global
    v_wind=v_wind_regrid-v_global
   
#######################################################################################
# 2 degree lats lon lists for wind regridding on plot
    lat_wind_1deg = np.arange(lat_low,lat_high, 2)
    lon_wind_1deg = np.arange(lon_low,lon_high, 2)

    lons_w,lats_w = np.meshgrid(lon_wind_1deg, lat_wind_1deg)

    for p in plot_levels:

        m_title = 'Height of %s-hPa level (m)' % (p)

# Set pressure height contour min/max
        if p == 925:
            clev_min = -24.
            clev_max = 24.
        elif p == 850:
            clev_min = -24.
            clev_max = 24.
        elif p == 700:
            clev_min = -24.
            clev_max = 24.
        elif p == 500:
            clev_min = -24.
            clev_max = 24.
        else:
            print 'Contour min/max not set for this pressure level'

# Set potential temperature min/max       
        if p == 925:
            clevpt_min = -3.
            clevpt_max = 3.
        elif p == 850:
            clevpt_min = -3.
            clevpt_max = 3.
        elif p == 700:
            clevpt_min = -3.
            clevpt_max = 3.
        elif p == 500:
            clevpt_min = -3.
            clevpt_max = 3.
        else:
            print 'Potential temperature min/max not set for this pressure level'

 # Set specific humidity min/max       
        if p == 925:
            clevsh_min = -0.0025
            clevsh_max = 0.0025
        elif p == 850:
            clevsh_min = -0.0025
            clevsh_max = 0.0025
        elif p == 700:
            clevsh_min = -0.0025
            clevsh_max = 0.0025
        elif p == 500:
            clevsh_min = -0.0025
            clevsh_max = 0.0025
        else:
            print 'Specific humidity min/max not set for this pressure level'

       #clevs_col = np.arange(clev_min, clev_max)
        clevs_lin = np.linspace(clev_min, clev_max, num=24)

        s = np.searchsorted(p_levels[::-1], p)
        sc =  np.searchsorted(p_levs, p)
# Set plot contour lines for pressure levels

        plt_h = mean_heights[:,:,-(s+1)]
        #plt_h[plt_h==0] = np.nan 
       
# Set plot colours for variable

        plt_v = mean_var[:,:,-(s+1)]
        #plt_v[plt_v==0] = np.nan 
              
# Set u,v for winds, linear interpolate to approx. 1 degree grid
        u_interp = u_wind[sc,:,:]
        v_interp = v_wind[sc,:,:]
        sample_points = [('grid_latitude', lat_wind_1deg), ('grid_longitude', lon_wind_1deg)]
        u = iris.analysis.interpolate.linear(u_interp, sample_points).data
        v = iris.analysis.interpolate.linear(v_interp, sample_points).data

        lons_w, lats_w = np.meshgrid(lon_wind_1deg, lat_wind_1deg)

        m =\
Basemap(llcrnrlon=lon_low,llcrnrlat=lat_low,urcrnrlon=lon_high,urcrnrlat=lat_high,projection='mill')

        #x, y = m(lons, lats)
        x, y = m(lons_go, lats_go)

        x_w, y_w = m(lons_w, lats_w)
        fig=plt.figure(figsize=(8,8))
        ax = fig.add_axes([0.05,0.05,0.9,0.85])

        m.drawcoastlines(color='gray')  
        m.drawcountries(color='gray')  
        m.drawcoastlines(linewidth=0.5)
        #m.fillcontinents(color='#CCFF99')
        #m.drawparallels(np.arange(-80,81,10),labels=[1,1,0,0])
        #m.drawmeridians(np.arange(0,360,10),labels=[0,0,0,1])
    
        cs_lin = m.contour(x,y, plt_h, clevs_lin,colors='k',linewidths=0.5)
        #cs_lin = m.contour(x,y, plt_h,colors='k',linewidths=0.5)
        #wind = m.barbs(x_w,y_w, u, v, length=6)

        if plot_diag=='temp':
             cs_col = m.contourf(x,y, plt_v,  np.linspace(clevpt_min, clevpt_max), cmap=plt.cm.RdBu_r, colorbar_extend='both')
             #cs_col = m.contourf(x,y, plt_v, cmap=plt.cm.RdBu_r)
             cbar = m.colorbar(cs_col,location='bottom',pad="5%",  format = '%d')  
             cbar.set_label('K')  
             plt.suptitle('Difference from Global Model (Model - Global Model ) of Height, Potential Temperature and Wind Vectors at %s hPa'% (p), fontsize=10)  

        elif plot_diag=='sp_hum':
             cs_col = m.contourf(x,y, plt_v,  np.linspace(clevsh_min, clevsh_max), cmap=plt.cm.RdBu_r)
             cbar = m.colorbar(cs_col,location='bottom',pad="5%", format = '%.3f') 
             cbar.set_label('kg/kg')
             plt.suptitle('Difference from Global Model (Model - Global Model ) of Height, Specific Humidity and Wind Vectors  at %s hPa'% (p), fontsize=10) 

        wind = m.quiver(x_w,y_w, u, v, scale=150)
        qk = plt.quiverkey(wind, 0.1, 0.1, 5, '5 m/s', labelpos='W')
                
        plt.clabel(cs_lin, fontsize=10, fmt='%d', color='black')

        #plt.title('%s\n%s' % (m_title, model_name_convert_title.main(experiment_id)), fontsize=10)
        plt.title('\n'.join(wrap('%s' % (model_name_convert_title.main(experiment_id)), 80)), fontsize=10)
        #plt.show()  
        if not os.path.exists('/home/pwille/figures/%s/%s' % (experiment_id, plot_diag)): os.makedirs('/home/pwille/figures/%s/%s' % (experiment_id, plot_diag))
        plt.savefig('/home/pwille/figures/%s/%s/geop_height_difference_%shPa_%s_%s.tiff' % (experiment_id, plot_diag, p, experiment_id, plot_diag), format='tiff', transparent=True)
clevs = np.arange(960,1061,5)
# compute native x,y coordinates of grid.
x, y = m(lons, lats)
# define parallels and meridians to draw.
parallels = np.arange(-80.,90,20.)
meridians = np.arange(0.,360.,20.)
# plot SLP contours.
CS1 = m.contour(x,y,slp,clevs,linewidths=0.5,colors='k',animated=True)
CS2 = m.contourf(x,y,slp,clevs,cmap=plt.cm.RdBu_r,animated=True)
# plot wind vectors on projection grid.
# first, shift grid so it goes from -180 to 180 (instead of 0 to 360
# in longitude).  Otherwise, interpolation is messed up.
ugrid,newlons = shiftgrid(180.,u,longitudes,start=False)
vgrid,newlons = shiftgrid(180.,v,longitudes,start=False)
# transform vectors to projection grid.
uproj,vproj,xx,yy = \
m.transform_vector(ugrid,vgrid,newlons,latitudes,31,31,returnxy=True,masked=True)
# now plot.
Q = m.quiver(xx,yy,uproj,vproj,scale=700)
# make quiver key.
qk = plt.quiverkey(Q, 0.1, 0.1, 20, '20 m/s', labelpos='W')
# draw coastlines, parallels, meridians.
m.drawcoastlines(linewidth=1.5)
m.drawparallels(parallels)
m.drawmeridians(meridians)
# add colorbar
cb = m.colorbar(CS2,"bottom", size="5%", pad="2%")
cb.set_label('hPa')
# set plot title
ax.set_title('SLP and Wind Vectors '+str(date))
plt.show()
Beispiel #54
0
    umean = griddata(lonu.ravel(), latu.ravel(), umean.ravel(), lon, lat) 
    vmean = griddata(lonv.ravel(), latv.ravel(), vmean.ravel(), lon, lat) 
    umean = np.ma.masked_where(h < zlev, umean)
    vmean = np.ma.masked_where(h < zlev, vmean) 


umean = np.ma.masked_where(np.abs(umean) > 2, umean)
vmean = np.ma.masked_where(np.abs(vmean) > 2, vmean)

mdict = {'lon':lon,'lat':lat,'umean':umean,'vmean':vmean}
filename = "averages/%s_run-average-vels_%sm.mat" %(expt, zlev)
sp.savemat(filename, mdict)

if zlev != 0:
    mdict2 = {'lon':lon,'lat':lat,'umean':u,'vmean':v}
    filename2 = "averages/%s_run-average-vels.mat" %expt
    sp.savemat(filename2, mdict2)



m = Basemap(projection='cyl', llcrnrlat = lat.min(), urcrnrlat = lat.max(), 
            llcrnrlon = lon.min(), urcrnrlon = lon.max(),
            lat_ts=0, resolution='l')

plt.figure(figsize=(10,10))
m.quiver(lon[::4,::4], lat[::4,::4], umean[::4,::4], vmean[::4,::4])
m.fillcontinents()
plt.title("Run-averaged velocities: %s m" %zlev)
plt.show()

def main():
    def unrotate_pole(rotated_lons, rotated_lats, pole_lon, pole_lat):
     """
      Convert rotated-pole lons and lats to unrotated ones.

      Example::

      lons, lats = unrotate_pole(grid_lons, grid_lats, pole_lon, pole_lat)

      .. note:: Uses proj.4 to perform the conversion.

      """
     src_proj = ccrs.RotatedGeodetic(pole_longitude=pole_lon,
                                    pole_latitude=pole_lat)
     target_proj = ccrs.Geodetic()
     res = target_proj.transform_points(x=rotated_lons, y=rotated_lats,
                                       src_crs=src_proj)
     unrotated_lon = res[..., 0]
     unrotated_lat = res[..., 1]

     return unrotated_lon, unrotated_lat

# Set rotated pole longitude and latitude, not ideal but easier than trying to find how to get iris to tell me what it is.

    plot_levels = [925, 850, 700, 500] 
    #plot_levels = [500]

    experiment_id = 'djznw'

    p_levels = [1000, 950, 925, 850, 700, 500, 400, 300, 250, 200, 150, 100, 70, 50, 30, 20, 10]
    expmin1 = experiment_id[:-1]
  
    plot_type='mean'
    plot_diag='temp'
    fname_h = '/nfs/a90/eepdw/Mean_State_Plot_Data/Mean_Heights_Temps_etc/408_pressure_levels_interp_pressure_%s_%s' % (experiment_id, plot_type)
    fname_d = '/nfs/a90/eepdw/Mean_State_Plot_Data/Mean_Heights_Temps_etc/%s_pressure_levels_interp_%s_%s' % (plot_diag, experiment_id, plot_type)
    print fname_h
    print fname_d
#  Height data file
    with h5py.File(fname_h, 'r') as i:
        mh = i['%s' % plot_type]
        mean_heights = mh[. . .]
    print mean_heights.shape
    with h5py.File(fname_d, 'r') as i:
        mh = i['%s' % plot_type]
        mean_var = mh[. . .]
    print mean_var.shape
    

    f_oro =  '/nfs/a90/eepdw/Mean_State_Plot_Data/pp_files/%s/%s/33.pp' % (expmin1, experiment_id)
    oro = iris.load_cube(f_oro)

    fu = '/nfs/a90/eepdw/Mean_State_Plot_Data/pp_files/%s/%s/30201_mean.pp' % (expmin1, experiment_id)
    
    u_wind,v_wind = iris.load(fu)
    print u_wind.shape
    
    lat_w = u_wind.coord('grid_latitude').points
    lon_w = u_wind.coord('grid_longitude').points
    p_levs = u_wind.coord('pressure').points

    lat = oro.coord('grid_latitude').points
    lon = oro.coord('grid_longitude').points

    lon_low= np.min(lon)
   
   # Wind may have different number of grid points so need to do this twice 

    lat_w = u_wind.coord('grid_latitude').points
    lon_w = u_wind.coord('grid_longitude').points
    p_levs = u_wind.coord('pressure').points

    lat = oro.coord('grid_latitude').points
    lon = oro.coord('grid_longitude').points
    
    cs_w = u_wind.coord_system('CoordSystem')
    cs = oro.coord_system('CoordSystem')

    if isinstance(cs_w, iris.coord_systems.RotatedGeogCS):
        print ' Wind - %s - Unrotate pole %s' % (experiment_id, cs_w)
        lons_w, lats_w = np.meshgrid(lon_w, lat_w)
        lons_w,lats_w = iris.analysis.cartography.unrotate_pole(lons_w,lats_w, cs_w.grid_north_pole_longitude, cs_w.grid_north_pole_latitude)
        
        lon_w=lons_w[0]
        lat_w=lats_w[:,0]

        csur_w=cs_w.ellipsoid

        for i, coord in enumerate (u_wind.coords()):
            if coord.standard_name=='grid_latitude':
                lat_dim_coord_uwind = i
            if coord.standard_name=='grid_longitude':
                lon_dim_coord_uwind = i
       
        u_wind.remove_coord('grid_latitude')
        u_wind.remove_coord('grid_longitude')
        u_wind.add_dim_coord(iris.coords.DimCoord(points=lat_w, standard_name='grid_latitude', units='degrees', coord_system=csur_w),lat_dim_coord_uwind )
        u_wind.add_dim_coord(iris.coords.DimCoord(points=lon_w, standard_name='grid_longitude', units='degrees', coord_system=csur_w), lon_dim_coord_uwind)

        v_wind.remove_coord('grid_latitude')
        v_wind.remove_coord('grid_longitude')
        v_wind.add_dim_coord(iris.coords.DimCoord(points=lat_w, standard_name='grid_latitude', units='degrees', coord_system=csur_w), lat_dim_coord_uwind)
        v_wind.add_dim_coord(iris.coords.DimCoord(points=lon_w, standard_name='grid_longitude', units='degrees', coord_system=csur_w),lon_dim_coord_uwind )
        
    if isinstance(cs, iris.coord_systems.RotatedGeogCS):
        print ' 33.pp  - %s - Unrotate pole %s' % (experiment_id, cs)
        lons, lats = np.meshgrid(lon, lat)      
        
        lon_low= np.min(lons)
        lon_high = np.max(lons)
        lat_low = np.min(lats)
        lat_high = np.max(lats)

        lon_corners, lat_corners = np.meshgrid((lon_low, lon_high), (lat_low, lat_high))
        lons,lats = iris.analysis.cartography.unrotate_pole(lons,lats, cs.grid_north_pole_longitude, cs.grid_north_pole_latitude)
        lon_corner_u,lat_corner_u = iris.analysis.cartography.unrotate_pole(lon_corners, lat_corners, cs.grid_north_pole_longitude, cs.grid_north_pole_latitude)
        #lon_highu,lat_highu = iris.analysis.cartography.unrotate_pole(lon_high, lat_high, cs.grid_north_pole_longitude, cs.grid_north_pole_latitude)

        lon=lons[0]
        lat=lats[:,0]

        print lon_corners
        print lat_corners
        print lon_corner_u
        print lat_corner_u
        print lon_corner_u[0,0]
        print lon_corner_u[0,1]
        print lat_corner_u[0,0]
        print lat_corner_u[1,0]

        lon_low = lon_corner_u[0,0]
        lon_high = lon_corner_u[0,1]
        lat_low = lat_corner_u[0,0]
        lat_high = lat_corner_u[1,0]

        csur=cs.ellipsoid     

        for i, coord in enumerate (oro.coords()):
            if coord.standard_name=='grid_latitude':
                lat_dim_coord_oro = i
            if coord.standard_name=='grid_longitude':
                lon_dim_coord_oro = i

        oro.remove_coord('grid_latitude')
        oro.remove_coord('grid_longitude')
        oro.add_dim_coord(iris.coords.DimCoord(points=lat, standard_name='grid_latitude', units='degrees', coord_system=csur), lat_dim_coord_oro)
        oro.add_dim_coord(iris.coords.DimCoord(points=lon, standard_name='grid_longitude', units='degrees', coord_system=csur), lon_dim_coord_oro)
        print oro
    else:
        lons, lats = np.meshgrid(lon, lat)
        lons_w, lats_w = np.meshgrid(lon_w, lat_w)

        lon_low= np.min(lons)
        lon_high = np.max(lons)
        lat_low = np.min(lats)
        lat_high = np.max(lats)


# 2 degree lats lon lists for wind regridding
    lat_wind_1deg = np.arange(lat_low,lat_high, 2)
    lon_wind_1deg = np.arange(lon_low,lon_high, 2)

   
    for p in plot_levels:

        m_title = 'Height of %s-hPa level (m)' % (p)

# Set pressure height contour min/max
        if p == 925:
            clev_min = 680.
            clev_max = 810.
        elif p == 850:
            clev_min = 1435.
            clev_max = 1530.
        elif p == 700:
            clev_min = 3090.
            clev_max = 3155.
        elif p == 500:
            clev_min = 5800.
            clev_max = 5890.
        else:
            print 'Contour min/max not set for this pressure level'

# Set potential temperature min/max       
        if p == 925:
            clevpt_min = 298.
            clevpt_max = 310.
        elif p == 850:
            clevpt_min = 302.
            clevpt_max = 312.
        elif p == 700:
            clevpt_min = 310.
            clevpt_max = 325.
        elif p == 500:
            clevpt_min = 325.
            clevpt_max = 332.
        else:
            print 'Potential temperature min/max not set for this pressure level'


  # Set specific humidity min/max       
        if p == 925:
            clevsh_min = 0.012
            clevsh_max = 0.022
        elif p == 850:
            clevsh_min = 0.0035
            clevsh_max = 0.018
        elif p == 700:
            clevsh_min = 0.002
            clevsh_max = 0.012
        elif p == 500:
            clevsh_min = 0.002
            clevsh_max = 0.006
        else:
            print 'Specific humidity min/max not set for this pressure level'
       

        #clevs_col = np.arange(clev_min, clev_max)
        clevs_lin = np.linspace(clev_min, clev_max, num=20)

        s = np.searchsorted(p_levels[::-1], p)
        sc =  np.searchsorted(p_levs, p)
# Set plot contour lines for pressure levels

        plt_h = mean_heights[:,:,-(s+1)]
        plt_h[plt_h==0] = np.nan 


# Set plot colours for variable

        plt_v = mean_var[:,:,-(s+1)]
        plt_v[plt_v==0] = np.nan 
        #c_max = int(np.max(plt_h[~np.isnan(plt_h)]))
        #c_min = int(np.min(plt_h[~np.isnan(plt_h) & ]))
              
# Set u,v for winds, linear interpolate to approx. 1 degree grid

      
       # Does not work on iris1.0 as on Leeds computers. Does work on later versions
        
        #u_interp = u_wind[sc,:,:]
        #v_interp = v_wind[sc,:,:].
        #sample_points = [('grid_latitude', np.arange(lat_low,lat_high,2)), ('grid_longitude', np.arange(lon_low,lon_high,2))]

        #u = iris.analysis.interpolate.linear(u_interp, sample_points, extrapolation_mode='linear')
        #v = iris.analysis.interpolate.linear(v_interp, sample_points).data

        u_interp = u_wind[sc,:,:].data
        v_interp = v_wind[sc,:,:].data
       
        lons_wi, lats_wi = np.meshgrid(lon_wind_1deg, lat_wind_1deg)

        fl_la_lo = (lats_w.flatten(),lons_w.flatten())
        u = scipy.interpolate.griddata(fl_la_lo, u_interp.flatten(), (lats_wi, lons_wi), method='linear')
        v = scipy.interpolate.griddata(fl_la_lo, v_interp.flatten(), (lats_wi, lons_wi), method='linear')
       
        lons_w, lats_w = np.meshgrid(lon_wind_1deg, lat_wind_1deg)
        
        m =\
Basemap(llcrnrlon=lon_low,llcrnrlat=lat_low,urcrnrlon=lon_high,urcrnrlat=lat_high,projection='mill', rsphere=6371229)

        x, y = m(lons, lats)
        x_w, y_w = m(lons_w, lats_w)

        #print x_w.shape
        fig=plt.figure(figsize=(8,8))
        ax = fig.add_axes([0.05,0.05,0.9,0.85])

        m.drawcoastlines(color='gray')  
        m.drawcountries(color='gray')  
        m.drawcoastlines(linewidth=0.5)
        #m.fillcontinents(color='#CCFF99')
        m.drawparallels(np.arange(-80,81,10),labels=[1,1,0,0])
        m.drawmeridians(np.arange(0,360,10),labels=[0,0,0,1])
    
        cs_lin = m.contour(x,y, plt_h, clevs_lin,colors='k',linewidths=0.5)

        if plot_diag=='temp':
             plt_v = np.ma.masked_outside(mean_var[:,:,-(s+1)], clevpt_max+20,  clevpt_min-20)

             cs_col = m.contourf(x,y, plt_v,  np.linspace(clevpt_min, clevpt_max), cmap=plt.cm.jet, extend='both')
             cbar = m.colorbar(cs_col,location='bottom',pad="5%", format = '%d')  
             cbar.set_label('K')  
             plt.suptitle('Height, Potential Temperature and Wind Vectors at %s hPa'% (p), fontsize=10)  

        elif plot_diag=='sp_hum':
             plt_v = np.ma.masked_outside(mean_var[:,:,-(s+1)], clevsh_max+20,  clevsh_min-20)

             cs_col = m.contourf(x,y, plt_v,  np.linspace(clevsh_min, clevsh_max), cmap=plt.cm.jet, extend='both')
             cbar = m.colorbar(cs_col,location='bottom',pad="5%", format = '%.3f') 
             cbar.set_label('kg/kg')
             plt.suptitle('Height, Specific Humidity and Wind Vectors at %s hPa'% (p), fontsize=10) 

        wind = m.quiver(x_w,y_w, u, v, scale=400)
        qk = plt.quiverkey(wind, 0.1, 0.1, 5, '5 m/s', labelpos='W')
                
        plt.clabel(cs_lin, fontsize=10, fmt='%d', color='black')

        #plt.title('%s\n%s' % (m_title, model_name_convert_title.main(experiment_id)), fontsize=10)
        plt.title('\n'.join(wrap('%s' % (model_name_convert_title.main(experiment_id)), 80)), fontsize=10)

        plt.show()  
        if not os.path.exists('/nfs/a90/eepdw/Mean_State_Plot_Data/Figures/%s/%s'  % (experiment_id, plot_diag)): os.makedirs('/home/pwille/figures/%s/%s' % (experiment_id, plot_diag))
      
    # Draw a thick border around the whole map
    m.drawmapboundary(linewidth=3)
              
    # Plot Data
    xi, yi = m(lon2,lat2)
    cs = m.pcolormesh(xi,yi,umag,cmap=cm.gist_ncar_r,vmin=0.005, vmax = 0.1)
    xi, yi = m(lon,lat)
    cM = m.contour(   xi,yi,scope2,[1,1],colors='k',linewidth=2.0)

    # transform vectors to projection grid.
    uproj,vproj,xx,yy = m.transform_vector(u[1::2,1::2]*10,v[1::2,1::2]*10,\
                                         lonu[0,1::2].squeeze(),latu[1::2,0].squeeze(),\
                                         60,60,returnxy=True,masked=True)
    # now plot.
    Q  = m.quiver(xx,yy,uproj,vproj,scale=15)

    # Add Coastlines, States, and Country Boundaries
    m.drawcoastlines()
    m.drawstates()
    m.drawcountries()
    m.fillcontinents(color='grey')
              
    # Add Colorbar
    clabels=np.array([0.005,0.025,0.05,0.075,0.1])
    cbar = m.colorbar(cs, location='right', pad="2%",ticks=clabels,extend='max')
    cbar.set_label('Current Speed (m/s)')
    cbar.ax.set_yticklabels([0.5,2.5,5,7.5,10])
  
  else:
    fig=plt.figure(num=None, figsize=(10, 10), dpi=300, facecolor=None)
Beispiel #57
0
    temp = np.squeeze(temp[pn,:,:]); 
    lont, latt = np.meshgrid(lont, latt)
    lonu, latu = np.meshgrid(lonu, latu)
    lontp,lattp = m(lont,latt)
    lonup,latup = m(lonu,latu)

    umean = umean + u
    vmean = vmean + v

u = umean; v = vmean
#################################################
s = 2; # quiver scale

plt.figure(figsize=(6,8),facecolor='w')
# m.pcolormesh(lont[::d,::d], latt[::d,::d],temp[::d,::d])
m.quiver(lonup[::d,::d], latup[::d,::d], u[::d,::d]*s,v[::d,::d]*s,scale=10);
m.contourf(xb,yb,zb,colors=('0.7'), alpha=0.5);
m.drawcoastlines(zorder=5)
m.drawcountries(zorder=4)
m.fillcontinents(color='0.8',lake_color='aqua',zorder=3)
m.drawparallels(np.arange(-22,-12,2),labels=[0, 1, 0, 0],dashes=[1,3],zorder=6)
m.drawmeridians(np.arange(-41,-34,2),labels=[0, 0, 0, 1],dashes=[1,3],zorder=7)
text = "50 cm/s";
ax,ay = m(-40.5,-13.0); m.quiver(ax,ay,0.5*s,0,scale=10,color='k',zorder=10)
ax,ay = m(-40.5,-13.4); plt.text(ax,ay,text,color='k',fontsize=10,fontweight='bold')
text = np.str(p) + ' m'
ax,ay = m(-34.8,-22.0); plt.text(ax,ay,text,color='k',fontsize=10,fontweight='bold')
ax,ay = m(-39.5,-18.5); plt.text(ax,ay,"ABROLHOS",color='k',fontsize=10)
ax,ay = m(-39.2,-18.8); plt.text(ax,ay,"BANK",color='k',fontsize=10)
ax,ay = m(-38.8,-16.2); plt.text(ax,ay,"RCB",color='k',fontsize=10)
ax,ay = m(-40,-14.5); plt.text(ax,ay,"Ilheus",color='k',fontsize=10)
Beispiel #58
0
import numpy as np


map = Basemap(llcrnrlon=-93.7, llcrnrlat=28., urcrnrlon=-66.1, urcrnrlat=39.5,
              projection='lcc', lat_1=30., lat_2=60., lat_0=34.83158, lon_0=-98.)

ds = gdal.Open("../sample_files/wrf.tiff")
lons = ds.GetRasterBand(4).ReadAsArray()
lats = ds.GetRasterBand(5).ReadAsArray()
u10 = ds.GetRasterBand(1).ReadAsArray()
v10 = ds.GetRasterBand(2).ReadAsArray()
speed = np.sqrt(u10*u10 + v10*v10)

x, y = map(lons, lats)

yy = np.arange(0, y.shape[0], 4)
xx = np.arange(0, x.shape[1], 4)

points = np.meshgrid(yy, xx)

map.drawmapboundary(fill_color='aqua')
map.fillcontinents(color='#cc9955', lake_color='aqua', zorder = 0)
map.drawcoastlines(color = '0.15')

map.quiver(x[points], y[points], 
    u10[points], v10[points], speed[points],
    cmap=plt.cm.autumn)

plt.show()