def plot_brights(ax, path, star, regionList, goal=False):
    '''
    Components of this routine:
        Projected brightness map
         
    Please note that this has been modified for use in diagnostic plots, 
    there should really be a way to specify a windowNumber for real data
    '''
    currentWindow = 0

    ###########################
    # Make the brightness map #
    ###########################
    img = make_bright_image(star, regionList, currentWindow, goal=goal)
    
    plt.imsave(path + "temp.jpg", img, cmap='hot', vmin=0.85, vmax=1.15)
    plt.imshow(img, cmap='hot')
    #Create the plot
    bmap = Basemap(projection='moll', lon_0 = 0, ax=ax)
    bmap.warpimage(path + "temp.jpg", ax=ax)
    
    if goal:
        ax.set_title("Desired Map")
    else:
        ax.set_title("Average Map")
Example #2
0
def warp_map_image(map_type):
    """
    Create an orthographic map projection from the perspective of a satellite
    looking down at 45N, 100W using low resolution coastlines.

    """
    infile = os.path.join(*PLOT_DIR, '%s_map.png' % map_type)
    fig = plt.figure(2, frameon=False)
    left = 0.0
    bottom = 0.05
    width = 1.0
    height = 0.9
    ax = fig.add_axes([left, bottom, width, height])
    print('    Creating Basemap...')
    map = Basemap(projection='ortho',
                  lat_0=45,
                  lon_0=-100,
                  resolution='l',
                  ax=ax)
    try:
        map.warpimage(infile)
    except FileNotFoundError:
        prepare_background(map_type)
        map.warpimage(infile)
    return fig, map
Example #3
0
def plot_map(file: str, centre_lat: float = 0, centre_lon: float = 0, show: float = True, projection: str = 'cyl',
             meridians: bool = True, parallels: bool = True):
    """
    Using an image file and basemap, plots the map to the projection specified. Projections should be those supported in
    Basemap; not all projections will work.
    :param file: Path to the image file.
    :param centre_lat: Latitude to show at centre.
    :param centre_lon: Longitude to show at centre.
    :param show: Set to True to show the plot.
    :param meridians: set to True to plot meridian lines.
    :param parallels: Set to True to plot parallel lines.
    :param projection: Projection type, as listed at https://matplotlib.org/basemap/users/mapsetup.html
    :return: Basemap object for this map.
    """
    if not check_basemap():
        return None
    # Set up basemap object.
    bmap = Basemap(projection=projection, llcrnrlat=-90, urcrnrlat=90,
                   llcrnrlon=-180, urcrnrlon=180, resolution='c',
                   lat_0=centre_lat, lon_0=centre_lon)
    # Draw plot.
    bmap.warpimage(image=file)
    if meridians:
        bmap.drawmeridians(np.arange(0, 360, 30))
    if parallels:
        bmap.drawparallels(np.arange(-90, 90, 30))
    if show:
        plt.show()

    return bmap
Example #4
0
def plot_globe(file: str, centre_lat: float = 0, centre_lon: float = 0, show: bool = True, meridians: bool = True,
               parallels: bool = True):
    """
    Using an image file and basemap, creates an orthographic projection of the image. Assumes the image is in a
    cylindrical projection.
    :param file: Path to the image file.
    :param centre_lat: Latitude to show at centre.
    :param centre_lon: Longitude to show at centre.
    :param show: Set to True to show the plot.
    :param meridians: set to True to plot meridian lines.
    :param parallels: Set to True to plot parallel lines.
    :return: Basemap object of map.
    """
    # Set up basemap object.
    if not check_basemap():
        return None
    bmap = Basemap(projection='ortho', lat_0=centre_lat, lon_0=centre_lon, resolution='l', area_thresh=1000.)
    # Draw plot.
    bmap.warpimage(image=file)
    bmap.drawmapboundary()
    if meridians:
        bmap.drawmeridians(np.arange(0, 360, 30))
    if parallels:
        bmap.drawparallels(np.arange(-90, 90, 30))
    if show:
        plt.show()

    return bmap
Example #5
0
def GenerateImages(key,counter,Coordinates,data,total):
	if key=='confirmed':
		color=(0,0,1)
	elif key=='deaths':
		color=(1,0,0)
	#fig = plt.figure(figsize=(15, 10))
	Map=Basemap(llcrnrlat=24,llcrnrlon=-130,urcrnrlat=50,urcrnrlon=-65)
	Map.warpimage()
	for i in range(len(Coordinates)):
		x,y=Coordinates.iloc[i,1],Coordinates.iloc[i,0]
		if data[i] > 0:
			Map.plot(x,y,color=color,marker='o',markersize=2)
	plt.savefig(os.path.join('Images',key,'Image'+str(counter)+'.png'),transparent=True,bbox_inches='tight',dpi=300)
	#plt.show()
	plt.close()
Example #6
0
def save_map(routes, file_name):
    """
    Render flight routes to an image file.

    :param list routes: flight path lines
    :param str file_name: image output file name
    """
    fig = plt.figure(figsize=(7.195, 3.841), dpi=100)
    m = Basemap(projection='cyl', lon_0=0, resolution='c')
    ax = plt.Axes(fig, [0., 0., 1., 1.])
    ax.set_axis_off()
    fig.add_axes(ax)

    for (colour, alpha, linewidth, lat1, long1, lat2, long2) in sorted(routes):
        """
        Cannot handle situations in which the great circle intersects the 
        edge of the map projection domain, and then re-enters the domain.

        Fix from: http://stackoverflow.com/questions/13888566/
        """
        line, = m.drawgreatcircle(long1,
                                  lat1,
                                  long2,
                                  lat2,
                                  linewidth=linewidth,
                                  color=colour,
                                  alpha=alpha,
                                  solid_capstyle='round')

        p = line.get_path()

        # Find the index which crosses the dateline (the delta is large)
        cut_point = np.where(np.abs(np.diff(p.vertices[:, 0])) > 200)[0]

        if cut_point:
            cut_point = cut_point[0]

            # Create new vertices with a nan in between and set
            # those as the path's vertices
            new_verts = np.concatenate([
                p.vertices[:cut_point, :], [[np.nan, np.nan]],
                p.vertices[cut_point + 1:, :]
            ])
            p.codes = None
            p.vertices = new_verts

    m.warpimage(image="earth_lights_lrg.jpg")
    plt.savefig(file_name, dpi=1000)
Example #7
0
    def plot_real_event(self, la_r, lo_r, la_s, lo_s):
        mars_dir = '/home/nienke/Documents/Applied_geophysics/Thesis/anaconda/mars_pictures/Mars_lightgray.jpg'

        fig = plt.figure()

        m = Basemap(projection='moll', lon_0=round(0.0))

        # draw parallels and meridians.
        par = np.arange(-90, 90, 30)
        label_par = np.full(len(par), True, dtype=bool)
        meridians = np.arange(-180, 180, 30)
        label_meri = np.full(len(meridians), True, dtype=bool)

        m.drawmeridians(np.arange(-180, 180, 30), labels=label_meri)
        m.drawparallels(np.arange(-90, 90, 30), label=label_par)

        m.warpimage(mars_dir)
        mstatlon, mstatlat = m(lo_r, la_r)
        m.plot(mstatlon, mstatlat, 'k^', markersize=10)

        EQlon, EQlat = m(lo_s, la_s)
        m.plot(EQlon,
               EQlat,
               'ro',
               markersize=4.6**2,
               zorder=10,
               markeredgecolor='k')

        #Blindtest dataset 3.5:

        Blind1lon, Blind1lat = m(210.047795358, 27.8640470986)
        m.plot(Blind1lon,
               Blind1lat,
               'ro',
               markersize=3.5**2,
               zorder=10,
               markeredgecolor='k')

        # Blindtest dataset 5.0:
        Blind2lon, Blind2lat = m(103.830554149, -10.0887531193)
        m.plot(Blind2lon,
               Blind2lat,
               'ro',
               markersize=5.0**2,
               zorder=10,
               markeredgecolor='k')

        plt.show()
Example #8
0
def bluemarble_daynight2(date, lon, lat, scale):

    # Define Bluemarble and Nightshade objects
    fig, axes = plt.subplots(1, figsize=(16, 12))
    m = Basemap(projection='cyl', resolution=None, area_thresh=None, ax=axes)
    bm = m.bluemarble(scale=scale)
    ns = m.nightshade(date, alpha=0.5)

    bm_rgb = bm.get_array()
    bm_ext = bm.get_extent()

    axes.cla()

    # Get the x and y index spacing
    x = np.linspace(bm_ext[0], bm_ext[1], bm_rgb.shape[1])
    y = np.linspace(bm_ext[2], bm_ext[3], bm_rgb.shape[0])

    # Define coordinates of the Bluemarble image
    x3d, y3d = np.meshgrid(x, y)
    pts = np.hstack((x3d.flatten()[:, np.newaxis], y3d.flatten()[:,
                                                                 np.newaxis]))

    # Find which coordinates fall in Nightshade
    # The following could be tidied up as there should only ever one polygon. Although
    # the length of ns.collections is 3? I'm sure there's a better way to do this.
    paths, polygons = [], []
    for i, polygons in enumerate(ns.collections):
        for j, paths in enumerate(polygons.get_paths()):
            #print j, i
            msk = paths.contains_points(pts)

    # Redefine mask
    msk = np.reshape(msk, bm_rgb[:, :, 0].shape)
    msk_s = np.zeros(msk.shape)
    msk_s[~msk] = 1.

    # Smooth interface between Night and Day
    for s in range(
            int(bm_rgb.shape[1] / 50)
    ):  # Make smoothing between day and night a function of Bluemarble resolution
        msk_s = 0.25 * (  np.vstack( (msk_s[-1,:            ], msk_s[:-1, :            ]) )  \
                        + np.vstack( (msk_s[1:,:            ], msk_s[0  , :            ]) )  \
                        + np.hstack( (msk_s[: ,0, np.newaxis], msk_s[:  , :-1          ]) )  \
                        + np.hstack( (msk_s[: ,1:           ], msk_s[:  , -1,np.newaxis]) ) )

    # Define new RGBA array
    bm_rgba = np.dstack((bm_rgb[:, :, 0:3], msk_s))
    # Plot up Bluemarble Nightshade
    m = Basemap(projection='cyl', resolution=None, area_thresh=None, ax=axes)
    bm_n = m.warpimage('./earth_lights_lrg.jpg', scale=scale)
    #from https://eoimages.gsfc.nasa.gov/images/imagerecords/55000/55167/earth_lights_lrg.jpg
    bm_d = m.imshow(bm_rgba)
    x, y = m(lon, lat)
    plt.plot(x, y, 'or', markersize=10)
    plt.title('Day/Night Map for %s (UTC)' %
              date.strftime("%d %b %Y %H:%M:%S"),
              fontsize=15)
    plt.subplots_adjust(left=0.02, right=0.98, top=0.98, bottom=0.02)
    plt.savefig('f2.jpg')
    def proj_plot(self):
        '''
        Creates a Mollweide projection of Rectangle and saves it
        '''
        #ax = plt.axes([.15, .6, .32, .32])
        plt.imsave("/temp.png", self.matrix, cmap='hot', vmin=0.85, vmax=1.15)
        plt.imshow(self.matrix, cmap='hot')    
        plt.clim(0.85,1.15)
        plt.colorbar(shrink=0.5)

        #Create the plot
        bmap = Basemap(projection='robin', lon_0 = 0)
        bmap.warpimage("/temp.png")
        
        fig = plt.gcf()
        fig.set_size_inches(18.5,11.5)
        plt.savefig("spot_proj.png", dpi=120)
Example #10
0
def save_map(routes, file_name):
    """
    Render flight routes to an image file.

    :param list routes: flight path lines
    :param str file_name: image output file name
    """
    fig = plt.figure(figsize=(7.195, 3.841), dpi=100)
    m = Basemap(projection='cyl', lon_0=0, resolution='c')
    ax = plt.Axes(fig, [0., 0., 1., 1.])
    ax.set_axis_off()
    fig.add_axes(ax)

    for (colour, alpha, linewidth, lat1, long1, lat2, long2) in sorted(routes):
        """
        Cannot handle situations in which the great circle intersects the 
        edge of the map projection domain, and then re-enters the domain.

        Fix from: http://stackoverflow.com/questions/13888566/
        """
        line, = m.drawgreatcircle(long1, lat1, long2, lat2,
                                  linewidth=linewidth,
                                  color=colour,
                                  alpha=alpha,
                                  solid_capstyle='round')

        p = line.get_path()

        # Find the index which crosses the dateline (the delta is large)
        cut_point = np.where(np.abs(np.diff(p.vertices[:, 0])) > 200)[0]

        if cut_point:
            cut_point = cut_point[0]

            # Create new vertices with a nan in between and set 
            # those as the path's vertices
            new_verts = np.concatenate([p.vertices[:cut_point, :], 
                                        [[np.nan, np.nan]], 
                                        p.vertices[cut_point+1:, :]])
            p.codes = None
            p.vertices = new_verts

    m.warpimage(image="earth_lights_lrg.jpg")
    plt.savefig(file_name, dpi=1000)
Example #11
0
def plot_clusters(pts,filename,markerscale,background_img=None):
	rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
	rc('text', usetex=True)
	m = Basemap(projection='moll',lon_0=0,resolution='c')
	if background_img: m.warpimage(background_img)
	else: m.drawmapboundary(fill_color='black')
	m.drawparallels(np.arange(-90.,180.,15.),color='white',linewidth=.5)
	m.drawmeridians(np.arange(0.,420.,15.),color='white',linewidth=.5)
	for px,py,sz,name,alpha in pts:
		x,y = m(r2d(px),r2d(py))
		plt.plot(x,y,'*',color='yellow',markersize=markerscale*log(sz,markerscale), alpha=alpha)
		plt.text(x,y,name.replace("_","-").replace("#","No. "),color='red',size=2)
	# Plot the zone of avoidance
	m.drawparallels([ZONE_OF_AVOIDANCE,-ZONE_OF_AVOIDANCE], color='yellow', linewidth=1)
	x,y=m(0,-(ZONE_OF_AVOIDANCE-2))
	plt.text(x,y,r'$b = %i^{\circ}$' % (-(ZONE_OF_AVOIDANCE)),color='yellow',size=7, ha='center', va='bottom')
	x_,y_=m(0,(ZONE_OF_AVOIDANCE-2))                      
	plt.text(x_,y_,r'$b = %i^{\circ}$' % (ZONE_OF_AVOIDANCE),color='yellow',size=7,ha='center', va='top')
	#plt.title("Galaxy Clusters")
	plt.savefig(filename,dpi=300)
Example #12
0
def plot_brights_stripes_only(path, bright_file, nstripes, output):
    '''
    Take in a set of brightness values and output a brightness map.
    This snippet of code is adapted from Leslie's IDL code
    '''
    
    #Read in file
    temp = []
    for line in open(bright_file):                           
        temp.append(float(line))
    brights = np.array(temp)
    
    #Set up arrays for brightnesses and positions
    nx = nstripes * 50
    ny = nstripes * 50
    bright_stripe = np.array(brights)
    img = np.zeros((nx,ny))
    idx1_stripe = np.arange(0, nstripes, 1.)/nstripes * nx
    idx2_stripe = (np.arange(0, nstripes, 1.) + 1)/nstripes * nx - 1

    #Populate the pixel values
    for jj in range(nstripes):
        idx1 = idx1_stripe[jj]
        idx2 = idx2_stripe[jj]
        idy1 = 0
        idy2 = ny-1
        img[idy1:idy2, idx1:idx2] = bright_stripe[jj]
    
    plt.imsave(path + "/" + output, img, cmap='hot')
    plt.imshow(img, cmap='hot')
    plt.clim(.9,1.25)
    plt.title("Surface Brightness Map")
    #Create the plot
    bmap = Basemap(projection='moll', lon_0 = 0)
    #plt.savefig(path + "/" + output)
    bmap.warpimage(path + "/" + output)
    #Place the plot in the appropriate place
    plt.savefig(path + "/" + output)
    plt.close()
Example #13
0
def create_map(llcrnrlat,
               urcrnrlat,
               llcrnrlon,
               urcrnrlon,
               relief_bool,
               highres,
               width,
               map_dpi=300):
    '''creates the map'''
    print("Building the map. This might take a minute...")

    plt.figure(figsize=(width / map_dpi, (width * 0.69) / map_dpi),
               dpi=map_dpi)
    m = Basemap(projection='mill', llcrnrlat=llcrnrlat, urcrnrlat=urcrnrlat, \
      llcrnrlon=llcrnrlon, urcrnrlon=urcrnrlon, resolution='l')

    if highres:
        tmpdir = '/Temp'

        size = [12000, 6000]
        Image.MAX_IMAGE_PIXELS = 233280001
        im = Image.open("HYP_HR_SR_W.tif")

        im2 = im.resize(size, Image.ANTIALIAS)
        im2.save(tmpdir + '/resized.png', "PNG")

        m.warpimage(tmpdir + '/resized.png')

    if relief_bool:
        m.shadedrelief()

    country_col = choose_border_color(relief_bool)
    m.drawcountries(color=country_col)

    m.fillcontinents(color=(0.9, 0.9, 0.9), lake_color='#FFFFFF', zorder=0)
    m.drawmapboundary(fill_color='#FFFFFF')

    return m
Example #14
0
# 加入colorbar
cb = m.colorbar(im,"right", size="5%", pad='2%')
ax.set_title('ETOPO5 Topography - Lambert Conformal Conic')
plt.show()


# Case_02_嘗試使用一張"earth_lights_lrg.jpg" 搭配不同的投影方式繪製地圖.
# 說明使用warpimage method 方法顯示圖像背景。
# 在地圖投影區域。 預設背景是『藍色。
# 來自美國宇航局的大理石圖像 (http://visibleearth.nasa.gov)
# 建立新圖像
fig=plt.figure()
# 定義以北美為中心的正交投影.
m = Basemap(projection='ortho',lat_0=40,lon_0=-100,resolution='l')
# 顯示非預設影像 - 匯入要使用的IMAGE
m.warpimage(image="earth_lights_lrg.jpg")
# 繪製海岸線。
m.drawcoastlines(linewidth=0.5,color='0.5')
# 每 30 度繪製一組 lat/lon 網格線。
m.drawmeridians(np.arange(0,360,30),color='0.5')
m.drawparallels(np.arange(-90,90,30),color='0.5')
#添加圖示標題
plt.title("Lights at Night image warped from 'cyl' to 'ortho' projection",fontsize=12)
print('warp to orthographic map ...')
plt.show()


# Case_03_定義圓柱形等距投影(projection="cyl")
# 建立新圖像
fig=plt.figure()
# 新定義圓柱形等距投影。
Example #15
0
        m = Basemap(projection='laea', width= 4300000,height=4000000, resolution='i', lat_ts=55.00,lat_0=55.00,lon_0=15.00)
        m.drawparallels(np.arange(-90.,91.,10.), labels=[0,0,0,0],linewidth=0.5)
        m.drawmeridians(np.arange(-180.,181.,10.), labels=[0,0,0,0],linewidth=0.5)
        m.drawmapboundary(fill_color='white')
    elif options.show_domain.lower()=='world':
        m = Basemap(projection='moll',resolution='c',lon_0=0.)
        m.drawparallels(np.arange(-90.,91.,10.), labels=[0,0,0,0],linewidth=0.5)
        m.drawmeridians(np.arange(-180.,181.,10.), labels=[0,0,0,0],linewidth=0.5)
        m.drawmapboundary(fill_color='white')
    else:
        grdis = gridfh.grid_size_in_meters

        m = Basemap(width=(len(gridfh.dimensions['x'])-bufferzone*2-2)*grdis, height=(len(gridfh.dimensions['y'])-bufferzone*2-2)*grdis, resolution='i', projection='lcc', lat_0=gridfh.latitude_of_projection_origin, lon_0=gridfh.longitude_of_projection_origin, lat_1=gridfh.standard_parallel[0], lat_2=gridfh.standard_parallel[1], ax=plt.gca())

    if isfile(options.bgimage):
        m.warpimage(image=options.bgimage)

    if options.normalize:
        vardatanorm = colors.Normalize(vmin=options.norm_minimum,vmax=options.norm_maximum)
    elif options.lognormalize:
        vardatanorm = colors.SymLogNorm(linthresh=20.,linscale=1.0,vmin=options.norm_minimum,vmax=options.norm_maximum)
    else:
        vardatanorm = None

    x,y = m(lon,lat)
    if options.deaccumulate>0 and t>time1 and counter%options.deaccumulate>0:
        print "*** Deaccumulating time %d " % t
        data = vardata[t]-vardata[t-1]
    else:
        data = vardata[t]
Example #16
0
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import Image

map = Basemap(projection="ortho", lat_0=0, lon_0=0)


tmpdir = "/tmp"

size = [600, 300]
im = Image.open("../sample_files/by.png")

im2 = im.resize(size, Image.ANTIALIAS)
im2.save(tmpdir + "/resized.png", "PNG")

map.warpimage(tmpdir + "/resized.png")

map.drawcoastlines()

plt.show()
    urcrnrlat=40,
    llcrnrlon=120,
    urcrnrlon=200,
    resolution="c",
)

# draw parallels and meridians.
par = np.arange(-90, 90, 30)
label_par = np.full(len(par), True, dtype=bool)
meridians = np.arange(-180, 180, 30)
label_meri = np.full(len(meridians), True, dtype=bool)

m.drawmeridians(np.arange(-180, 180, 30), labels=label_meri)
m.drawparallels(np.arange(-90, 90, 30), label=label_par)

m.warpimage(mars_dir)
lat_rec = 4.5  # 02384
lon_rec = 135.623447
mstatlon, mstatlat = m(lon_rec, lat_rec)
m.plot(mstatlon, mstatlat, "k^", markersize=20, label="InSight")

EQlonA, EQlatA = m(162.8890468, 11.40707267)  # S0235b
EQlonB, EQlatB = m(164.9642605, 3.437219264)  # S0173a
EQlonC, EQlatC = m(179.59, 15.09)  # S0183a
EQlonD, EQlatD = m(164.6489946, 5.390502842)  # S0809a
EQlonE, EQlatE = m(165.3877124, -1.629058007)  # S0820a
m.plot(EQlonA, EQlatA, "r*", markersize=20, zorder=10, label="S0235b")
m.plot(EQlonB, EQlatB, "g*", markersize=20, zorder=10, label="S0173a")
m.plot(EQlonC, EQlatC, "b*", markersize=20, zorder=10, label="S0183a")
m.plot(
    EQlonD,
Example #18
0
def plotxy(ifile='grid_search_xy_out',
           xyzfile='grid_search_xyz_out',
           ofile='grid_search_xy.pdf',
           basemapflag=False,
           mksmin=1.,
           mksmax=30.,
           delta=XY_NX * XY_DX,
           resolution='h'):
    # Initialize variables
    rms = []
    lon = []
    lat = []
    flag = False
    # Read file grid search XYZ
    # WARNING :: PDE from XYZ is the initial epicenter
    if os.path.exists(xyzfile):
        latopt, lonopt, depopt, rmsopt, ilatpde, ilonpde, deppde, rmspde, lats, lons, deps, rmss, depths, rmsdep = rxyzgfile(
            xyzfile)
    # Read file grid search XY
    # WARNING :: PDE from XY is the solution of grid search in Z
    latopt, lonopt, depopt, rmsopt, latpde, lonpde, rmspde, lat, lon, rms = r_xy_gfile(
        ifile)
    if not os.path.exists(xyzfile):
        ilatpde = latpde
        ilonpde = lonpde
    # RMS Scale
    minrms = rmsopt
    nrms = rms / minrms * 100.
    maxrms = max(rms) / minrms * 100.
    minrms = 100.
    plt.figure(figsize=(9.6125, 8.1))
    ax1 = plt.axes([0.04, 0.13, 0.8, 0.85])
    ax2 = plt.axes([0.85, 0.35, 0.1, 0.6])
    cm = plt.get_cmap('jet')
    for i in range(8):
        Bpos = interp(i, 8, 0., 1.)
        Brms = interp(i, 8, minrms, maxrms)
        mksize = ((Brms - minrms) /
                  (maxrms - minrms)) * (mksmax - mksmin) + mksmin
        plt.plot([0.5], [Bpos],
                 'ko',
                 ms=mksize,
                 markerfacecolor=cm((Brms - minrms) / (maxrms - minrms)))
        plt.text(0.9, Bpos - 0.02, '%7.1f' % Brms)
    ax2.set_axis_off()
    mksize = ((np.array(nrms) - minrms) /
              (maxrms - minrms)) * (mksmax - mksmin) + mksmin
    plt.ylim(-0.1, 1.1)
    plt.xlim(0, 1.6)
    plt.title('Normalized RMS')
    # DISPLAY MAP
    plt.axes(ax1)
    if basemapflag:
        try:
            from mpl_toolkits.basemap import Basemap
        except:
            print('WARNING: No module named basemap')
            print('   The mpl_toolkits.basemap module is necessary')
            print('   if you want to plot bathymetry and coastlines')
            basemapflag = False
    if basemapflag:
        wraplons(lon)
        deltalon = delta / np.cos(np.pi * latpde / 180.0)
        latll = lat.min() - delta
        latur = lat.max() + delta
        lonll = lon.min() - deltalon
        lonur = lon.max() + deltalon
        # Basemap instance
        m = Basemap(projection='merc',
                    llcrnrlon=lonll,
                    llcrnrlat=latll,
                    urcrnrlon=lonur,
                    urcrnrlat=latur,
                    resolution=resolution)
        # Bathymetry
        ETOPO_file = os.path.expandvars('$ETOPOFILE')
        if os.path.exists(ETOPO_file):
            try:
                plot_etopo(ETOPO_file, m, ax1)
                etopoflag = True
            except:
                etopoflag = False
                print('WARNING: error encountered while plotting ETOPO')
                print('         Will not display topography/bathymetry')
        else:
            etopoflag = False
            if ETOPO_file[0] == '$':
                print('WARNING: Undefined environment variable $ETOPOFILE')
            else:
                print('WARNING: ETOPOFILE=%s does not exists' % (ETOPO_file))
                print('         Will not display topography/bathymetry')
        # Coastlines/meridians/paralells
        plt.axes(ax1)
        m.drawcoastlines(linewidth=0.5)
        m.drawmeridians(np.arange(float(int(lonll)), lonur + delta, delta),
                        labels=[0, 0, 0, 1],
                        dashes=[1, 1],
                        linewidth=0.5,
                        color='k')
        m.drawparallels(np.arange(float(int(latll)), latur + delta, delta),
                        labels=[1, 0, 0, 0],
                        dashes=[1, 1],
                        linewidth=0.5,
                        color='k')
        if not etopoflag:
            try:
                BLUEMARBLE_file = os.path.expandvars('$BLUEMARBLEFILE')
                if os.path.exists(BLUEMARBLE_file):
                    m.warpimage(image=BLUEMARBLE_file)
                else:
                    if BLUEMARBLE_file[0] == '$':
                        print(
                            'WARNING: Undefined environment variable $BLUEMARBLEFILE'
                        )
                    else:
                        print('WARNING: BLUEMARBLEFILE=%s does not exists' %
                              (BLUEMARBLE_file))
                        print(
                            '         Will not display topography/bathymetry')
            except:
                print(
                    'WARNING: error encountered while plotting background bluemarbe image'
                )
                print('         Will not display topography/bathymetry')
                pass
            m.fillcontinents(color='0.65', lake_color='white')
        m.drawcountries(linewidth=0.3, color='k')
        # RMS misfit
        for la, lo, err, siz in zip(lat, lon, nrms, mksize):
            x, y = m(lo, la)
            col = cm((err - minrms) / (maxrms - minrms))
            m.plot([x], [y], c=col, marker='o', ms=siz)
        l = [ilonpde, lonopt]
        wraplons(l)
        xpde, ypde = m(l[0], ilatpde)
        xopt, yopt = m(l[1], latopt)
        m.plot([xpde], [ypde], 'rv', ms=14, alpha=0.7, label='Initial PDE')
        m.plot([xopt], [yopt],
               'g*',
               ms=18,
               mew=1.2,
               alpha=0.7,
               label='W-Phase Centroid')
        leg = plt.legend(loc='lower center',prop={'size': 12},numpoints=1, scatterpoints=1, \
                             bbox_to_anchor=(0.5, 0.01),ncol=2, shadow=True, fancybox=True)
        leg.get_frame().set_alpha(0.6)
    else:
        deltalon = delta / np.cos(np.pi * latpde / 180.0)
        latll = lat.min() - delta
        latur = lat.max() + delta
        lonll = lon.min() - deltalon
        lonur = lon.max() + deltalon
        for la, lo, err, siz in zip(lat, lon, nrms, mksize):
            col = cm((err - minrms) / (maxrms - minrms))
            plt.plot([lo], [la], c=col, marker='o', ms=siz)
        plt.plot([lonpde], [latpde], 'k+', ms=14, mew=2.5, alpha=0.7)
        plt.plot([lonopt], [latopt], 'rv', ms=14, alpha=0.7)
        plt.xlim([lonll, lonur])
        plt.ylim([latll, latur])
    plt.savefig(ofile)
    # All done
    return
Example #19
0
def mapSubject(dataSetIn,
               subject,
               box='tight',
               level='auto',
               longest=20,
               call='default',
               highlight=False,
               heatmap=True,
               mark='r',
               cmap='YlOrRd',
               show=True,
               offset=0,
               subtitle='',
               geobox='null',
               important='null',
               background='none'):

    dataset = filterMapNans(dataSetIn)

    if call == 'animate':
        plt.clf()
    else:
        fig = plt.figure(figsize=(9, 9))

    if geobox == 'null' or (type(box) is str and type(geobox) is str):
        box = fixBox(dataset, box)
    else:
        box = geobox

    lats, lons, times = getData(dataset, offset)

    mapped = Basemap(projection='mill',
                     llcrnrlon=box['lon1'],
                     llcrnrlat=box['lat1'],
                     urcrnrlon=box['lon2'],
                     urcrnrlat=box['lat2'])

    mapOpacity = 0.75
    if background == 'etopo':
        mapped.etopo(zorder=0, alpha=mapOpacity)
    elif background == 'shaded relief':
        mapped.shadedrelief(zorder=0, alpha=mapOpacity)
    elif background == 'blue marble':
        mapped.bluemarble(zorder=0, alpha=mapOpacity)
    elif '/' in background or '.' in background:
        try:
            mapped.warpimage(image='maps/' + background,
                             scale=None,
                             zorder=0,
                             alpha=mapOpacity)
        except:
            mapped.warpimage(image=background,
                             scale=None,
                             zorder=0,
                             alpha=mapOpacity)
    else:
        background = 'null'

    smallest = min(box['lat2'] - box['lat1'], box['lon2'] - box['lon1'])

    mapped.drawcoastlines(zorder=3, linewidth=1.5)

    if smallest < 5:
        mapped.drawcountries(zorder=3, linewidth=2)
        mapped.drawstates(zorder=3, linewidth=1.5)
        try:
            mapped.drawcounties(zorder=20, linewidth=1)
        except:
            print "Counties rendering still broken"
            #https://github.com/matplotlib/basemap/pull/459
    else:
        mapped.drawcountries(zorder=3, linewidth=1.5)
        mapped.drawstates(zorder=3, linewidth=1)

    if heatmap:
        density, lon_bins, lat_bins = getDensity(box, lats, lons, longest)
        lon_bins_2d, lat_bins_2d = np.meshgrid(lon_bins, lat_bins)
        xs, ys = mapped(lon_bins_2d,
                        lat_bins_2d)  # will be plotted using pcolormesh

        if level == 'auto':
            level = np.amax(density)

        density = fixDensity(density, xs, ys)

        if background == 'null':
            plt.pcolormesh(xs,
                           ys,
                           density,
                           cmap=cmap,
                           zorder=2,
                           alpha=1,
                           vmin=1)
        else:
            extent = (xs[0][0], xs[0][-1], ys[0][0], ys[-1][0])
            colorized = mapColors(density, level, cmap)
            colorized = mapTransparency(density, colorized, level)
            plt.imshow(colorized,
                       extent=extent,
                       cmap=cmap,
                       origin='lower',
                       interpolation='nearest',
                       zorder=2)

    smallest = min(box['lat2'] - box['lat1'], box['lon2'] - box['lon1'])

    if smallest < 1.0:
        gridIncrement = 0.1
    if smallest < 2.5:
        gridIncrement = 0.5
    elif smallest < 5:
        gridIncrement = 1.0
    elif smallest < 10:
        gridIncrement = 2.5
    elif smallest < 50:
        gridIncrement = 5.0
    else:
        gridIncrement = 45

    parallels = np.arange(-90., 90., gridIncrement)
    mapped.drawparallels(parallels, labels=[1, 0, 0, 0], alpha=.75)
    meridians = np.arange(-180., 180., gridIncrement)
    mapped.drawmeridians(meridians, labels=[0, 0, 0, 1], alpha=.75)

    if important != 'null':
        xI, yI = mapped(important[0], important[1])
        xM, yM = mapped(np.mean(lons), np.mean(lats))
        mapped.plot(xI,
                    yI,
                    'o',
                    markersize=15,
                    zorder=6,
                    markerfacecolor="white",
                    markeredgecolor=mark,
                    alpha=1.0)
        mapped.plot(xM,
                    yM,
                    'x',
                    markersize=15,
                    zorder=6,
                    markerfacecolor="white",
                    markeredgecolor=mark,
                    alpha=1.0)

    x, y = mapped(lons, lats)  # compute map proj coordinates.
    mapped.plot(x,
                y,
                'o',
                markersize=4,
                zorder=6,
                markerfacecolor=mark,
                markeredgecolor="none",
                alpha=0.30)
    if highlight != False:
        mapped.plot(x,
                    y,
                    'o',
                    markersize=4,
                    zorder=6,
                    markerfacecolor=highlight,
                    markeredgecolor="none",
                    alpha=0.03)

    title = '%s Search for "%s" with %s Related\nTweets Found from%s to %s' % (
        dataset['name'], subject, len(dataset['data']),
        times[0].strftime("%a %m/%d/%y"), times[-1].strftime("%a %m/%d/%y"))
    plt.title(title)
    if subtitle != '':
        plt.xlabel(subtitle)

    if heatmap:
        divider = make_axes_locatable(plt.gca())
        cax = divider.append_axes("right", "5%", pad="3%")
        cbar = plt.colorbar(orientation='vertical', cax=cax)
        if level != 'full':
            plt.clim([0, level])
        cbar.set_label('Number of Tweets')

    if call != 'animate' and show:
        plt.show()
    return plt
def basemap(dat,
            lat,
            lon,
            lat_min=None,
            lat_max=None,
            lon_min=None,
            lon_max=None,
            res='c',
            proj='mill',
            origin=0,
            shift=0,
            title="",
            loc=None,
            loc1=None,
            loc2=None,
            lsmask=False,
            ms_lat=None,
            ms_lon=None,
            lms=0.1,
            ms_length=None,
            uwinds=None,
            vwinds=None,
            hatch=None,
            hatch_color='none',
            gc_lat0=None,
            gc_lon0=None,
            gc_lat1=None,
            gc_lon1=None,
            gc_lat2=None,
            gc_lon2=None,
            gdists=None,
            gc_lw=.5,
            gc_color=plt.cm.jet,
            gc_contours=None,
            gc_extend='both',
            gc_cbar=False,
            font_size=8,
            asp=None,
            quiverscale=100,
            stream=None,
            dat2=None,
            dat3=None,
            dat4=None,
            dat5=None,
            dat6=None,
            area1=None,
            area2=None,
            area3=None,
            area4=None,
            area5=None,
            area6=None,
            area7=None,
            area8=None,
            area9=None,
            area10=None,
            area11=None,
            area12=None,
            area13=None,
            contours=None,
            contours2=None,
            contours3=None,
            contours4=None,
            contours5=None,
            contours6=None,
            lcontours=None,
            lcd=None,
            lclabel=None,
            clim=None,
            over=None,
            extend='neither',
            shaderelief=False,
            etopo=False,
            colors=None,
            colors2=None,
            colors3=None,
            colors4=None,
            colors5=None,
            colors6=None,
            color=plt.cm.gist_stern_r,
            colorbar=True,
            cbar_title="",
            hillshade=False,
            scale=.1,
            alpha=1,
            line_color1=None,
            line_color2=None,
            line_color3=None,
            line_color4=None,
            line_color5=None,
            line_color6=None,
            line_color7=None,
            line_color8=None,
            line_color9=None,
            line_color10=None,
            line_color11=None,
            line_color12=None,
            line_color13=None,
            line_style1='solid',
            line_style2='solid',
            line_style3='solid',
            line_style4='solid',
            line_style5='solid',
            line_style6='solid',
            line_style7='solid',
            line_style8='solid',
            line_style9='solid',
            line_style10='solid',
            line_style11='solid',
            line_style12='solid',
            line_style13='solid',
            parallels=np.arange(-90., 90., 20.),
            meridians=np.arange(0., 360., 20.),
            plabels=[1, 0, 0, 0],
            mlabels=[0, 0, 0, 1]):
    """plots a pcolormesh of 2-dim. dat on a geographical grid
		corresponding to lon and lat, optionally takes fixed colorlimits climl and climr, and saves the figure as title"""
    if proj == 'mill' or proj == 'cea' or proj == 'cyl':
        if lat_min is None:
            m = Basemap(projection=proj,
                        lat_ts=12,
                        llcrnrlon=lon.min() + shift,
                        urcrnrlon=lon.max() + shift,
                        llcrnrlat=lat.min(),
                        urcrnrlat=lat.max(),
                        resolution=res)
        else:
            m = Basemap(projection=proj,
                        lat_ts=12,
                        llcrnrlon=lon_min,
                        urcrnrlon=lon_max,
                        llcrnrlat=lat_min,
                        urcrnrlat=lat_max,
                        resolution=res)
        # m=Basemap(projection = proj, lat_ts=None,llcrnrlon=10, urcrnrlon=190, llcrnrlat=lat.min(), urcrnrlat=lat.max(),resolution = res)
        # m=Basemap(projection=proj, lat_0 = 0, lon_0 = shift,resolution = 'c')
    elif proj == 'ortho':
        m = Basemap(projection='ortho', lat_0=0., lon_0=0., resolution='c')
    elif proj == 'moll' or proj == 'hammer' or proj == 'robin':
        m = Basemap(projection=proj, lon_0=shift, resolution='c')
    elif proj == 'npstere':
        m = Basemap(projection=proj,
                    lat_0=0.,
                    lon_0=0.,
                    boundinglat=40,
                    resolution='c')
    # dat, lons = shiftgrid(0., dat, lon)
    # print lon
    lons, dat = m.shiftdata(lon, dat, lon_0=origin + shift)
    if lcd is not None:
        lons, lcd = m.shiftdata(lon, lcd, lon_0=origin + shift)
    # lons = lon
    # print lons
    if loc is not None:
        xloc, yloc = m(loc[0], loc[1])
        m.plot(xloc, yloc, marker='D', color='r', markersize=lms)
    if loc1 is not None:
        xloc1, yloc1 = m(loc1[0], loc1[1])
        m.plot(xloc1, yloc1, marker='D', color='royalblue')
    if loc2 is not None:
        xloc2, yloc2 = m(loc2[0], loc2[1])
        m.plot(xloc2, yloc2, marker='D', color='darkorange')
    # dat, lons = addcyclic(dat, lons)
    if hatch is not None:
        lons, hatch = m.shiftdata(lon, hatch, lon_0=origin + shift)
    if area1 is not None:
        lons, area1 = m.shiftdata(lon, area1, lon_0=origin + shift)
    if area2 is not None:
        lons, area2 = m.shiftdata(lon, area2, lon_0=origin + shift)
    if area3 is not None:
        lons, area3 = m.shiftdata(lon, area3, lon_0=origin + shift)
    if area4 is not None:
        lons, area4 = m.shiftdata(lon, area4, lon_0=origin + shift)
    if area5 is not None:
        lons, area5 = m.shiftdata(lon, area5, lon_0=origin + shift)
    if area6 is not None:
        lons, area6 = m.shiftdata(lon, area6, lon_0=origin + shift)
    if area7 is not None:
        lons, area7 = m.shiftdata(lon, area7, lon_0=origin + shift)
    if area8 is not None:
        lons, area8 = m.shiftdata(lon, area8, lon_0=origin + shift)
    if area9 is not None:
        lons, area9 = m.shiftdata(lon, area9, lon_0=origin + shift)
    if area10 is not None:
        lons, area10 = m.shiftdata(lon, area10, lon_0=origin + shift)
    if area11 is not None:
        lons, area11 = m.shiftdata(lon, area11, lon_0=origin + shift)
    if area12 is not None:
        lons, area12 = m.shiftdata(lon, area12, lon_0=origin + shift)
    if area13 is not None:
        lons, area13 = m.shiftdata(lon, area13, lon_0=origin + shift)
    # m=Basemap(projection='mill', lat_0 = 0, lon_0 = 160, resolution = 'c')
    Lon, Lat = np.meshgrid(lons, lat)
    x, y = m(Lon, Lat)
    # m.drawcoastlines(linewidth = .3)
    if lsmask is True:
        m.drawlsmask(land_color='.1', ocean_color='1.', resolution='h')
    else:
        m.drawcoastlines(linewidth=.3)
        m.drawcountries(linewidth=.3)
        m.drawmapboundary()
        # m.readshapefile('/Users/omarlittle/Desktop/Desktop/PIK/climatenetwork/basemap/10m_physical/ne_10m_coastline', 'scale rank', drawbounds=True)
    # m.drawmapbound)
    # m.drawcountries(linewidth = .3)
    m.drawparallels(parallels,
                    labels=plabels,
                    rotation='90',
                    linewidth=.3,
                    fontsize=font_size,
                    family='times new roman')
    m.drawmeridians(meridians,
                    labels=mlabels,
                    linewidth=.3,
                    fontsize=font_size,
                    family='times new roman')
    if etopo is True:
        m.etopo()
    if shaderelief is True:
        m.shadedrelief()
    if hillshade is True:
        m.warpimage(
            image=
            '/Users/omarlittle/Desktop/Desktop/PIK/climatenetwork/basemap/SR_50M.tif',
            scale=scale)
    if contours is None:
        cs = m.pcolormesh(x, y, dat, cmap=color, alpha=alpha)
        if clim is not None:
            cs.set_clim(clim)
    else:
        if colors is None:
            cs = m.contourf(x,
                            y,
                            dat,
                            contours,
                            alpha=alpha,
                            cmap=color,
                            extend=extend)
        else:
            cs = m.contourf(x,
                            y,
                            dat,
                            contours,
                            alpha=alpha,
                            colors=colors,
                            extend=extend)
    if contours2 is not None:
        csa = m.contourf(x,
                         y,
                         dat2,
                         contours2,
                         alpha=alpha,
                         colors=colors2,
                         extend=extend)
    if contours3 is not None:
        csb = m.contourf(x,
                         y,
                         dat3,
                         contours3,
                         alpha=alpha,
                         colors=colors3,
                         extend=extend)
    if contours4 is not None:
        csc = m.contourf(x,
                         y,
                         dat4,
                         contours4,
                         alpha=alpha,
                         colors=colors4,
                         extend=extend)
    if contours5 is not None:
        csd = m.contourf(x,
                         y,
                         dat5,
                         contours5,
                         alpha=alpha,
                         colors=colors5,
                         extend=extend)
    if contours6 is not None:
        cse = m.contourf(x,
                         y,
                         dat6,
                         contours6,
                         alpha=alpha,
                         colors=colors6,
                         extend=extend)
    if hatch is not None:
        # hat = m.contourf(x, y, hatch, [-2,0, 2], colors = 'none', hatches = [None, '////'])
        mpl.rcParams['hatch.linewidth'] = 0.1
        hat = m.contourf(x,
                         y,
                         hatch, [-2, 0, 2],
                         colors='none',
                         hatches=[None, '///////'])
    if lcontours is not None:
        lc = m.contour(x, y, lcd, lcontours, colors='black', linewidths=.2)
        if lclabel is True:
            plt.clabel(lc, inline=1, fontsize=8, fmt='%d')
    if area1 is not None:
        cs1 = m.contour(x,
                        y,
                        area1, [0],
                        linestyles=line_style1,
                        linewidths=1.,
                        colors=line_color1)
    if area2 is not None:
        cs2 = m.contour(x,
                        y,
                        area2, [0],
                        linestyles=line_style2,
                        linewidths=1.,
                        colors=line_color2)
    if area3 is not None:
        cs3 = m.contour(x,
                        y,
                        area3, [0],
                        linestyles=line_style3,
                        linewidths=1.,
                        colors=line_color3)
    if area4 is not None:
        cs4 = m.contour(x,
                        y,
                        area4, [0],
                        linestyles=line_style4,
                        linewidths=1.,
                        colors=line_color4)
    if area5 is not None:
        cs5 = m.contour(x,
                        y,
                        area5, [0],
                        linestyles=line_style5,
                        linewidths=1.,
                        colors=line_color5)
    if area6 is not None:
        cs6 = m.contour(x,
                        y,
                        area6, [0],
                        linestyles=line_style6,
                        linewidths=1.,
                        colors=line_color6)
    if area7 is not None:
        cs7 = m.contour(x,
                        y,
                        area7, [0],
                        linestyles=line_style7,
                        linewidths=1.,
                        colors=line_color7)
    if area8 is not None:
        cs8 = m.contour(x,
                        y,
                        area8, [0],
                        linestyles=line_style8,
                        linewidths=1.,
                        colors=line_color8)
    if area9 is not None:
        cs9 = m.contour(x,
                        y,
                        area9, [0],
                        linestyles=line_style9,
                        linewidths=1.,
                        colors=line_color9)
    if area10 is not None:
        cs10 = m.contour(x,
                         y,
                         area10, [0],
                         linestyles=line_style10,
                         linewidths=.5,
                         colors=line_color10)
    if area11 is not None:
        cs11 = m.contour(x,
                         y,
                         area11, [0],
                         linestyles=line_style11,
                         linewidths=.5,
                         colors=line_color11)
    if area12 is not None:
        cs12 = m.contour(x,
                         y,
                         area12, [0],
                         linestyles=line_style12,
                         linewidths=.5,
                         colors=line_color12)
    if area13 is not None:
        cs13 = m.contour(x,
                         y,
                         area13, [0],
                         linestyles=line_style13,
                         linewidths=.5,
                         colors=line_color13)

    if stream is not None:
        print "be careful ..."
        lons, stream[0] = m.shiftdata(lon, stream[0], lon_0=origin + shift)
        lons, stream[1] = m.shiftdata(lon, stream[1], lon_0=origin + shift)
        lons, stream[2] = m.shiftdata(lon, stream[2], lon_0=origin + shift)
        xxs, yys = m.makegrid(stream[0].shape[1],
                              stream[0].shape[0],
                              returnxy=True)[2:4]
        st = m.streamplot(xxs,
                          yys,
                          stream[1],
                          stream[2],
                          color="w",
                          cmap=plt.cm.spectral,
                          arrowsize=.5,
                          density=3,
                          linewidth=.5)
    FP = FontProperties()
    FP.set_family('times new roman')
    FP.set_size('%d' % font_size)
    if uwinds is not None:
        lons, uwinds = m.shiftdata(lon, uwinds, lon_0=origin + shift)
        lons, vwinds = m.shiftdata(lon, vwinds, lon_0=origin + shift)
        u = uwinds
        v = vwinds
        #ugrid,newlons = shiftgrid(180.,u,lon,start=False)
        #vgrid,newlons = shiftgrid(180.,v,lon,start=False)
        # transform vectors to projection grid.
        #uproj,vproj,xx,yy = m.transform_vector(ugrid,vgrid,newlons,lat,31,31,returnxy=True,masked=True)
        # now plot.
        # scale =
        Q = m.quiver(x[::asp, ::asp],
                     y[::asp, ::asp],
                     u[::asp, ::asp],
                     v[::asp, ::asp],
                     pivot='mid',
                     units='width',
                     scale=quiverscale)
        # make quiver key
        # qk = plt.quiverkey(Q, 0.85, 0.05, 5, '5 m/s', coordinates = 'figure', labelpos='W', labelcolor = 'black', fontproperties = {'family':'times new roman', 'size':'10', 'style':'normal'})
    if gc_lat0 is not None:
        for i in xrange(gc_lat1.shape[0]):
            if gc_color is None:
                gc = m.drawgreatcircle(gc_lon0,
                                       gc_lat0,
                                       gc_lon1[i],
                                       gc_lat1[i],
                                       linewidth=gc_lw,
                                       color=plt.cm.jet(.0001),
                                       alpha=.02)
            else:
                gc = m.drawgreatcircle(
                    gc_lon0,
                    gc_lat0,
                    gc_lon1[i],
                    gc_lat1[i],
                    linewidth=gc_lw,
                    color=gc_color(int(5 * gdists[i] / gdists.max()) / 5.,
                                   alpha=.02 + gdists[i] / gdists.max()))
    if gc_lat2 is not None:
        for i in xrange(gc_lat2.shape[0]):
            gc = m.drawgreatcircle(gc_lon0,
                                   gc_lat0,
                                   gc_lon2[i],
                                   gc_lat2[i],
                                   linewidth=gc_lw,
                                   color=plt.cm.jet(.9999),
                                   alpha=.3)
    if loc is not None:
        xloc, yloc = m(loc[0], loc[1])
        m.plot(xloc, yloc, marker='D', color='r', markersize=0.5)
    if ms_lat is not None:
        m.drawmapscale(lat=ms_lat,
                       lon=ms_lon,
                       lon0=0.,
                       lat0=0.,
                       length=ms_length,
                       barstyle='fancy')
    if colorbar is True:
        ticks_font = matplotlib.font_manager.FontProperties(
            family='times new roman',
            style='normal',
            size=font_size,
            weight='normal',
            stretch='normal')
        if gc_cbar == True:
            cs_fake = plt.contourf(x,
                                   y,
                                   np.ones_like(dat) * -1e7,
                                   gc_contours,
                                   cmap=gc_color,
                                   extend='neither')
            cbar = m.colorbar(cs_fake, extend=extend, orientation='horizontal')
        else:
            cbar = m.colorbar(cs, extend=extend)
        if cbar_title is not None:
            cbar.ax.set_ylabel(cbar_title,
                               fontsize=font_size,
                               family='times new roman')
        for label in cbar.ax.get_yticklabels():
            label.set_fontproperties(ticks_font)
    if over is not None:
        cs.cmap.set_over(over)
    plt.title('%s' % title, fontsize=font_size)
    return cs
Example #21
0
def map_cube(cube,
             projection='lonlat',
             limit=False,
             lon_0=None,
             lat_0=None,
             show_cube=True,
             show_footprint=False,
             show_pts=True,
             show_gc=True,
             show_labels=True,
             bg='Titan_VIMS_ISS',
             wvln=2.03,
             fig=None,
             debug=False):
    """Plot projected cube on a map.

    Parameters
    ----------
    cube: pyvims.VIMS
        Cube to project.
    projection: str, optional
        Projection name. Case sensitive. Avalaible:
            - ``lonlat``: Latitude/Longitude cylindical projection.
            - ``mollweide``: Mollweide projection.
            - ``polar``: Polar projection (North if ``SC lat > 0``, South otherwise).
            - ``ortho``: Cassini fov projection (centered on
                         SC lon/lat if ``lon_0``/``lat_0`` are not provided).
    limit: bool, optional
        Limit FOV on cube corners.
    lon_0: float, optional
        Optional centered longitude for ``ortho`` projection. Set to ``SC lon`` otherwise.
    lat_0: float, optional
        Optional centered lattidue for ``ortho`` or ``polar`` projection.
        Set to ``SC lat`` (for ``ortho``) or ``50ºN/S`` otherwise.
    show_cube: bool, optional
        Show cube data.
    show_footprint: bool, optional
        Show cube footprint.
    show_pts: bool, optional
        Show the SC and SS points locations.
    show_gc: bool, optional
        Show the SC and SS great cricle.
    show_labels: bool, optional
        Show map labels.
    bg: str, optional
        Background frame name.
    wvln: float, optional
        Wavelength to display.
    fig: matplotlib.figure
        Optional matplotlib figure object.
    debug: bool, optional
        Debug mode. Draw cube triangules.

    Raises
    ------
    ValueError
        If the project name is unknown.

    Return
    ------
    mpl_toolkits.basemap.Basemap
        Matplotlib basemap object.

    """

    im = cube.getImg(wvln=wvln)
    moon = SPICE_MOON(cube.target)
    _, SC_lon, SC_lat = moon.SC(cube.time)
    _, SS_lon, SS_lat = moon.SS(cube.time)
    # FOV apparent radius
    ra = np.sqrt(1 - (moon.radius / moon.dist(cube.time))**2)

    hemi = int(np.sign(SC_lat))

    if fig is None:
        fig = plt.figure(figsize=(12, 12))

    if projection == 'lonlat':
        m = Basemap(projection='cyl',
                    llcrnrlat=-90,
                    urcrnrlat=90,
                    llcrnrlon=-180,
                    urcrnrlon=180)

    elif projection == 'mollweide':
        m = Basemap(projection='moll', lon_0=0)

    elif projection == 'polar':
        if SC_lat > 0:
            p = 'npaeqd'
            if lat_0 is None:
                lat_0 = 50
        else:
            p = 'spaeqd'
            if lat_0 is None:
                lat_0 = -50
        m = Basemap(projection=p, boundinglat=lat_0, lon_0=0)

    elif projection == 'ortho':
        if lon_0 is None:
            lon_0 = SC_lon
        if lat_0 is None:
            lat_0 = SC_lat
        m = Basemap(projection='ortho', lat_0=lat_0, lon_0=lon_0)

    else:
        raise ValueError('Projection `%s` unknown.' % projection)

    if bg is not None:
        if bg.upper() == 'TITAN_VIMS_ISS':
            bg = os.path.join(os.path.dirname(__file__), 'bg',
                              'Titan_VIMS_ISS.jpg')
        elif bg.upper() == 'TITAN_VIMS_ISS-HR':
            bg = os.path.join(os.path.dirname(__file__), 'bg',
                              'Titan_VIMS_ISS-HR.jpg')
        elif bg.upper() == 'TITAN_ISS':
            bg = os.path.join(os.path.dirname(__file__), 'bg', 'Titan_ISS.jpg')
        elif bg.upper() == 'TITAN_ISS-HR':
            bg = os.path.join(os.path.dirname(__file__), 'bg',
                              'Titan_ISS-HR.jpg')

        m.warpimage(bg)

    lon = (cube.lon + 180) % 360 - 180
    lat = cube.lat

    f_lon, f_lat = footprint(lon, lat, SC_lon, SC_lat, ra=ra)

    if projection == 'lonlat':
        f_lon, f_lat = contour_lonlat(f_lon, f_lat, hemi)
        lon, lat, im = duplicate_lonlat(lon,
                                        lat,
                                        im,
                                        hemi,
                                        f_lon,
                                        f_lat,
                                        dlon=15)

    if projection == 'mollweide':
        f_lon, f_lat = contour_mollweide(f_lon, f_lat, hemi)

    contour = m(f_lon, f_lat)

    limb = np.isnan(lon)
    pts = np.array(m(lon[~limb], lat[~limb]))

    if show_cube:
        im = im[~limb]

        # Discard ortho projected pts at 1e30
        if (pts > 1e29).any():
            x, y = pts
            cond = (x < 1e29) & (y < 1e29)
            pts = np.array([x[cond], y[cond]])
            im = im[cond]

        triang = triangles_in_coutour(pts, contour)

        if debug:
            plt.triplot(tri.Triangulation(*pts), color='r')
            plt.triplot(triang)

        plt.tricontourf(triang, im, 255, cmap='gray')

    if show_footprint:
        plt.plot(*contour, 'w-')

    if show_gc:
        SC_gc = great_circle(SC_lon, SC_lat, ra=ra)
        SS_gc = great_circle(SS_lon, SS_lat)

        if projection == 'lonlat':
            SC_gc = contour_lonlat(*SC_gc, np.sign(SC_lat))
            SS_gc = contour_lonlat(*SS_gc, np.sign(SS_lat))

        elif projection == 'mollweide':
            SC_gc = contour_mollweide(*SC_gc, np.sign(SC_lat))
            SS_gc = contour_mollweide(*SS_gc, np.sign(SS_lat))

        SC_gc = np.array(m(*SC_gc))
        SS_gc = np.array(m(*SS_gc))

        if projection == 'ortho':
            SC_gc[SC_gc > 1e29] = np.nan
            SS_gc[SS_gc > 1e29] = np.nan

        plt.plot(*SC_gc, 'b-')
        plt.plot(*SS_gc, '-', color='gold')

    if show_pts:
        SC_pt = m(SC_lon, SC_lat)
        SS_pt = m(SS_lon, SS_lat)

        plt.scatter(*SC_pt, c='b', s=50)
        plt.scatter(*SS_pt, c='gold', s=50)

        if limit:
            xmin, xmax = np.min(pts[0]), np.max(pts[0])
            ymin, ymax = np.min(pts[1]), np.max(pts[1])

        else:
            ax = plt.gca()
            xmin, xmax = ax.get_xlim()
            ymin, ymax = ax.get_ylim()

        if xmin < SC_pt[0] < xmax and ymin < SC_pt[1] < ymax:
            plt.text(*SC_pt, 'SC\n\n', color='b', va='center', ha='center')

        if xmin < SS_pt[0] < xmax and ymin < SS_pt[1] < ymax:
            plt.text(*SS_pt, 'SS\n\n', color='gold', va='center', ha='center')

    # Define longitudes and latitudes grid
    lons = np.linspace(-180, 180, 19)
    lats = np.linspace(-90, 90, 19)

    # Map labels
    mlabels, plabels = [0, 0, 0, 0], [0, 0, 0, 0]

    if show_labels and not limit:
        if projection == 'lonlat':
            mlabels, plabels = [0, 0, 0, 1], [1, 0, 0, 0]
        elif projection == 'mollweide':
            plabels = [1, 1, 0, 0]
        elif projection == 'polar':
            mlabels = [1, 1, 1, 1]

    # Draw meridians and parallels
    m.drawmeridians(lons, linewidth=.25, color='w', labels=mlabels)
    m.drawparallels(lats, linewidth=.25, color='w', labels=plabels)
    m.drawmeridians([0], linewidth=.2, color='r', dashes=[1, 0])
    m.drawparallels([0], linewidth=.2, color='r', dashes=[1, 0])

    if limit:
        xmin, xmax = np.min(pts[0]), np.max(pts[0])
        ymin, ymax = np.min(pts[1]), np.max(pts[1])

        if projection == 'lonlat':
            xmin, xmax = max([xmin, -180]), min([xmax, 180])
            ymin, ymax = max([ymin, -90]), min([ymax, 90])

        plt.xlim(xmin, xmax)
        plt.ylim(ymin, ymax)

    if debug and projection == 'lonlat':
        plt.xlim(-180 - dlon - 5, 180 + dlon + 5)
        plt.ylim(-90 - dlat - 5, 90 + dlat + 5)

    return m
Example #22
0
class Window(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.setWindowIcon(QtGui.QIcon(iconpath))
        self.ui = layout.Ui_MainWindow()
        self.ui.setupUi(self)
        self.instaseis = False
        self.instaseis_db = None
        self.sac_file = None
        self.stream = None
        self.stream_copy = None
        self.stream_slice = None
        self.source = None
        self.window_start = None
        self.window_end = None
        self.sigmax = None
        self.nbands = 200
        self.gabor_matrix = np.zeros((self.nbands, self.nbands))
        self.periods = np.linspace(self.ui.min_period.value(),
                                   self.ui.max_period.value(), self.nbands)
        self.period_pick = None
        self.vel_pick = None
        self.dist_km = None

        if self.ui.planet.currentText() == 'Earth':
            self.planet_radius = 6371.0
        elif self.ui.planet.currentText() == 'Mars':
            self.planet_radius = 3385.5
        elif self.ui.planet.currentText() == 'Europa':
            self.planet_radius = 1565.0

        m_rr = 3.98E13
        m_tt = 0.0
        m_pp = -3.98E13
        m_rt = 0.0
        m_rp = 0.0
        m_tp = 0.0
        self.ui.m_rr.setValue(m_rr)
        self.ui.m_tt.setValue(m_tt)
        self.ui.m_pp.setValue(m_pp)
        self.ui.m_rt.setValue(m_rt)
        self.ui.m_rp.setValue(m_rp)
        self.ui.m_tp.setValue(m_tp)
        self.ui.stlo.setValue(30.0)
        self.ui.stla.setValue(0.0)
        self.ui.evlo.setValue(0.0)
        self.ui.evla.setValue(0.0)
        self.ui.evdp.setValue(0.0)
        self.ui.window_start.setMinimum(0.0)
        self.ui.window_start.setMaximum(1.0)
        self.ui.window_start.setValue(0.0)
        self.ui.window_end.setMinimum(0.0)
        self.ui.window_end.setMaximum(1.0)
        self.ui.window_end.setValue(1.0)

        #TODO move this eventually so it only gets plotted after MFT analysis
        #self.plot_gabor()
        self.plot_map()

    def on_open_sac_button_released(self):
        cwd = os.getcwd()
        self.sac_file = str(
            QtGui.QFileDialog.getOpenFileName(self, "choose sac file", cwd))
        if not self.sac_file:
            return

        self.stream = obspy.read(self.sac_file)
        self.stream_copy = self.stream.copy()
        time = self.get_time_axis
        self.ui.window_start.setMaximum(time[-1])
        self.ui.window_end.setMaximum(time[-1])
        self.ui.window_start.setValue(time[0])
        self.ui.window_end.setValue(time[-1])
        self.instaseis = False
        self.ui.stlo.setValue(self.stream[0].stats.sac['stlo'])
        self.ui.stla.setValue(self.stream[0].stats.sac['stla'])
        self.ui.evlo.setValue(self.stream[0].stats.sac['evlo'])
        self.ui.evla.setValue(self.stream[0].stats.sac['evla'])
        self.ui.evdp.setValue(self.stream[0].stats.sac['evdp'])
        self.time_window = None
        self.update()

    def on_open_instaseis_button_released(self):
        cwd = os.getcwd()
        self.folder = str(
            QtGui.QFileDialog.getExistingDirectory(
                self, "choose instaseis database folder", cwd))
        if not self.folder:
            return

        self.instaseis_db = instaseis.open_db(self.folder)
        self.source = instaseis.Source(latitude=self.ui.evla.value(),
                                       longitude=self.ui.evlo.value(),
                                       depth_in_m=self.ui.evdp.value() * 1000.,
                                       m_rr=self.ui.m_rr.value(),
                                       m_tt=self.ui.m_tt.value(),
                                       m_pp=self.ui.m_pp.value(),
                                       m_rt=self.ui.m_rt.value(),
                                       m_rp=self.ui.m_rp.value(),
                                       m_tp=self.ui.m_pp.value())
        self.receiver = instaseis.Receiver(latitude=self.ui.stla.value(),
                                           longitude=self.ui.stlo.value())
        self.stream = self.instaseis_db.get_seismograms(
            source=self.source,
            receiver=self.receiver,
            components=str(self.ui.component.currentText()),
            kind=str(self.ui.motion_type.currentText()),
            remove_source_shift=True)
        self.stream[0].stats.sac = {}
        self.stream[0].stats.sac['o'] = 0.0
        self.stream[0].stats.sac['gcarc'] = geodetics.locations2degrees(
            float(self.ui.evla.value()), float(self.ui.evlo.value()),
            float(self.ui.stla.value()), float(self.ui.stlo.value()))
        self.stream_copy = self.stream.copy()

        time = self.get_time_axis
        self.ui.window_start.setMaximum(time[-1])
        self.ui.window_end.setMaximum(time[-1])
        self.ui.window_start.setValue(time[0])
        self.ui.window_end.setValue(time[-1])
        self.instaseis = True
        self.plot_map()
        self.update()

    #def on_integrate_button_released(self):
    #    if not self.stream:
    #        return
    #    self.stream = self.stream.integrate()
    #
    #     self.update()
    #def on_differentiate_button_released(self):
    #    if not self.stream:
    #        return
    #    self.stream = self.stream.differentiate()
    #    self.update()

    def on_save_curve_button_released(self):
        print 'THE DISPERSION CURVE SHOULD BE SAVED'
        np.savetxt('dispersion_curve.dat',
                   np.c_[self.period_pick, self.vel_pick],
                   fmt='%5f')
        self.update()

    def on_calc_dispersion_button_released(self):
        #self.gabor_matrix = np.zeros((self.stream_slice.stats.npts,
        #self.stream_slice.stats.npts))
        #self.gabor_matrix[:,0] = self.stream_slice[0].data
        #for i in range(0,self.gabor_matrix.shape[0]):
        #    self.gabor_matrix[i,:] = self.stream_slice.data
        self.multiple_filter()
        self.plot_gabor()

        filename = 'grpvel_dispersion.dat'
        fout = open(filename, 'w')
        for i in range(0, len(self.period_pick)):
            fout.write('{} {}\n'.format(1. / self.period_pick[i],
                                        self.vel_pick[i]))
        fout.close()

        self.update()

    def multiple_filter(self, Tmin=20.0, Tmax=200.0):
        #time = self.get_time_axis
        self.km_per_deg = (2. * np.pi * self.planet_radius / 360.0)
        self.dist_km = self.stream[0].stats.sac['gcarc'] * self.km_per_deg

        try:
            self.time_window = np.linspace(self.ui.window_start.value(),
                                           self.ui.window_end.value(),
                                           len(self.stream_slice.data))
        except TypeError:
            # time = np.linspace(100,200,100)
            raise ValueError('error in self.time_window')

        #self.periods = np.linspace(Tmin,Tmax,nbands)
        self.gabor_matrix = np.zeros(
            (len(self.time_window), len(self.periods)))
        print 'GABOR MATRIX SHAPE', self.gabor_matrix.shape
        self.period_pick = []
        self.vel_pick = []

        if self.ui.mft_type.currentText() == 'gaussian':
            for i, period in enumerate(self.periods):
                self.stream_slice_copy = self.stream_slice.copy()
                tr = self.stream_slice_copy
                dcol = gauss_filter(tr.data,
                                    tr.stats.sampling_rate,
                                    w_0=(1 / period),
                                    alpha=self.ui.alpha.value())
                env = np.abs(hilbert(dcol.real))
                self.gabor_matrix[:, i] = env

                if np.max(env) > 0.0:
                    self.vel_pick.append(self.dist_km /
                                         self.time_window[np.argmax(env)])
                    self.period_pick.append(period)

        elif self.ui.mft_type.currentText() == 'butterworth':
            for i, period in enumerate(self.periods):
                #Tstart = period / 1.2
                #Tend = period + (period / 2.0)
                freqmin = 1. / period - (self.ui.gamma.value() * (1. / period))
                freqmax = 1. / period + (self.ui.gamma.value() * (1. / period))
                #freqmin = 1. / Tend
                #freqmax = 1. / Tstart
                self.stream_slice_copy = self.stream_slice.copy()

                if freqmin > 0:
                    tr = self.stream_slice_copy.filter(
                        'bandpass',
                        freqmin=freqmin,
                        freqmax=freqmax,
                        corners=self.ui.corners.value(),
                        zerophase=True)
                else:
                    tr = self.stream_slice_copy.filter('lowpass', freq=freqmax)

                dcol = tr.data
                env = np.abs(hilbert(dcol.real))
                self.gabor_matrix[:, i] = env

                if np.max(env) > 0.0:
                    self.vel_pick.append(self.dist_km /
                                         self.time_window[np.argmax(env)])
                    self.period_pick.append(period)

        elif self.ui.mft_type.currentText() == 'bessel':
            for i, period in enumerate(self.periods):
                self.stream_slice_copy = self.stream_slice.copy()
                tr = self.stream_slice_copy
                st_new = obspy.Stream()
                st_new += tr
                #dcol = gauss_filter(tr.data,tr.stats.sampling_rate,
                #    w_0=(1/period),alpha=self.ui.alpha.value())

                #dcol = stream_filter_bessel(st_new,(1./period) - (self.ui.gamma.value()*(1./period)),
                #                                   (1./period) + (self.ui.gamma.value()*(1./period)),
                #                                    corners=self.ui.corners.value(),zerophase=True)[0].data
                dcol = stream_filter_bessel(st_new,
                                            1. / period,
                                            self.ui.gamma.value(),
                                            corners=self.ui.corners.value(),
                                            zerophase=True)[0].data
                env = np.abs(hilbert(dcol.real))
                self.gabor_matrix[:, i] = env

                if np.max(env) > 0.0:
                    self.vel_pick.append(self.dist_km /
                                         self.time_window[np.argmax(env)])
                    self.period_pick.append(period)

        else:
            raise ValueError('filter type', kind, ' not implemented')

        #np.savetxt('dispersion_curve.dat',np.c_[self.period_pick,self.vel_pick],fmt='%5f')

        self.update()

    @property
    def mt_source(self):
        m_rr = float(self.ui.m_rr.value())
        m_tt = float(self.ui.m_tt.value())
        m_pp = float(self.ui.m_pp.value())
        m_rt = float(self.ui.m_rt.value())
        m_rp = float(self.ui.m_rp.value())
        m_tp = float(self.ui.m_tp.value())
        source = instaseis.Source(latitude=self.ui.evla.value(),
                                  longitude=self.ui.evlo.value(),
                                  depth_in_m=self.ui.evdp.value(),
                                  m_rr=m_rr,
                                  m_tt=m_tt,
                                  m_pp=m_pp,
                                  m_rt=m_rt,
                                  m_rp=m_rp,
                                  m_tp=m_tp)
        return source

    @property
    def instaseis_receiver(self):
        longitude = float(self.ui.stlo.value())
        latitude = float(self.ui.stla.value())
        rec = instaseis.Receiver(latitude=latitude, longitude=longitude)
        return rec

    @property
    def get_time_axis(self):
        time = np.linspace(
            self.stream[0].stats.sac['o'],
            self.stream[0].stats.npts * self.stream[0].stats.delta,
            self.stream[0].stats.npts)
        return time

    def on_m_rr_valueChanged(self, *args):
        if self.instaseis:
            src = self.mt_source
            rec = self.instaseis_receiver
            self.stream = self.instaseis_db.get_seismograms(
                source=src,
                receiver=rec,
                components=str(self.ui.component.currentText()),
                kind=str(self.ui.motion_type.currentText()),
                remove_source_shift=True)
            self.stream[0].stats.sac = {}
            self.stream[0].stats.sac['o'] = 0.0
            self.stream_copy = self.stream.copy()
        self.update()

    def on_m_tt_valueChanged(self, *args):
        if self.instaseis:
            src = self.mt_source
            rec = self.instaseis_receiver
            self.stream = self.instaseis_db.get_seismograms(
                source=src,
                receiver=rec,
                components=str(self.ui.component.currentText()),
                kind=str(self.ui.motion_type.currentText()),
                remove_source_shift=True)
            self.stream[0].stats.sac = {}
            self.stream[0].stats.sac['o'] = 0.0
            self.stream[0].stats.sac['gcarc'] = geodetics.locations2degrees(
                float(self.ui.evla.value()), float(self.ui.evlo.value()),
                float(self.ui.stla.value()), float(self.ui.stlo.value()))
            self.stream_copy = self.stream.copy()
        self.update()

    def on_m_pp_valueChanged(self, *args):
        if self.instaseis:
            src = self.mt_source
            rec = self.instaseis_receiver
            self.stream = self.instaseis_db.get_seismograms(
                source=src,
                receiver=rec,
                components=str(self.ui.component.currentText()),
                kind=str(self.ui.motion_type.currentText()),
                remove_source_shift=True)
            self.stream[0].stats.sac = {}
            self.stream[0].stats.sac['o'] = 0.0
            self.stream[0].stats.sac['gcarc'] = geodetics.locations2degrees(
                float(self.ui.evla.value()), float(self.ui.evlo.value()),
                float(self.ui.stla.value()), float(self.ui.stlo.value()))
            self.stream_copy = self.stream.copy()
        self.update()

    def on_m_rt_valueChanged(self, *args):
        if self.instaseis:
            src = self.mt_source
            rec = self.instaseis_receiver
            self.stream = self.instaseis_db.get_seismograms(
                source=src,
                receiver=rec,
                components=str(self.ui.component.currentText()),
                kind=str(self.ui.motion_type.currentText()),
                remove_source_shift=True)
            self.stream[0].stats.sac = {}
            self.stream[0].stats.sac['o'] = 0.0
            self.stream[0].stats.sac['gcarc'] = geodetics.locations2degrees(
                float(self.ui.evla.value()), float(self.ui.evlo.value()),
                float(self.ui.stla.value()), float(self.ui.stlo.value()))
            self.stream_copy = self.stream.copy()
        self.update()

    def on_m_rp_valueChanged(self, *args):
        if self.instaseis:
            src = self.mt_source
            rec = self.instaseis_receiver
            self.stream = self.instaseis_db.get_seismograms(
                source=src,
                receiver=rec,
                components=str(self.ui.component.currentText()),
                kind=str(self.ui.motion_type.currentText()),
                remove_source_shift=True)
            self.stream[0].stats.sac = {}
            self.stream[0].stats.sac['o'] = 0.0
            self.stream[0].stats.sac['gcarc'] = geodetics.locations2degrees(
                float(self.ui.evla.value()), float(self.ui.evlo.value()),
                float(self.ui.stla.value()), float(self.ui.stlo.value()))
            self.stream_copy = self.stream.copy()
        self.update()

    def on_m_tp_valueChanged(self, *args):
        if self.instaseis:
            src = self.mt_source
            rec = self.instaseis_receiver
            self.stream = self.instaseis_db.get_seismograms(
                source=src,
                receiver=rec,
                components=str(self.ui.component.currentText()),
                kind=str(self.ui.motion_type.currentText()),
                remove_source_shift=True)
            self.stream[0].stats.sac = {}
            self.stream[0].stats.sac['o'] = 0.0
            self.stream[0].stats.sac['gcarc'] = geodetics.locations2degrees(
                float(self.ui.evla.value()), float(self.ui.evlo.value()),
                float(self.ui.stla.value()), float(self.ui.stlo.value()))
            self.stream_copy = self.stream.copy()
        self.update()

    def on_evdp_valueChanged(self, *args):
        if self.instaseis:
            src = self.mt_source
            rec = self.instaseis_receiver
            self.stream = self.instaseis_db.get_seismograms(
                source=src,
                receiver=rec,
                components=str(self.ui.component.currentText()),
                kind=str(self.ui.motion_type.currentText()),
                remove_source_shift=True)
            self.stream[0].stats.sac = {}
            self.stream[0].stats.sac['o'] = 0.0
            self.stream[0].stats.sac['gcarc'] = geodetics.locations2degrees(
                float(self.ui.evla.value()), float(self.ui.evlo.value()),
                float(self.ui.stla.value()), float(self.ui.stlo.value()))
            self.stream_copy = self.stream.copy()
        self.update()

    def on_evlo_valueChanged(self, *args):
        if self.instaseis:
            src = self.mt_source
            rec = self.instaseis_receiver
            self.stream = self.instaseis_db.get_seismograms(
                source=src,
                receiver=rec,
                components=str(self.ui.component.currentText()),
                kind=str(self.ui.motion_type.currentText()),
                remove_source_shift=True)
            self.stream[0].stats.sac = {}
            self.stream[0].stats.sac['o'] = 0.0
            self.stream[0].stats.sac['gcarc'] = geodetics.locations2degrees(
                float(self.ui.evla.value()), float(self.ui.evlo.value()),
                float(self.ui.stla.value()), float(self.ui.stlo.value()))
            self.stream_copy = self.stream.copy()
        self.plot_map()
        self.update()

    def on_evla_valueChanged(self, *args):
        if self.instaseis:
            src = self.mt_source
            rec = self.instaseis_receiver
            self.stream = self.instaseis_db.get_seismograms(
                source=src,
                receiver=rec,
                components=str(self.ui.component.currentText()),
                kind=str(self.ui.motion_type.currentText()),
                remove_source_shift=True)
            self.stream[0].stats.sac = {}
            self.stream[0].stats.sac['o'] = 0.0
            self.stream[0].stats.sac['gcarc'] = geodetics.locations2degrees(
                float(self.ui.evla.value()), float(self.ui.evlo.value()),
                float(self.ui.stla.value()), float(self.ui.stlo.value()))
            self.stream_copy = self.stream.copy()
        self.plot_map()
        self.update()

    def on_stlo_valueChanged(self, *args):
        if self.instaseis:
            src = self.mt_source
            rec = self.instaseis_receiver
            self.stream = self.instaseis_db.get_seismograms(
                source=src,
                receiver=rec,
                components=str(self.ui.component.currentText()),
                kind=str(self.ui.motion_type.currentText()),
                remove_source_shift=True)
            self.stream[0].stats.sac = {}
            self.stream[0].stats.sac['o'] = 0.0
            self.stream[0].stats.sac['gcarc'] = geodetics.locations2degrees(
                float(self.ui.evla.value()), float(self.ui.evlo.value()),
                float(self.ui.stla.value()), float(self.ui.stlo.value()))
            self.stream_copy = self.stream.copy()
        self.plot_map()
        self.update()

    def on_stla_valueChanged(self, *args):
        if self.instaseis:
            src = self.mt_source
            rec = self.instaseis_receiver
            self.stream = self.instaseis_db.get_seismograms(
                source=src,
                receiver=rec,
                components=str(self.ui.component.currentText()),
                kind=str(self.ui.motion_type.currentText()),
                remove_source_shift=True)
            self.stream[0].stats.sac = {}
            self.stream[0].stats.sac['o'] = 0.0
            self.stream[0].stats.sac['gcarc'] = geodetics.locations2degrees(
                float(self.ui.evla.value()), float(self.ui.evlo.value()),
                float(self.ui.stla.value()), float(self.ui.stlo.value()))
            self.stream_copy = self.stream.copy()
        self.plot_map()
        self.update()

    def on_min_period_valueChanged(self, *args):
        self.periods = np.linspace(self.ui.min_period.value(),
                                   self.ui.max_period.value(), self.nbands)
        self.update()

    def on_max_period_valueChanged(self, *args):
        self.periods = np.linspace(self.ui.min_period.value(),
                                   self.ui.max_period.value(), self.nbands)
        self.update()

    def on_component_currentIndexChanged(self, *args):
        if self.instaseis:
            src = self.mt_source
            rec = self.instaseis_receiver
            self.stream = self.instaseis_db.get_seismograms(
                source=src,
                receiver=rec,
                components=str(self.ui.component.currentText()),
                kind=str(self.ui.motion_type.currentText()),
                remove_source_shift=True)
            self.stream[0].stats.sac = {}
            self.stream[0].stats.sac['o'] = 0.0
            self.stream[0].stats.sac['gcarc'] = geodetics.locations2degrees(
                float(self.ui.evla.value()), float(self.ui.evlo.value()),
                float(self.ui.stla.value()), float(self.ui.stlo.value()))
            self.stream_copy = self.stream.copy()
        self.update()

    def on_mft_type_currentIndexChanged(self, *args):
        if self.instaseis:
            src = self.mt_source
            rec = self.instaseis_receiver
            self.stream = self.instaseis_db.get_seismograms(
                source=src,
                receiver=rec,
                components=str(self.ui.component.currentText()),
                kind=str(self.ui.motion_type.currentText()),
                remove_source_shift=True)
            self.stream[0].stats.sac = {}
            self.stream[0].stats.sac['o'] = 0.0
            self.stream[0].stats.sac['gcarc'] = geodetics.locations2degrees(
                float(self.ui.evla.value()), float(self.ui.evlo.value()),
                float(self.ui.stla.value()), float(self.ui.stlo.value()))
            self.stream_copy = self.stream.copy()
        self.update()

    def on_motion_type_currentIndexChanged(self, *args):
        if self.instaseis:
            src = self.mt_source
            rec = self.instaseis_receiver
            self.stream = self.instaseis_db.get_seismograms(
                source=src,
                receiver=rec,
                components=str(self.ui.component.currentText()),
                kind=str(self.ui.motion_type.currentText()),
                remove_source_shift=True)
            self.stream[0].stats.sac = {}
            self.stream[0].stats.sac['o'] = 0.0
            self.stream[0].stats.sac['gcarc'] = geodetics.locations2degrees(
                float(self.ui.evla.value()), float(self.ui.evlo.value()),
                float(self.ui.stla.value()), float(self.ui.stlo.value()))
            self.stream_copy = self.stream.copy()
        self.update()

    def on_planet_currentIndexChanged(self, *args):

        if self.ui.planet.currentText() == 'Earth':
            self.planet_radius = 6371.0
        elif self.ui.planet.currentText() == 'Mars':
            self.planet_radius = 3385.5
        elif self.ui.planet.currentText() == 'Europa':
            self.planet_radius = 1565.0
        print self.planet_radius
        self.update()

    def on_window_start_valueChanged(self, *args):
        t_start = float(self.ui.window_start.value())
        t_end = float(self.ui.window_end.value())
        #self.stream_slice = self.stream[0].slice(
        #    self.stream[0].stats.starttime + t_start,
        #    self.stream[0].stats.starttime + t_end)
        self.stream_slice = self.stream_copy[0].slice(
            self.stream_copy[0].stats.starttime + t_start,
            self.stream_copy[0].stats.starttime + t_end)
        self.stream = self.stream_copy
        self.update()

    def on_window_end_valueChanged(self, *args):
        t_start = float(self.ui.window_start.value())
        t_end = float(self.ui.window_end.value())
        self.stream_slice = self.stream[0].slice(
            self.stream[0].stats.starttime + t_start,
            self.stream[0].stats.starttime + t_end)
        self.stream = self.stream_copy
        self.update()

    def on_alpha_valueChanged(self, *args):
        self.update()

    def on_snr_value_valueChanged(self, band_limited=True, *args):
        self.stream = self.stream_copy.copy()
        print self.stream_copy is self.stream
        noise = np.random.random(len(self.stream[0].data))
        noise = (noise * 2.0) - 1.
        noise *= self.ui.snr_value.value() * self.sigmax

        if band_limited:
            noise_tr = obspy.Trace()
            noise_tr.stats.sampling_rate = self.stream[0].stats.sampling_rate
            noise_tr.data = noise
            noise_tr.filter('lowpass', freq=1. / self.ui.min_period.value())
            self.stream[0].data = self.stream_copy[0].data + noise_tr.data

        else:
            self.stream[0].data += self.stream_copy[0].data + noise
        #self.stream[0] = self.stream_copy[0].data + noise
        self.update()

    def update(self, force=False):
        #plot_widget = self.ui.seismogram
        #plot_widget.clear()
        #time = np.linspace(self.stream[0].stats.sac['o'],
        #                   self.stream[0].stats.npts*self.stream[0].stats.delta,
        #                   self.stream[0].stats.npts)
        #plot_widget.plot(time,self.stream[0].data,pen='b')
        self.sigmax = np.max(np.abs(self.stream_copy[0].data))
        print 'min and max of stream_copy', np.min(
            self.stream_copy[0].data), np.max(self.stream_copy[0].data)
        self.plot_seismogram()
        #self.plot_gabor()

    def plot_seismogram(self):

        time = self.get_time_axis

        self.mpl_seis_figure = self.ui.seismogram.fig
        if hasattr(self, 'mpl_seis_ax'):
            self.mpl_seis_ax.clear()
        self.mpl_seis_ax = self.mpl_seis_figure.add_axes(
            [0.1, 0.15, 0.90, 0.70])
        self.mpl_seis_ax.plot(time, self.stream[0].data, c='b')
        self.mpl_seis_ax.set_xlabel('time (s)')

        self.mpl_seis_ax.axvline(float(self.ui.window_start.value()), c='k')
        self.mpl_seis_ax.axvline(float(self.ui.window_end.value()), c='k')
        self.mpl_seis_ax.set_xlim(
            [self.ui.window_start.value(),
             self.ui.window_end.value()])
        self.mpl_seis_figure.canvas.draw()

    def plot_map(self):
        plt.cla()
        self.mpl_map_figure = self.ui.map.fig
        self.mpl_map_ax = self.mpl_map_figure.add_axes(
            [0.01, 0.01, 0.99, 0.99])
        self.map = Basemap(projection='moll',
                           lon_0=0,
                           resolution='c',
                           ax=self.mpl_map_ax)
        #self.map.drawcoastlines()
        DIR = os.path.dirname(os.path.abspath(__file__))
        self.map.warpimage(image=DIR + '/../data/images/europa_comp_800.jpg',
                           zorder=0)
        x, y = self.map(self.ui.evlo.value(), self.ui.evla.value())
        x2, y2 = self.map(self.ui.stlo.value(), self.ui.stla.value())
        self.map.scatter(x, y, marker='*', color='yellow')
        self.map.scatter(x2, y2, marker='^', color='red')
        self.mpl_map_figure.canvas.draw()
        self.mpl_map_figure.canvas.flush_events()

    def plot_gabor(self):

        if hasattr(self, 'mpl_gabor_ax'):
            self.mpl_gabor_ax.clear()

        self.mpl_gabor_figure = self.ui.gabormatrix.fig
        self.mpl_gabor_ax = self.mpl_gabor_figure.add_axes(
            [0.1, 0.1, 0.8, 0.6])

        if self.stream is not None:
            self.km_per_deg = (2. * np.pi * self.planet_radius / 360.0)
            self.dist_km = self.stream[0].stats.sac['gcarc'] * self.km_per_deg
            vel_min = self.dist_km / float(self.ui.window_start.value())
            vel_max = self.dist_km / float(self.ui.window_end.value())

        #extent = [20.,200.,vel_max,vel_min]
        #self.mpl_gabor_ax.imshow(self.gabor_matrix.T,
        #    aspect='auto',extent=extent,cmap='jet')
        #self.mpl_gabor_ax.set_xlabel('period (s)')
        #self.mpl_gabor_ax.set_ylabel('velocity (km/s)')

        self.gabor_matrix /= np.max(self.gabor_matrix)
        self.mpl_gabor_ax.contourf(self.periods,
                                   self.dist_km / self.time_window,
                                   self.gabor_matrix,
                                   cmap='jet',
                                   levels=np.linspace(0, 1, 50))

        if self.vel_pick is not None:
            self.mpl_gabor_ax.scatter(self.period_pick,
                                      self.vel_pick,
                                      c='k',
                                      marker='+')

        veloc = self.dist_km / self.time_window
        #ftest = np.loadtxt('/home/romaguir/Tools/europa_seismo/data/prem_grpvel_minos.txt')
        #self.mpl_gabor_ax.plot(ftest[:,0],ftest[:,1],c='k',alpha=0.75)
        self.mpl_gabor_ax.set_xlim(
            [self.ui.min_period.value(),
             self.ui.max_period.value()])
        #self.mpl_gabor_ax.set_ylim([np.min(veloc),min(5,np.max(veloc))])
        self.mpl_gabor_ax.set_xlabel('period (s)')
        self.mpl_gabor_ax.set_ylabel('velocity (km/s)')
        self.mpl_gabor_figure.canvas.draw()

    def on_Save_dispersion_curve_triggered(self, *args):
        #np.savetxt('dispersion_curve.dat',np.c_[self.period_pick,self.vel_pick],fmt='%5f')
        filename = QtGui.QFileDialog.getSaveFileName(self, 'Save File')
        fout = open(filename, 'w')
        for i in range(0, len(self.period_pick)):
            fout.write('{} {}\n'.format(1. / self.period_pick[i],
                                        self.vel_pick[i]))
        fout.close()

    def on_Save_report_triggered(self, *args):
        report_dir = 'report_' + self.folder.split('/')[-1] + '_deg' + str(
            self.ui.stlo.value())
        if not os.path.isdir(report_dir):
            os.mkdir(report_dir)

        #open files
        metadata = open(report_dir + '/metadata.txt', 'w')
        waveform = open(report_dir + '/waveform.dat', 'w')
        mft_data_freq = open(report_dir + '/mft_data_freq.dat', 'w')
        mft_data_per = open(report_dir + '/mft_data_per.dat', 'w')
        disp_crv = open(report_dir + '/disp_crv.dat', 'w')

        #write metadata
        metadata.write('----------------------------------------\n')
        metadata.write('basic info\n')
        metadata.write('----------------------------------------\n')
        metadata.write('database:' + self.folder + '\n')
        metadata.write('window start:' + str(self.ui.window_start.value()) +
                       '\n')
        metadata.write('window end:' + str(self.ui.window_end.value()) + '\n')
        metadata.write('stlo:' + str(self.ui.stlo.value()) + '\n')
        metadata.write('stla:' + str(self.ui.stla.value()) + '\n')
        metadata.write('evlo:' + str(self.ui.evlo.value()) + '\n')
        metadata.write('evla:' + str(self.ui.evla.value()) + '\n')
        metadata.write('mft_type:' + self.ui.mft_type.currentText() + '\n')
        metadata.write('alpha:' + str(self.ui.alpha.value()) + '\n')
        metadata.write('gamma:' + str(self.ui.gamma.value()) + '\n')
        metadata.write('corners:' + str(self.ui.corners.value()) + '\n')
        metadata.write('min period:' + str(self.ui.min_period.value()) + '\n')
        metadata.write('max period:' + str(self.ui.max_period.value()) +
                       '\n\n')

        metadata.write('----------------------------------------\n')
        metadata.write('moment tensor\n')
        metadata.write('----------------------------------------\n')
        metadata.write('m_rr:' + str(self.ui.m_rr.value()) + '\n')
        metadata.write('m_tt:' + str(self.ui.m_tt.value()) + '\n')
        metadata.write('m_pp:' + str(self.ui.m_pp.value()) + '\n')
        metadata.write('m_rt:' + str(self.ui.m_rt.value()) + '\n')
        metadata.write('m_rp:' + str(self.ui.m_rp.value()) + '\n')
        metadata.write('m_tp:' + str(self.ui.m_tp.value()) + '\n')

        #save gabor matrix
        self.gabor_matrix /= np.max(self.gabor_matrix)
        pers, vels = np.meshgrid(self.periods, self.dist_km / self.time_window)
        freqs = 1. / pers

        for i in range(0, len(freqs.flatten())):
            mft_data_freq.write('{} {} {}\n'.format(
                freqs.flatten()[i],
                vels.flatten()[i],
                self.gabor_matrix.flatten()[i]))
            mft_data_per.write('{} {} {}\n'.format(
                pers.flatten()[i],
                vels.flatten()[i],
                self.gabor_matrix.flatten()[i]))

        #save waveform
        for i in range(0, len(self.stream_slice.data)):
            waveform.write('{} {}\n'.format(self.time_window[i],
                                            self.stream_slice.data[i]))

        #save dispersion curve
        for i in range(0, len(self.period_pick)):
            disp_crv.write('{} {}\n'.format(1. / self.period_pick[i],
                                            self.vel_pick[i]))

        #close files
        metadata.close()
        waveform.close()
        mft_data_freq.close()
        mft_data_per.close()
        disp_crv.close()

    def on_Open_noise_file_triggered(self, *args):
        cwd = os.getcwd()
        noisefile = QtGui.QFileDialog.getOpenFileName(
            self, "choose a noise file (must have .dat extension)", cwd,
            'Data Files (*.dat)')
        if noisefile != '':
            self.noisefile = noisefile

        f = open(self.noisefile, 'r')
        f.close()
        if not self.noisefile:
            return

    def on_Plot_noise_power_spectrum_triggered(self, *args):
        plt.style.use('default')
        f_ = open(self.noisefile, 'r')
        lines = f_.readlines()
        per = []
        power = []
        for line in lines:
            vals = line.strip().split()
            per.append(np.float(vals[0]))
            power.append(np.float(vals[1]))

        fig, ax = plt.subplots(1, figsize=(6, 6))
        ax.semilogx(per, power)
        ax.set_xlabel('period (s)')
        ax.set_ylabel('power (dB)')
        ax.get_xaxis().set_visible(True)
        plt.show()

    def editor(self):
        self.textEdit = QtGui.TextEdit()
        self.setCentralWidget(self.textEdit)
Example #23
0
class PlanetarySurveyor(object):
    """
    The PlanetarySurveyor creates a Matplotlib "widget" letting the user
    navigate map data loaded from an image file.
    """

    def __init__(self, filename="templates/nowwhat.png"):
        """
        Initialized with filename of image file containing the equirectangular
        map data.
        """

        self.filename = filename
        self.load_image()

        # Setup display:
        self.fig = plt.figure(1)
        self.ax = plt.subplot(111)
        plt.clf()
        plt.subplots_adjust(left=0.1, bottom=0.20)

        self.meridian = -90
        self.parallel = 22.5
        self.projection = "orthographic"
        self.parallels = 16
        self.meridians = 16

        self.setup_display()

        # Setup mouse interaction:
        self.click = self.hemisphere_axes.figure.canvas.mpl_connect(
                        'button_press_event', self.mouseclick)

        self.cursor = Cursor(self.hemisphere_axes, useblit=True, color='red',
                             linewidth=1)

        # Setup axes:
        self.axes_step = plt.axes([0.13, 0.15, 0.60, 0.03])
        self.axes_meridians = plt.axes([0.13, 0.10, 0.60, 0.03])
        self.axes_parallels = plt.axes([0.13, 0.05, 0.60, 0.03])

        self.update_axes = plt.axes([0.79, 0.095, 0.08, 0.04])
        self.reset_axes = plt.axes([0.79, 0.05, 0.08, 0.04])

        self.radio_axes = plt.axes([0.88, 0.05, 0.11, 0.15])

        # Setup sliders:
        self.step = 22.5
        self.slider_step = Slider(self.axes_step, 'Step', 0, 90,
                                  valinit=self.step, valfmt='%2.1f')
        self.slider_meridians = Slider(self.axes_meridians, 'Meridians', 0,
                                       64, valinit=self.parallels,
                                       valfmt='%2d')
        self.slider_parallels = Slider(self.axes_parallels, 'Parallels', 0,
                                       64, valinit=self.parallels,
                                       valfmt='%2d')

        self.slider_step.on_changed(self.update)
        self.slider_meridians.on_changed(self.update)
        self.slider_parallels.on_changed(self.update)

        # Setup button(s):
        self.update_button = Button(self.update_axes, 'Update')
        self.update_button.on_clicked(self.update_display)

        self.button = Button(self.reset_axes, 'Reset')
        self.button.on_clicked(self.reset)

        # Setup radio buttons:
        self.radio = RadioButtons(self.radio_axes, ('ortho', 'eq.dist',
                                                    'rect'), active=0)
        self.radio.on_clicked(self.set_mode)
        self.projections = {"ortho": ("orthographic", "ortho"),
                            "eq.dist": ("equidistant", "aeqd"),
                            "rect": ("rectangular", "cyl")}

        # Almost done:
        self.update()
        plt.show()

    def load_image(self):
        """
        Checks if the image file specified exists and is an image file. If this
        fails, the default map is loaded.
        """

        try:
            map_image = plt.imread(self.filename)
        except IOError as e:
            print "Could not load file {0} ({1})".format(
                  self.filename, e.strerror)
            print "Using default image..."
            self.filename = "templates/nowwhat.png"

    def setup_display(self):
        """
        Setup parameters and map display.
        """

        self.hemisphere_axes = plt.gca()
        self.R = 10000 * 360.0 / (2 * np.pi)
        self.width = 180 * 10000
        self.height = 180 * 10000

        if self.projection == 'orthographic':
            self.hemisphere = Basemap(projection="ortho", lon_0=self.meridian,
                              lat_0=self.parallel, resolution='c',
                              area_thresh=100000, ax=self.hemisphere_axes)
        elif self.projection == 'equidistant':
            self.hemisphere = Basemap(projection="aeqd", lon_0=self.meridian,
                              lat_0=self.parallel, resolution='c',
                              area_thresh=100000, rsphere=self.R,
                              ax=self.hemisphere_axes, width=self.width,
                              height=self.height)
        elif self.projection == 'rectangular':
            self.hemisphere = Basemap(projection="cyl", lon_0=0, lat_0=0,
                              resolution='c', area_thresh=100000,
                              ax=self.hemisphere_axes)

        self.hemisphere.warpimage(self.filename)
        self.hemisphere.drawmapboundary()
        self.draw_graticules()

    def update_display(self):
        """
        Update map display.
        """

        if self.projection == 'orthographic':
            self.hemisphere = Basemap(projection="ortho", lon_0=self.meridian,
                              lat_0=self.parallel, resolution='c',
                              area_thresh=100000, ax=self.hemisphere_axes)
        elif self.projection == 'equidistant':
            self.hemisphere = Basemap(projection="aeqd", lon_0=self.meridian,
                              lat_0=self.parallel, resolution='c',
                              area_thresh=100000, rsphere=self.R,
                              ax=self.hemisphere_axes, width=self.width,
                              height=self.height)
        elif self.projection == 'rectangular':
            self.hemisphere = Basemap(projection="cyl", lon_0=0, lat_0=0,
                              resolution='c', area_thresh=100000,
                              ax=self.hemisphere_axes)

        self.hemisphere_axes.cla()
        self.hemisphere.warpimage(self.filename)
        self.hemisphere.drawmapboundary()
        self.draw_graticules()

        self.update()

    def update(self, val=0):
        """
        Update internal parameters from sliders, update coordiantes and draw.
        """

        if self.step != self.slider_step.val:
            self.step = np.round(self.slider_step.val / 0.5) * 0.5
            self.slider_step.set_val(self.step)

        if (self.meridians != self.slider_meridians.val or
                self.parallels != self.slider_parallels.val):

            self.meridians = np.round(self.slider_meridians.val
                                      ).astype(np.int)
            self.parallels = np.round(self.slider_parallels.val
                                      ).astype(np.int)

        self.fix_coordinates()

        plt.draw()

    def set_mode(self, val="ortho"):
        """
        Set projection mode.
        """

        self.projection = self.projections[val][0]

        self.update_display()

    def reset(self, event):
        """
        Reset widget
        """

        self.slider_step.reset()
        self.slider_meridians.reset()
        self.slider_parallels.reset()
        self.meridian = 90
        self.parallel = 0
        self.update()

    def mouseclick(self, event):
        """
        Handle mouse navigation of map display for the different projections.
        """

        if event.inaxes == self.hemisphere_axes:
            if event.button == 1:
                if self.projection == "rectangular":
                    self.parallel = np.round(event.ydata / 0.5) * 0.5
                    self.meridian = np.round(event.xdata / 0.5) * 0.5
                else:
                    xlim = self.hemisphere_axes.get_xlim()
                    x = np.round(3 * (event.xdata -
                        0.5 * (xlim[1] - xlim[0])) / (xlim[1] - xlim[0]))

                    ylim = self.hemisphere_axes.get_ylim()
                    y = np.round(3 * (event.ydata -
                        0.5 * (ylim[1] - ylim[0])) / (ylim[1] - ylim[0]))

                    self.meridian += self.step * x
                    self.parallel += self.step * y

                    self.update_display()

                self.update()

    def fix_coordinates(self):
        """
        Fix coordinates so they comply to standard representation for maps.
        """

        if self.parallel > 90.0:
            self.parallel = 180.0 - self.parallel
        elif self.parallel < -90.0:
            self.parallel = -180.0 - self.parallel

        if self.meridian > 180.0:
            self.meridian = 360.0 - self.meridian
        elif self.meridian < -180.0:
            self.meridian = -360.0 - self.meridian

        self.hemisphere_axes.set_title("{0}: {1}".format(self.projection,
                                                  self.get_coordinates()))

    def get_coordinates(self):
        """
        Return string representation of coordinates in N-S/E-W standard.
        """

        parallel = np.abs(self.parallel)
        meridian = np.abs(self.meridian)

        if self.parallel >= 0:
            NS = "N"
        else:
            NS = "S"

        if self.meridian >= 0:
            EW = "E"
        else:
            EW = "W"

        return "{0} {1}, {2} {3}".format(parallel, NS, meridian, EW)

    def get_graticule(self):
        """
        Return resolution of the current graticule (distances between parallel
        and meridian lines).
        """

        try:
            dLat = 180.0 / self.parallels
        except ZeroDivisionError:
            dLat = None

        try:
            dLon = 360.0 / self.meridians
        except ZeroDivisionError:
            dLon = 0

        return dLat, dLon

    def draw_graticules(self):
        """
        Draw parallel and meridian lines.
        """

        parallel_step = 180.0 / self.parallels
        meridian_step = 360.0 / self.meridians

        if self.parallels > 0:
            min_parallel = -90
            max_parallel = 90 - parallel_step
            self.hemisphere.drawparallels(
                            np.arange(min_parallel, max_parallel + 1,
                            parallel_step), latmax=90 - parallel_step)

        if self.meridians > 0:
            min_meridian = -180
            max_meridian = 180 - meridian_step
            self.hemisphere.drawmeridians(
                            np.arange(min_meridian, max_meridian + 1,
                            meridian_step), latmax=90 - parallel_step)
logging.info("Let's start")

plt.style.use('dark_background')

figdir = "../images/rotatingEarth/V2/"
if not os.path.exists(figdir):
    os.makedirs(figdir)
    logger.info("Create figure directory {}".format(figdir))

lons = np.arange(0, 360., 1.)
lat0 = 10.
nlons = len(lons)
for i, lon0 in enumerate(lons):
    m = Basemap(projection='ortho', lon_0=lon0, lat_0=lat0, resolution='c')
    logger.info("Working on figure {} / {}".format(i, nlons))
    ii = str(i).zfill(4)

    fig = plt.figure(1, figsize=(10, 10))
    #ax = plt.subplot(111)
    #ax.set_facecolor(".2")
    #m.fillcontinents()
    #m.drawcoastlines(linewidth=.5)
    m.warpimage("./world.topo.bathy.200403.3x5400x2700.jpg", zorder=2)
    plt.savefig(os.path.join(figdir, "earth_visible_{}.jpg".format(ii)),
                dpi=300,
                bbox_inches="tight")
    fig.clf()
    plt.close(fig)

    plt.close("all")
Example #25
0
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import Image

map = Basemap(projection='ortho', lat_0=0, lon_0=0)

tmpdir = '/tmp'

size = [600, 300]
im = Image.open("../sample_files/by.png")

im2 = im.resize(size, Image.ANTIALIAS)
im2.save(tmpdir + '/resized.png', "PNG")

map.warpimage(tmpdir + '/resized.png')

map.drawcoastlines()

plt.show()
Example #26
0
def bluemarble_daynight(date, scale):
    mpl.rcParams['savefig.pad_inches'] = 0
    # Define Bluemarble and Nightshade objects
    #fig, axes = plt.subplots(1, figsize=(12,8), frameon=False)
    fig = plt.figure(figsize=(12, 8))
    axes = plt.axes([0, 0, 1, 1], frameon=False)
    axes.get_xaxis().set_visible(False)
    axes.get_yaxis().set_visible(False)
    plt.autoscale(tight=True)
    m = Basemap(projection='cyl', resolution=None, area_thresh=None, ax=axes)
    bm = m.bluemarble(scale=scale)
    ns = m.nightshade(date, alpha=0.5)

    bm_rgb = bm.get_array()
    bm_ext = bm.get_extent()

    axes.cla()

    # Get the x and y index spacing
    x = np.linspace(bm_ext[0], bm_ext[1], bm_rgb.shape[1])
    y = np.linspace(bm_ext[2], bm_ext[3], bm_rgb.shape[0])

    # Define coordinates of the Bluemarble image
    x3d, y3d = np.meshgrid(x, y)
    pts = np.hstack((x3d.flatten()[:, np.newaxis], y3d.flatten()[:,
                                                                 np.newaxis]))

    # Find which coordinates fall in Nightshade
    # The following could be tidied up as there should only ever one polygon. Although
    # the length of ns.collections is 3? I'm sure there's a better way to do this.
    paths, polygons = [], []
    for i, polygons in enumerate(ns.collections):
        for j, paths in enumerate(polygons.get_paths()):
            #print j, i
            msk = paths.contains_points(pts)

    # Redefine mask
    msk = np.reshape(msk, bm_rgb[:, :, 0].shape)
    msk_s = np.zeros(msk.shape)
    msk_s[~msk] = 1.

    # Smooth interface between Night and Day
    for s in range(
            bm_rgb.shape[1] // 50
    ):  # Make smoothing between day and night a function of Bluemarble resolution
        msk_s = 0.25 * (  np.vstack( (msk_s[-1,:            ], msk_s[:-1, :            ]) )  \
                        + np.vstack( (msk_s[1:,:            ], msk_s[0  , :            ]) )  \
                        + np.hstack( (msk_s[: ,0, np.newaxis], msk_s[:  , :-1          ]) )  \
                        + np.hstack( (msk_s[: ,1:           ], msk_s[:  , -1,np.newaxis]) ) )

    # Define new RGBA array
    bm_rgba = np.dstack((bm_rgb, msk_s))

    # Plot up Bluemarble Nightshade
    m = Basemap(projection='cyl', resolution=None, area_thresh=None, ax=axes)
    bm_n = m.warpimage('/home/pi/Mimic/Pi/imgs/orbit/earth_lights_lrg.jpg',
                       scale=scale)
    bm_d = m.imshow(bm_rgba)
    plt.savefig('/home/pi/Mimic/Pi/imgs/orbit/map.jpg',
                bbox_inches='tight',
                pad_inches=0)
Example #27
0
# basemap.colorbar(img)
# </pre>
#     

# <markdowncell>

# # Basemap
# Can be used for nice map backgrounds

# <codecell>

from mpl_toolkits.basemap import Basemap
b = Basemap()
fig, (ax1, ax2) = plt.subplots(1,2)

b.warpimage(ax = ax1, scale = 0.1); 
im = b.etopo(ax = ax2, scale = 0.1); 

# <markdowncell>

# Define a helper download function
# ======

# <codecell>

import os
def download_link(url, local_path):
    if os.path.isfile(local_path):
        return
    
    import urllib2
Example #28
0
def createCountryMap(input,
                     baseColor=None,
                     baseTexture=None,
                     colormap="Greens",
                     countryKey="",
                     dataKey="",
                     filename="",
                     isWorldBank=False,
                     max_year=3000,
                     min_year=0,
                     printMissingCountries=False,
                     range_min=None,
                     range_max=None,
                     transparent=False,
                     yearKey=""):
    """Function to take a CSV file containing country-based data and build a Science on a Sphere texture from it.
    """
    if isinstance(input, pd.DataFrame):
        df = input
    elif isinstance(input, list):
        df = pd.DataFrame()
        df["Country"] = input
        df["Data"] = 1
    elif isinstance(input, str):  # We probably got a CSV filename
        df = getOptimizedDataset(input,
                                 countryKey=countryKey,
                                 dataKey=dataKey,
                                 isWorldBank=isWorldBank,
                                 max_year=max_year,
                                 min_year=min_year,
                                 yearKey=yearKey)
    else:
        print(
            "createCountryMap: Error: You must pass a CSV filename or a pandas DataFrame, or a list of countries"
        )
        return

    # Matplotlib setup
    plt.rcParams["figure.figsize"] = (16, 8)
    plt.clf()
    fig = plt.figure()
    ax = fig.add_subplot(111)

    if baseTexture is not None:
        m = Basemap(projection='cyl',llcrnrlat=-90,urcrnrlat=90,\
                    llcrnrlon=-180,urcrnrlon=180,resolution='l')
        m.warpimage(baseTexture)
    elif baseColor is not None:
        fig.patch.set_facecolor(baseColor)

    colormap = cm.get_cmap(colormap)
    if range_min is not None:
        vmin = range_min
    else:
        vmin = np.min(df["Data"])
    if range_max is not None:
        vmax = range_max
    else:
        vmax = np.max(df["Data"])
    norm = mpl.colors.Normalize(vmin=vmin, vmax=vmax)

    # Shapefile setup
    sf = shapefile.Reader("./world_shapefile/world.shp")
    records = sf.records()
    shapes = sf.shapes()
    num_shapes = len(shapes)

    country_names = []
    for i in range(num_shapes):
        country_names.append(records[i][1])
    country_names = np.array(country_names)
    if isWorldBank:
        country_names = countryNameToWorldBank(country_names)
    else:
        country_names = countryNameNormalize(country_names)
        df["Country"] = countryNameNormalize(df["Country"].values)
    if printMissingCountries:
        print("Countries in input data that are not in the map data:")
        print((df[~df["Country"].isin(country_names)])["Country"].values)
        print("Countries in the map data that are not in the input data:")

    # Iterate the country shapes and color them based on the data
    for i in range(num_shapes):
        patches = []
        points = np.array(shapes[i].points)
        parts = shapes[i].parts
        par = list(parts) + [points.shape[0]]

        for j in range(len(parts)):
            patches.append(mpl.patches.Polygon(points[par[j]:par[j + 1]]))

        country = country_names[i]

        try:
            val = float((df[df['Country'] == country])["Data"].values[0])
            base_color = colormap(norm(val))
            if baseTexture is not None:
                color = (base_color[0], base_color[1], base_color[2], 0.5
                         )  # Make patrially transparent
            else:
                color = base_color
            ax.add_collection(
                PatchCollection(patches,
                                facecolor=color,
                                edgecolor='k',
                                linewidths=.1))
        except:
            if printMissingCountries:
                print(country)
            if baseTexture is None:
                color = "gray"
            else:
                color = (0, 0, 0, 0.5)
            ax.add_collection(
                PatchCollection(patches,
                                facecolor=color,
                                edgecolor='k',
                                linewidths=.1))

    fig.subplots_adjust(left=0, right=1, top=1, bottom=0)
    ax.axis("off")
    ax.set_xlim(-180, +180)
    ax.set_ylim(-90, 90)

    if filename != "":
        plt.savefig(filename,
                    dpi=256,
                    facecolor=baseColor,
                    transparent=transparent)
Example #29
0
def mapSubject(dataset,subject,box='tight',level='auto',
               longest=20,call='default',highlight=False,
               heatmap=True, mark = 'r', cmap='YlOrRd',
               show = True, offset = 0, subtitle = '', geobox = 'null',
	       important = 'null',background = 'none'):

    if call == 'animate':
        plt.clf()
    else:
        fig = plt.figure(figsize=(9,9))
    
    if geobox == 'null' or (type(box) is str and type(geobox) is str):
    	box = fixBox(dataset,box)
    else:
        box = geobox
    	
    lats, lons, times = getData(dataset,offset)
    
    mapped = Basemap(projection='mill', 
                     llcrnrlon=box['lon1'],
                     llcrnrlat=box['lat1'],
                     urcrnrlon=box['lon2'],
                     urcrnrlat=box['lat2'])

    mapOpacity = 0.75
    if background == 'etopo':
	mapped.etopo(zorder=0, alpha=mapOpacity)
    elif background == 'shaded relief':
	mapped.shadedrelief(zorder=0, alpha=mapOpacity)
    elif background == 'blue marble':
        mapped.bluemarble(zorder=0, alpha=mapOpacity)
    elif '/' in background or '.' in background:
        try:
            mapped.warpimage(image='maps/'+background, scale=None, zorder=0, alpha=mapOpacity)
        except:
            mapped.warpimage(image=background, scale=None, zorder=0, alpha=mapOpacity)
    else:
	background = 'null'
	
    smallest = min(box['lat2']-box['lat1'],box['lon2']-box['lon1'])

    mapped.drawcoastlines(zorder=3)
    
    if smallest < 5:
        mapped.drawcountries(zorder=3,linewidth = 3)
        mapped.drawstates(zorder=3, linewidth = 2)
        mapped.drawcounties(zorder=3,linewidth = 1)
    else:
        mapped.drawcountries(zorder=3,linewidth = 2)
        mapped.drawstates(zorder=3, linewidth = 1)
    
    if heatmap:
        # ######################################################################
        # http://stackoverflow.com/questions/11507575/basemap-and-density-plots)
        density, lon_bins, lat_bins = getDensity(box,lats,lons,longest)
        lon_bins_2d, lat_bins_2d = np.meshgrid(lon_bins, lat_bins)
        xs, ys = mapped(lon_bins_2d, lat_bins_2d) # will be plotted using pcolormesh
        # ######################################################################
        
        if level == 'auto':
            level = np.amax(density)

	density = fixDensity(density,xs,ys)
	
  	if background == 'null':
        	plt.pcolormesh(xs, ys, density, cmap = cmap,zorder=2, alpha = 1, vmin =1)
	else:
		extent = (xs[0][0],xs[0][-1],ys[0][0],ys[-1][0]) 
		colorized = mapColors(density,level,cmap)
		colorized = mapTransparency(density,colorized,level)
		plt.imshow(colorized, extent=extent,cmap=cmap,origin='lower',interpolation='nearest',zorder=2)


    smallest = min(box['lat2']-box['lat1'],box['lon2']-box['lon1'])
    
    if smallest < 1.0:
        gridIncrement = 0.1
    if smallest < 2.5:
	gridIncrement = 0.5
    elif smallest < 5:
	gridIncrement = 1.0
    elif smallest < 10:
	gridIncrement = 2.5
    else:
	gridIncrement = 5.0

    parallels = np.arange(-90.,90.,gridIncrement)
    mapped.drawparallels(parallels,labels=[1,0,0,0],fontsize=10, alpha = .75)
    meridians = np.arange(-180.,180.,gridIncrement)
    mapped.drawmeridians(meridians,labels=[0,0,0,1],fontsize=10, alpha = .75)

    if important != 'null':
	xI,yI = mapped(important[0],important[1])
	xM,yM = mapped(np.mean(lons),np.mean(lats))
	mapped.plot(xI,yI,'o',markersize=15, zorder=6, markerfacecolor = "white", markeredgecolor=mark, alpha = 1.0)
	mapped.plot(xM,yM,'x',markersize=15, zorder=6, markerfacecolor = "white", markeredgecolor=mark, alpha = 1.0)

    x, y = mapped(lons, lats) # compute map proj coordinates.
    mapped.plot(x, y, 'o', markersize=4,zorder=6, markerfacecolor=mark,markeredgecolor="none", alpha=0.30)
    if highlight != False:
        mapped.plot(x, y, 'o', markersize=4,zorder=6, markerfacecolor=highlight,markeredgecolor="none", alpha=0.03)

    
    title = '%s search for "%s",\n%s Related Tweets Found from\n%s to %s' % (dataset['name'],
                                                                            subject,
                                                                            len(dataset['data']),
                                                                            times[0],
                                                                            times[-1])
    plt.title(title)
    if subtitle != '':
   	 plt.xlabel(subtitle)

    if heatmap:
        divider = make_axes_locatable(plt.gca())
        cax = divider.append_axes("right", "5%", pad="3%")
        cbar = plt.colorbar(orientation='vertical',cax=cax)
        if level != 'full':
            plt.clim([0,level])
        cbar.set_label('Number of Tweets')
    
    if call != 'animate' and show:
        plt.show()
    return plt
Example #30
0
#plt.imshow(generatedarray) ################################################LOOK AT THIS HERE
#plt.axis('off')
#plt.savefig("planettemp.png", bbox_inches='tight')
#plt.show()

print "Done"

#############################################################################

bmap = Basemap(projection='ortho',
               lat_0=180,
               lon_0=0,
               resolution='l',
               area_thresh=1000.)
# plot surface
bmap.warpimage(image='planet1copy.jpeg')
# draw the edge of the map projection region (the projection limb)
bmap.drawmapboundary()
# draw lat/lon grid lines every 30 degrees.
bmap.drawmeridians(np.arange(0, 360, 30))
bmap.drawparallels(np.arange(-90, 90, 30))
plt.show()

#Need to fix this init
##############################################################################
#ALL AGAIN DIFFERENT MAGNITUDE

x = np.linspace(5, 30, num=1000)

c0 = 9.73946
c1 = -4.39968e-01
Example #31
0
    "back_face.png", "left_face.png"
]

#creates the 6 squares
for i in range(0, 6):
    m = Basemap(projection="aeqd",
                lat_0=coords[i][1],
                lon_0=coords[i][0],
                width=width,
                height=height)
    if (using_image != 'y'):
        m.drawmapboundary(fill_color="aqua")
        m.drawcoastlines(linewidth=0.5)
        m.fillcontinents(color="coral", lake_color="aqua")
    else:
        m.warpimage("quantized_img.png")

    m.drawparallels(np.arange(-90, 90, line_angle))
    m.drawmeridians(np.arange(-180, 180, line_angle))

    plt.axis('off')
    plt.savefig(file_names[i], bbox_inches="tight", pad_inches=0)
    plt.clf()

img1 = Image.open('north_pole.png')
img2 = Image.open('south_pole.png').rotate(180)
img3 = Image.open('front_face.png')
img4 = Image.open('right_face.png').rotate(90)
img5 = Image.open('back_face.png').rotate(180)
img6 = Image.open('left_face.png').rotate(270)
Example #32
0
    # Load coordinates
    SSS = nc.variables['_l3m_data'][:]
    SSS = np.flipud(SSS)
    
llon,llat=np.meshgrid(lon,lat)

if doplot==1:
    
    # create figure
    fig = plt.figure()
    ax = plt.subplot(111)

    # set up orthographic map projection with
    map = Basemap(projection='ortho',lat_0=5.,lon_0=-20,resolution='l')

    map.warpimage(image=visibledir+visiblefile,alpha=0.9,zorder=1)
    lonc,latc=map(llon,llat)
    lonc[lonc==1e+30]=np.nan
    latc[latc==1e+30]=np.nan

    #map.contourf(lonc,latc,SLA,levels2plot,cmap=cmap,norm=norm,zorder=2)
    map.pcolormesh(lonc,latc,SSS,cmap=cmap,norm=norm,zorder=2)

    
    plt.savefig(figdir+figname, dpi=300, facecolor='w', edgecolor='w',transparent=True, bbox_inches='tight', pad_inches=0.)
                
    #plt.show()
    plt.close

    fig=plt.figure()
    ax = fig.add_axes([0.1,0.2,0.7,0.5])
Example #33
0
import mpl_toolkits
mpl_toolkits.__path__.append('/usr/lib/python2.7/dist-packages/mpl_toolkits/')
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import numpy as np
# set up orthographic map projection with
# perspective of satellite looking down at 50N, 100W.
# use low resolution coastlines.
# don't plot features that are smaller than 1000 square km.
bmap = Basemap(projection='ortho',
               lat_0=50,
               lon_0=-100,
               resolution='l',
               area_thresh=1000.)
# plot surface
bmap.warpimage(image='/home/lsdo/Cubesat/lsdo_cubesat/viz/blue_marble.jpg')
# draw the edge of the map projection region (the projection limb)
bmap.drawmapboundary()
# draw lat/lon grid lines every 30 degrees.
bmap.drawmeridians(np.arange(0, 360, 30))
bmap.drawparallels(np.arange(-90, 90, 30))
plt.show()
Example #34
0
edge = gp.sample(y)
edge = np.append(edge, edge)

# Now sample from the conditional distribution
gp = george.GP(kernel2d)
gp.compute(np.array(np.meshgrid(np.array([0,1]),y)).reshape(2, -1).T, yerr = 0)
z = gp.sample_conditional(edge, np.array(np.meshgrid(x,y)).reshape(2, -1).T)
z -= np.min(z)
z /= np.max(z)

# Plot the contour
pl.contourf(x, y, z.reshape(size,size), levels = np.linspace(0, 1, size), cmap = blue_brown)

# Plot the water level
pl.contour(x, y, z.reshape(size,size), levels = [0, water_level], lw = 2, colors = ['w', 'w'])
pl.xlim(0,1)
pl.ylim(0,1)
pl.show()

# Plot on sphere (TODO)
if False and Basemap is not None:
  map = Basemap(projection='ortho', lat_0 = 50, lon_0 = -100,
                resolution = 'l', area_thresh = 1000.)
  # plot surface
  map.warpimage(image='?')
  # draw the edge of the map projection region (the projection limb)
  map.drawmapboundary()
  # draw lat/lon grid lines every 30 degrees.
  map.drawmeridians(np.arange(0, 360, 30))
  map.drawparallels(np.arange(-90, 90, 30))
  pl.show()
                ax=ax1)
    m.drawmapboundary(color='#787878', linewidth=0.4)

if (mproj == 'CE'):
    # define projection
    m = Basemap(projection='cyl',llcrnrlat=-90,urcrnrlat=90,area_thresh=10000,\
    llcrnrlon=30,urcrnrlon=390,resolution='l')

if (mproj == 'RB'):
    m = Basemap(projection='robin', lon_0=-150, resolution='l')

orig = Image.open(infile)
bg = Image.new("RGB", orig.size, (211, 211, 211))
bg.paste(orig, orig)
bg.save("./tmp.png")
im = m.warpimage("./tmp.png")

# fill the continents/lakes
m.fillcontinents(color='#E2E2E2', lake_color='#E2E2E2')

#m.drawcoastlines(color='#787878',linewidth=mlw)
#m.drawcountries(color='#787878',linewidth=mlw)
#m.fillcontinents(color='#E2E2E2')
#m.drawrivers(color='#E2E2E2',linewidth=mlw+1.)

#Add the NOAA logo (except for DIY)
if (imgsize != 'DIY'):
    logo_im = Image.open(logo_image)
    height = logo_im.size[1]
    # We need a float array between 0-1, rather than
    # a uint8 array between 0-255 for the logo
Example #36
0
    def make(self):
        # get what is done in the parent class...
        plot.make(self)
        if self.fmt is None: self.fmt = "%.1e"
        # ... then add specific stuff
        ############################################################################################
        ### PRE-SETTINGS
        ############################################################################################
        # if projection is set, set mapmode to True
        if self.proj is not None:
            self.mapmode = True
        # set dummy xy axis if not defined
        if self.x is None: 
            self.x = np.array(range(self.f.shape[0]))
            self.mapmode = False
            print "!! WARNING !! dummy coordinates on x axis"
        if self.y is None: 
            self.y = np.array(range(self.f.shape[1]))
            self.mapmode = False
            print "!! WARNING !! dummy coordinates on y axis"
        # check sizes
        if self.c is not None:
            if self.c.ndim != 2:
                print "!! WARNING !! Contour is not a 2D field. No contour.",self.c.ndim
                self.c = None
        if self.f.ndim != 2:
            print "!! ERROR !! Field is not two-dimensional" ; exit()
        # transposing if necessary
        shape = self.f.shape
        if shape[0] != shape[1]:
         if len(self.x) == shape[0] and len(self.y) == shape[1]:
            #print "!! WARNING !! Transposing axes"
            self.f = np.transpose(self.f)
            if self.c is not None: 
              self.c = np.transpose(self.c)
        # bound field
        zevmin, zevmax = calculate_bounds(self.f,vmin=self.vmin,vmax=self.vmax,sigma=self.sigma)
        what_I_plot = bounds(self.f,zevmin,zevmax)
        # define contour field levels. define color palette
        ticks = self.div + 1
        zelevels = np.linspace(zevmin,zevmax,ticks)
        palette = get_cmap(name=self.colorbar)
        # do the same thing for possible contourline entries
        if self.c is not None:
            # if masked array, set masked values to filled values (e.g. np.nan) for plotting purposes
            if type(self.c).__name__ in 'MaskedArray':
               self.c[self.c.mask] = self.c.fill_value
            # set levels for contour lines
            if self.clev is None:
              zevminc, zevmaxc = calculate_bounds(self.c)
              what_I_contour = bounds(self.c,zevminc,zevmaxc)
              ticks = self.div + 1
              self.clev = np.linspace(zevminc,zevmaxc,ticks)
            else:
              what_I_contour = self.c
            # formatting
            ft = int(mpl.rcParams['font.size']*0.55)
            if self.cfmt is None: self.cfmt = "%.2g"
              
        ############################################################################################
        ### MAIN PLOT
        ### NB: contour lines are done before contour shades otherwise colorar error
        ############################################################################################
        if not self.mapmode:
            ## A SIMPLE 2D PLOT
            ###################
            # swapping if requested
            if self.swap:  x = self.y ; y = self.x
            else:          x = self.x ; y = self.y
            # coefficients on axis
            if self.xcoeff is not None: x=x*self.xcoeff
            if self.ycoeff is not None: y=y*self.ycoeff
            # make shaded and line contours
            if self.c is not None: 
                objC = mpl.contour(x, y, what_I_contour, \
                            self.clev, colors = self.ccol, linewidths = cline)
                ft = int(mpl.rcParams['font.size']*0.55)
                mpl.clabel(objC, inline=1, fontsize=ft,\
                             inline_spacing=1,fmt=self.cfmt)
            mpl.contourf(x, y, \
                         self.f, \
                         zelevels, cmap=palette)
            #mpl.pcolor(x,y,\
            #             self.f, \
            #             cmap=palette)
            # make log axes and/or invert ordinate
            ax = mpl.gca()
            if self.xdate:
              import matplotlib.dates as mdates
              ax.xaxis.set_major_formatter(mdates.DateFormatter('%m/%d/%y %Hh'))
              #ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%b-%d %H:%M:%S'))
              ax.xaxis.set_major_locator(mdates.DayLocator())
              mpl.setp(mpl.xticks()[1], rotation=30, ha='right') # rotate the x labels
            if self.logx: mpl.semilogx()
            if self.logy: mpl.semilogy()
            if self.invert: ax.set_ylim(ax.get_ylim()[::-1])
            if self.xmin is not None and self.xmax is not None:
              if self.xmin > self.xmax: 
                ax.set_xlim(ax.get_xlim()[::-1])
                self.xmin,self.xmax = self.xmax,self.xmin
            if self.xmin is not None: ax.set_xbound(lower=self.xmin)
            if self.xmax is not None: ax.set_xbound(upper=self.xmax)
            if self.ymin is not None: ax.set_ybound(lower=self.ymin)
            if self.ymax is not None: ax.set_ybound(upper=self.ymax)
            # use back attributes to set a background
            if self.back is not None: ax.set_axis_bgcolor(self.back)
            # set the number of ticks
            if not self.logx:
                ax.xaxis.set_major_locator(MaxNLocator(self.nxticks))
            else:
                pass
                #print "!! WARNING. in logx mode, ticks are set automatically."
            if not self.logy:
                ax.yaxis.set_major_locator(MaxNLocator(self.nyticks))
            else:
                pass
                #print "!! WARNING. in logy mode, ticks are set automatically."
            ## specific modulo labels
            if self.modx is not None:
                ax = labelmodulo(ax,self.modx)
        else:
            ## A 2D MAP USING PROJECTIONS (basemap)
            #######################################
            mpl.xlabel("") ; mpl.ylabel("")
            # additional security in case self.proj is None here
            # ... we set cylindrical projection (the simplest one)
            if self.proj is None: self.proj = "cyl"
            # get lon and lat in 2D version.
            # (but first ensure we do have 2D coordinates)
            if self.x.ndim == 1:  [self.x,self.y] = np.meshgrid(self.x,self.y)
            elif self.x.ndim > 2: print "!! ERROR !! lon and lat arrays must be 1D or 2D"
            # get lat lon intervals and associated settings
            wlon = [np.min(self.x),np.max(self.x)]
            wlat = [np.min(self.y),np.max(self.y)]
            # -- area presets are in set_area.txt
            if self.area is not None:
             if self.area in area.keys():
                wlon, wlat = area[self.area]
            # -- user-defined limits
            if self.xmin is not None: wlon[0] = self.xmin
            if self.xmax is not None: wlon[1] = self.xmax
            if self.ymin is not None: wlat[0] = self.ymin
            if self.ymax is not None: wlat[1] = self.ymax
            # -- settings for meridians and parallels
            steplon = int(abs(wlon[1]-wlon[0])/3.)
            steplat = int(abs(wlat[1]-wlat[0])/3.)
            #mertab = np.r_[wlon[0]:wlon[1]:steplon] ; merlab = [0,0,0,1]
            #partab = np.r_[wlat[0]:wlat[1]:steplat] ; parlab = [1,0,0,0]
            if steplon < 1: steplon = 1
            if steplat < 1: steplat = 1
            if np.abs(wlon[0]) < 180.1 and np.abs(wlon[1]) < 180.1:
                mertab = np.r_[-180.:180.:steplon]
            else:
                mertab = np.r_[0.:360.:steplon]
            merlab = [0,0,0,1]
            partab = np.r_[-90.:90.+steplat:steplat] ; parlab = [1,0,0,0]
            format = '%.1f'
            # -- center of domain and bounding lats
            lon_0 = 0.5*(wlon[0]+wlon[1])
            lat_0 = 0.5*(wlat[0]+wlat[1])
            # some tests, bug fixes, and good-looking settings
            # ... cyl is good for global and regional
            if self.proj == "cyl":
                format = '%.0f'
                partab = np.r_[-90.:90.+15.:15.]
            # ... global projections
            elif self.proj in ["ortho","moll","robin"]:
                wlat[0] = None ; wlat[1] = None ; wlon[0] = None ; wlon[1] = None
                lon_0 = np.ceil(lon_0) # reverse map if lon_0 is slightly below 180 with [0,360]
                steplon = 30. ; steplat = 30.
                if self.proj in ["moll"]: steplon = 60.
                if self.proj in ["robin"]: steplon = 90.
                mertab = np.r_[-360.:360.:steplon]
                #partab = np.r_[-90.:90.+steplat:steplat]
                partab = np.r_[-60.,-30.,0.,30.,60.]
                if self.proj == "ortho": 
                    merlab = [0,0,0,0] ; parlab = [0,0,0,0]
                    # in ortho projection, blon and blat can be used to set map center
                    if self.blon is not None: lon_0 = self.blon
                    if self.blat is not None: lat_0 = self.blat
                elif self.proj == "moll":
                    merlab = [0,0,0,0]
                format = '%.0f'
            # ... regional projections
            elif self.proj in ["lcc","laea","merc"]:
                if self.proj in ["lcc","laea"] and wlat[0] == -wlat[1]: 
                    print "!! ERROR !! with Lambert lat1 must be different than lat2" ; exit()
                if wlat[0] < -80. and wlat[1] > 80.:
                    print "!! ERROR !! set an area (not global)" ; exit()
                format = '%.0f'
            elif self.proj in ["npstere","spstere"]:
                # in polar projections, blat gives the bounding lat
                # if not set, set something reasonable
                if self.blat is None:   self.blat = 60.
                # help the user who forgets self.blat would better be negative in spstere
                # (this actually serves for the default setting just above)
                if self.proj == "spstere" and self.blat > 0: self.blat = -self.blat
                # labels
                mertab = np.r_[-360.:360.:15.]
                partab = np.r_[-90.:90.:5.]
            # ... unsupported projections
            else:
                print "!! ERROR !! unsupported projection. supported: "+\
                      "cyl, npstere, spstere, ortho, moll, robin, lcc, laea, merc"
            # finally define projection
	    try:
	      from mpl_toolkits.basemap import Basemap
	    except:
              print "!! ERROR !! basemap is not available."
	      print "... either install it or use another plot type."
	      exit()
            m = Basemap(projection=self.proj,\
                        lat_0=lat_0,lon_0=lon_0,\
                        boundinglat=self.blat,\
                        llcrnrlat=wlat[0],urcrnrlat=wlat[1],\
                        llcrnrlon=wlon[0],urcrnrlon=wlon[1])
            # in some case need to translated to the left for colorbar + labels
            # TBD: break stuff. a better solution should be found.
            if self.leftcorrect:
                ax = mpl.gca()
                pos = ax.get_position().bounds
                newpos = [0.,pos[1],pos[2],pos[3]]
                ax.set_position(newpos)
            # draw meridians and parallels
            ft = int(mpl.rcParams['font.size']*3./4.)
            zelatmax = 85.
            m.drawmeridians(mertab,labels=merlab,color='grey',linewidth=0.75,fontsize=ft,fmt=format,latmax=zelatmax)
            m.drawparallels(partab,labels=parlab,color='grey',linewidth=0.75,fontsize=ft,fmt=format,latmax=zelatmax)
            # define background (see set_back.txt)
            if self.back is not None:
              if self.back in back.keys():
                 print "**** info: loading a background, please wait.",self.back
                 if self.back not in ["coast","sea"]:
                    try: m.warpimage(back[self.back],scale=0.75)
                    except: print "!! ERROR !! no background image could be loaded. probably not connected to the internet?"
                 elif self.back == "coast":
                    m.drawcoastlines()
                 elif self.back == "sea":
                    m.drawlsmask(land_color='white',ocean_color='aqua')
              else:
                 print "!! ERROR !! requested background not defined. change name or fill in set_back.txt" ; exit()
            # define x and y given the projection
            x, y = m(self.x, self.y)
            # contour field. first line contour then shaded contour.
            if self.c is not None: 
                #zelevelsc = np.arange(900.,1100.,5.)
                objC2 = m.contour(x, y, what_I_contour, \
                            self.clev, colors = self.ccol, linewidths = cline)
                #mpl.clabel(objC2, inline=1, fontsize=10,manual=True,fmt='-%2.0f$^{\circ}$C',colors='r')
                #mpl.clabel(objC2, inline=0, fontsize=8, fmt='%.0f',colors='r', inline_spacing=0) 
            m.contourf(x, y, what_I_plot, zelevels, cmap = palette, alpha = self.trans, antialiased=True)
        ############################################################################################
        ### COLORBAR
        ############################################################################################
        if self.trans > 0. and self.showcb:
            ## draw colorbar. settings are different with projections. or if not mapmode.
            #if not self.mapmode: orientation=zeorientation ; frac = 0.075 ; pad = 0.03 ; lu = 0.5
            if not self.mapmode: orientation=zeorientation ; frac = 0.15 ; pad = 0.04 ; lu = 0.5
            elif self.proj in ['moll']: orientation="horizontal" ; frac = 0.08 ; pad = 0.03 ; lu = 1.0
            elif self.proj in ['robin']: orientation="horizontal" ; frac = 0.07 ; pad = 0.1 ; lu = 1.0
            elif self.proj in ['cyl']: orientation="vertical" ; frac = 0.023 ; pad = 0.03 ; lu = 0.5
            else: orientation = zeorientation ; frac = zefrac ; pad = 0.03 ; lu = 0.5
            if self.cbticks is None:
                self.cbticks = min([ticks/2+1,21])
            zelevpal = np.linspace(zevmin,zevmax,num=self.cbticks)
            zecb = mpl.colorbar(fraction=frac,pad=pad,\
                                format=self.fmt,orientation=orientation,\
                                ticks=zelevpal,\
                                extend='neither',spacing='proportional')
            if zeorientation == "horizontal": zecb.ax.set_xlabel(self.title) ; self.title = ""
            # colorbar title --> units
            if self.units not in ["dimless",""]:
                zecb.ax.set_title("["+self.units+"]",fontsize=3.*mpl.rcParams['font.size']/4.,x=lu,y=1.025)

        ############################################################################################
        ### VECTORS. must be after the colorbar. we could also leave possibility for streamlines.
        ############################################################################################
        ### not expecting NaN in self.vx and self.vy. masked arrays is just enough.
        if self.vx is not None and self.vy is not None: 
                # vectors on map projection or simple 2D mapping
                if self.mapmode: 
                   try:
                     #[vecx,vecy] = m.rotate_vector(self.vx,self.vy,self.x,self.y) # for metwinds only ?
                     vecx,vecy = self.vx,self.vy
                   except:
                     print "!! ERROR !! Problem with field shapes for vector?" 
                     print self.vx.shape,self.vy.shape,self.x.shape,self.y.shape
                     exit()
                else:
                   vecx,vecy = self.vx,self.vy 
                   if x.ndim < 2 and y.ndim < 2: x,y = np.meshgrid(x,y)
                # reference vector is scaled
                if self.wscale is None:
                    self.wscale = ppcompute.mean(np.sqrt(self.vx*self.vx+self.vy*self.vy))
                # make vector field
                if self.mapmode: 
                    q = m.quiver( x[::self.svy,::self.svx],y[::self.svy,::self.svx],\
                                  vecx[::self.svy,::self.svx],vecy[::self.svy,::self.svx],\
                                  angles='xy',color=self.colorvec,pivot='middle',\
                                  scale=self.wscale*reducevec,width=widthvec )
                else:
                    q = mpl.quiver( x[::self.svy,::self.svx],y[::self.svy,::self.svx],\
                                    vecx[::self.svy,::self.svx],vecy[::self.svy,::self.svx],\
                                    angles='xy',color=self.colorvec,pivot='middle',\
                                    scale=self.wscale*reducevec,width=widthvec )
                # make vector key.
                #keyh = 1.025 ; keyv = 1.05 # upper right corner over colorbar
                keyh = 0.97 ; keyv = 1.06
                keyh = 0.97 ; keyv = 1.11
                #keyh = -0.03 ; keyv = 1.08 # upper left corner
                p = mpl.quiverkey(q,keyh,keyv,\
                                  self.wscale,str(int(self.wscale)),\
                                  fontproperties={'size': 'small'},\
                                  color='black',labelpos='S',labelsep = 0.07)
        ############################################################################################
        ### TEXT. ANYWHERE. add_text.txt should be present with lines x ; y ; text ; color
        ############################################################################################
        try:
            f = open("add_text.txt", 'r')
            for line in f:
              if "#" in line: pass
              else:
                  userx, usery, usert, userc = line.strip().split(';')
                  userc = userc.strip()
                  usert = usert.strip()
                  userx = float(userx.strip())
                  usery = float(usery.strip())
                  if self.mapmode: userx,usery = m(userx,usery)
                  mpl.text(userx,usery,usert,\
                           color = userc,\
                           horizontalalignment='center',\
                           verticalalignment='center')
            f.close()
        except IOError:
            pass
Example #37
0
def define_proj(char, wlon, wlat, back=None, blat=None, blon=None):
    from mpl_toolkits.basemap import Basemap
    import numpy as np
    import matplotlib as mpl
    meanlon = 0.5 * (wlon[0] + wlon[1])
    meanlat = 0.5 * (wlat[0] + wlat[1])
    zewidth = np.abs(wlon[0] - wlon[1]) * 60000. * np.cos(
        3.14 * meanlat / 180.)
    zeheight = np.abs(wlat[0] - wlat[1]) * 60000.
    if blat is None:
        ortholat = meanlat
        if wlat[0] >= 80.: blat = -40.
        elif wlat[1] <= -80.: blat = -40.
        elif wlat[1] >= 0.: blat = wlat[0]
        elif wlat[0] <= 0.: blat = wlat[1]
    else: ortholat = blat
    if blon is None: ortholon = meanlon
    else: ortholon = blon
    h = 50.  ## en km
    radius = 3397200.
    if char == "cyl":        m = Basemap(rsphere=radius,projection='cyl',\
          llcrnrlat=wlat[0],urcrnrlat=wlat[1],llcrnrlon=wlon[0],urcrnrlon=wlon[1])
    elif char == "moll":
        m = Basemap(rsphere=radius, projection='moll', lon_0=meanlon)
    elif char == "ortho":
        m = Basemap(rsphere=radius,
                    projection='ortho',
                    lon_0=ortholon,
                    lat_0=ortholat)
    elif char == "lcc":        m = Basemap(rsphere=radius,projection='lcc',lat_1=meanlat,lat_0=meanlat,lon_0=meanlon,\
          width=zewidth,height=zeheight)
        #llcrnrlat=wlat[0],urcrnrlat=wlat[1],llcrnrlon=wlon[0],urcrnrlon=wlon[1])
    elif char == "npstere":
        m = Basemap(rsphere=radius,
                    projection='npstere',
                    boundinglat=blat,
                    lon_0=0.)
    elif char == "spstere":
        m = Basemap(rsphere=radius,
                    projection='spstere',
                    boundinglat=blat,
                    lon_0=180.)
    elif char == "nplaea":
        m = Basemap(rsphere=radius,
                    projection='nplaea',
                    boundinglat=wlat[0],
                    lon_0=meanlon)
    elif char == "laea":        m = Basemap(rsphere=radius,projection='laea',lon_0=meanlon,lat_0=meanlat,lat_ts=meanlat,\
          width=zewidth,height=zeheight)
        #llcrnrlat=wlat[0],urcrnrlat=wlat[1],llcrnrlon=wlon[0],urcrnrlon=wlon[1])
    elif char == "nsper":
        m = Basemap(rsphere=radius,
                    projection='nsper',
                    lon_0=meanlon,
                    lat_0=meanlat,
                    satellite_height=h * 1000.)
    elif char == "merc":        m = Basemap(rsphere=radius,projection='merc',lat_ts=0.,\
          llcrnrlat=wlat[0],urcrnrlat=wlat[1],llcrnrlon=wlon[0],urcrnrlon=wlon[1])
    elif char == "geos":
        m = Basemap(rsphere=radius, projection='geos', lon_0=meanlon)
    elif char == "robin":
        m = Basemap(rsphere=radius, projection='robin', lon_0=0)
    elif char == "cass":
        if zewidth > 60000.:  ## approx. more than one degree
            m = Basemap(rsphere=radius,projection='cass',\
                          lon_0=meanlon,lat_0=meanlat,\
                          width=zewidth,height=zeheight)
        else:
            m = Basemap(rsphere=radius,projection='cass',\
                          lon_0=meanlon,lat_0=meanlat,\
                          llcrnrlat=wlat[0],urcrnrlat=wlat[1],llcrnrlon=wlon[0],urcrnrlon=wlon[1])
    else:
        errormess("projection not supported.")
    fontsizemer = int(mpl.rcParams['font.size'] * 3. / 4.)
    if zewidth > 60000.:
        if char in ["cyl", "lcc", "merc", "nsper", "laea"]:
            step = findstep(wlon)
        else:
            step = 10.
        steplon = step * 2.
    else:
        print "very small domain !"
        steplon = 0.5
        step = 0.5
    zecolor = 'grey'
    zelinewidth = 1
    zelatmax = 80.
    if meanlat > 75.:
        zelatmax = 90.
        step = step / 2.
        steplon = steplon * 2.
    #    # to show gcm grid:
    #    #zecolor = 'r'
    #    #zelinewidth = 1
    #    #step = 180./48.
    #    #steplon = 360./64.
    #    #zelatmax = 90. - step/3
    #    if char not in ["moll","robin"]:
    #        if wlon[1]-wlon[0] < 2.:  ## LOCAL MODE
    #            m.drawmeridians(np.r_[-1.:1.:0.05], labels=[0,0,0,1], color=zecolor, linewidth=zelinewidth, fontsize=fontsizemer, fmt='%5.2f')
    #            m.drawparallels(np.r_[-1.:1.:0.05], labels=[1,0,0,0], color=zecolor, linewidth=zelinewidth, fontsize=fontsizemer, fmt='%5.2f')
    #        else:  ## GLOBAL OR REGIONAL MODE
    #            m.drawmeridians(np.r_[-180.:180.:steplon], labels=[0,0,0,1], color=zecolor, linewidth=zelinewidth, fontsize=fontsizemer, latmax=zelatmax)
    #            m.drawparallels(np.r_[-90.:90.:step], labels=[1,0,0,0], color=zecolor, linewidth=zelinewidth, fontsize=fontsizemer, latmax=zelatmax)
    if back is not None:
        if back not in ["coast", "sea"]: m.warpimage(marsmap(back), scale=0.75)
        elif back == "coast": m.drawcoastlines()
        elif back == "sea":
            m.drawlsmask(land_color='white', ocean_color='aqua')
        #if not back:
        #    if not var:                                        back = "mola"    ## if no var:         draw mola
        #    elif typefile in ['mesoapi','meso','geo'] \
        #       and proj not in ['merc','lcc','nsper','laea']:  back = "molabw"  ## if var but meso:   draw molabw
        #    else:                                              pass             ## else:              draw None
    return m
Example #38
0
def plot_lc_and_brights(path, bright_file, chi_file, model_curve, data_curve, bb, Rp, nstripes, nboxes, outfile, number, trans_info):
    #Read in the values for model and data light curves
    model_time = []
    model_flux = []
    data_time_on = []
    data_flux_on = []
    data_time_off = []
    data_flux_off = []
    
    #Read in file
    temp = []
    for line in open(bright_file):                           
        temp.append(float(line))
    brights = np.array(temp)
   
    #Define latitudes of boxes
    lat1 = bb - Rp
    lat2 = bb + Rp

    for line in open(model_curve):                            
        new_array = line.split(' ')
        model_time.append(float(new_array[0]))
        model_flux.append(float(new_array[1]))
        
    for line in open(data_curve):                            
        new_array = line.split(' ')
        if float(new_array[0]) >= model_time[0] and float(new_array[0]) <= model_time[len(model_time) - 1]:
            data_time_on.append(float(new_array[0]))
            data_flux_on.append(float(new_array[1]))
        else:
            data_time_off.append(float(new_array[0]))
            data_flux_off.append(float(new_array[1]))

    try:
        information = csv.reader(open(trans_info))
    except:
        information = []
    transit_count = 1
    
    for row in information:
        trans_time = []
        trans_flux = []
        #Create the plot and label it
        plt.plot(model_time, model_flux, c='black', label="Model")
        plt.scatter(data_time_on, data_flux_on, c='red', marker='+', label="Brightness Map Region")
        plt.scatter(data_time_off, data_flux_off, c='green', marker = '+', label="Data")
        minimum = min(data_flux_on + data_flux_off)
        maximum = max(data_flux_on + data_flux_off)
        diff = maximum - minimum
        plt.ylim(ymax=maximum + (diff * .85))
        plt.ylim(ymin=minimum - (diff * .1))
        plt.xlabel("Orbital Phase")
        plt.ylabel("Relative Flux")
        plt.title("Model Light Curve Vs. Data - Window %d" % number)
    
           #Set up arrays for brightnesses and positions
        nx = nboxes * 50
        ny = nboxes * 50
        bright_stripe = np.array(brights[nboxes:nboxes+nstripes])
        bright_box = np.array(brights[0:nboxes])
        img = np.zeros((nx,ny))
        idx1_stripe = np.arange(0, nstripes, 1.)/nstripes * nx
        idx2_stripe = (np.arange(0, nstripes, 1.) + 1)/nstripes * nx - 1
        idx1_box = np.arange(0, nboxes, 1.)/nboxes * nx
        idx2_box = (np.arange(0, nboxes, 1.) + 1)/nboxes * nx - 1
        idy1_lat = int(lat1 * ny/2 + ny/2 + 0.5)
        idy2_lat = int(lat2 * ny/2 + ny/2 + 0.5) - 1
    
        #Populate the pixel values
        for jj in range(nstripes):
            idx1 = idx1_stripe[jj]
            idx2 = idx2_stripe[jj]
            idy1 = 0
            idy2 = idy1_lat-1
            img[idy1:idy2, idx1:idx2] = bright_stripe[jj]
            idy1 = idy2_lat+1
            idy2 = ny-1
            img[idy1:idy2, idx1:idx2] = bright_stripe[jj]
        for jj in range(nboxes):
            idx1 = idx1_box[jj]
            idx2 = idx2_box[jj]
            idy1 = idy1_lat
            idy2 = idy2_lat
            img[idy1:idy2, idx1:idx2] = bright_box[jj]
    
        ax = plt.axes([.15, .6, .32, .32])
        plt.imsave(path + "/temp.png", img, cmap='hot', vmin=0.85, vmax=1.15)
        plt.imshow(img, cmap='hot')    
        plt.clim(0.85,1.15)
        plt.colorbar(shrink=0.5)    

        #Create the plot
        bmap = Basemap(projection='moll', lon_0 = 0)
        bmap.warpimage(path + "/temp.png")

        #Create the plots of the transits
        for line in open(path + "/" + "input_files/binned_%d.out" % number):
            new_array = line.split(' ')
            trans_time.append(float(new_array[0]))
            trans_flux.append(float(new_array[1]))
        minimum = min(trans_flux[int(row[0]):int(row[1])])
        maximum = max(trans_flux[int(row[0]):int(row[1])])
        diff = maximum - minimum
        trans_ax = plt.axes([.58,.6,.27,.27])
        plt.plot(model_time[int(row[0]):int(row[1])], model_flux[int(row[0]):int(row[1])], c='black', label="Model")
        plt.scatter(trans_time[int(row[0]):int(row[1])], trans_flux[int(row[0]):int(row[1])], c='red', marker='+', label="Data")
        plt.xlabel("Orbital Phase")
        plt.ylabel("Relative Flux")
        plt.title("Transit %d" % transit_count)
        plt.ylim(ymax=maximum + (diff * .08))
        plt.ylim(ymin=minimum - (diff * .08))
        #plt.setp(trans_ax)
        fig = plt.gcf()
        fig.set_size_inches(18.5,11.5)
        plt.savefig(path + "/" + outfile + "_t%02d" % transit_count + ".png", dpi=120)
        print "Window:  %d Trans: %d" % (number, transit_count - 1)
        transit_count += 1
        del trans_time[:]
        del trans_flux[:]
        plt.close()
Example #39
0
    # draw the edge of the map projection region (the projection limb)
    ###bm1.drawmapboundary()
    # draw lat/lon grid lines every 30 degrees. But omit labels
    ###bm1.drawmeridians(np.arange(0.,360.,60.),labels=[0,0,0,0],fontsize=10,linewidth=0.25)
    bm1.drawparallels(np.arange(-90.,120.,30.),labels=[0,0,0,0],fontsize=10,linewidth=0.5)

    # now plot the quantity on tthe map
    bm1.pcolormesh(xm,ym,chosen_p,cmap=m_map)

    # indicate the night and day regions
    if req_lightlevel:
      bm1.pcolormesh(lons_p, lats, lightlevel , cmap=plt.cm.gray,alpha=0.2)

    # try put the geography under data
    ###bm1.warpimage( image=etopo_jpg )
    bm1.warpimage(image='/nfs/see-fs-02_users/earmgr/Images/etopo3000.jpg',scale=0.64)
    ###bm1.etopo(scale=0.28)
    # Labels on equator
    xst = np.zeros(3)
    yst = np.zeros(3)
    xst[0],yst[0] = bm1(65.0,0.0)
    xst[1],yst[1] = bm1(-160.0,0.0)
    xst[2],yst[2] = bm1(-45.0,0.0)

  else:
    print "Basemap not found plotting anyway"
    # Now to plot the actual data
    plt.pcolormesh(lons_p, lats, chosen_p , cmap=plt.cm.Purples)
    # indicate the night and day regions
    if req_lightlevel:
      plt.pcolormesh(lons_p, lats, lightlevel , cmap=plt.cm.gray,alpha=0.2)
from mpl_toolkits.basemap import Basemap
from master_variables import ZONE_OF_AVOIDANCE
import numpy as np
import matplotlib.pyplot as plt
import sys

if __name__ == "__main__":
	rc('text', usetex=True)
	rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
	# lon_0 is central longitude of projection.
	# resolution = 'c' means use crude resolution coastlines.
	m = Basemap(projection='moll',lat_0=0,lon_0=0,resolution='h')
	# draw parallels and meridians.
	m.drawparallels(np.arange(-90.,180.,15.),color='white',linewidth=.5)
	m.drawmeridians(np.arange(0.,420.,15.),color='white',linewidth=.5)
	# Draw a line of longitude
	m.drawparallels([ZONE_OF_AVOIDANCE,-ZONE_OF_AVOIDANCE],color='yellow',linewidth=1)
	m.warpimage(sys.argv[1],scale=1.0)
	#m.drawgreatcircle(0,0,4*15,0,color='r',linewidth=1)
	x,y=m(0,-(ZONE_OF_AVOIDANCE+2))
	plt.text(x,y,r'$b = %i^{\circ}$' % (-(ZONE_OF_AVOIDANCE)),color='yellow',size=7, ha='center', va='top')
	x_,y_=m(0,(ZONE_OF_AVOIDANCE+2))
	plt.text(x_,y_,r'$b = %i^{\circ}$' % (ZONE_OF_AVOIDANCE),color='yellow',size=7,ha='center', va='bottom')
	x__,y__=m(0,0)
	plt.text(x__,y__,r'Zone of Avoidance',color='yellow',size=16,ha='center', va='center')
	# Draw a line of latitude
	#m.drawgreatcircle(4*15,0,4*15,4*15,color='r',linewidth=1)
	#x_,y_=m(4*15+4,2*15)
	#plt.text(x_,y_,r'$b$',color='r',size=16)
	plt.savefig(sys.argv[2],dpi=300,transparent=True)
Example #41
0
class Window(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        # Injected by the compile_and_import_ui_files() function.
        self.ui = qt_window.Ui_MainWindow()  # NOQA
        self.ui.setupUi(self)

        label = {"z": "vertical", "e": "east", "n": "north"}
        for component in ["z", "n", "e"]:
            p = getattr(self.ui, "%s_graph" % component)
            p.setLabel("left", "Displacement", units="m")
            p.setLabel("bottom", "Time since event", units="s")

            p.setTitle(label[component].capitalize() + " component")

        self.ui.n_graph.setXLink(self.ui.e_graph)
        self.ui.n_graph.setXLink(self.ui.z_graph)
        self.ui.e_graph.setXLink(self.ui.z_graph)
        self.ui.n_graph.setYLink(self.ui.e_graph)
        self.ui.n_graph.setYLink(self.ui.z_graph)
        self.ui.e_graph.setYLink(self.ui.z_graph)

        # Set some random mt at startup.
        m_rr = 4.71e17
        m_tt = 3.81e15
        m_pp = -4.74e17
        m_rt = 3.99e16
        m_rp = -8.05e16
        m_tp = -1.23e17
        self.ui.m_rr.setValue(m_rr)
        self.ui.m_tt.setValue(m_tt)
        self.ui.m_pp.setValue(m_pp)
        self.ui.m_rt.setValue(m_rt)
        self.ui.m_rp.setValue(m_rp)
        self.ui.m_tp.setValue(m_tp)

        self.instaseis_db = None
        self.finite_source = None
        self.st_copy = None

        self.plot_map()
        self.plot_mt()
        self.update()

    @property
    def focmec(self):
        if self.ui.source_tab.currentIndex() == 0:
            return [
                float(self.ui.m_rr.value()),
                float(self.ui.m_tt.value()),
                float(self.ui.m_pp.value()),
                float(self.ui.m_rt.value()),
                float(self.ui.m_rp.value()),
                float(self.ui.m_tp.value()),
            ]
        elif self.ui.source_tab.currentIndex() == 1:
            source = Source.from_strike_dip_rake(
                latitude=float(self.ui.source_latitude.value()),
                longitude=float(self.ui.source_longitude.value()),
                depth_in_m=float(self.source_depth) * 1000.0,
                strike=float(self.ui.strike_slider.value()),
                dip=float(self.ui.dip_slider.value()),
                rake=float(self.ui.rake_slider.value()),
                M0=1e16,
            )
            return [
                source.m_rr,
                source.m_tt,
                source.m_pp,
                source.m_rt,
                source.m_rp,
                source.m_tp,
            ]

    def plot_mt(self):
        self.mpl_mt_figure = self.ui.mt_fig.fig
        self.mpl_mt_ax = self.mpl_mt_figure.add_axes([0.0, 0.0, 1.0, 1.0])
        self.mpl_mt_ax.set_axis_off()
        self.mpl_mt_figure.patch.set_alpha(0.0)
        self.mpl_mt_figure.set_facecolor("None")

        self._draw_mt()

    def _draw_mt(self):
        if not hasattr(self, "mpl_mt_ax"):
            return

        try:
            self.bb.remove()
        except Exception:
            pass

        fm = self.focmec
        fm = [_i / 1e16 for _i in fm]
        self.bb = beach(fm, xy=(0, 0), width=200, linewidth=1, facecolor="red")
        self.mpl_mt_ax.add_collection(self.bb)
        self.mpl_mt_ax.set_xlim(-105, 105)
        self.mpl_mt_ax.set_ylim(-105, 105)
        self.mpl_mt_figure.canvas.draw()

    def plot_mt_finite(self):
        self.mpl_mt_finite_figure = self.ui.mt_fig_finite.fig
        self.mpl_mt_finite_ax = self.mpl_mt_finite_figure.add_axes(
            [0.0, 0.0, 1.0, 1.0])
        self.mpl_mt_finite_ax.set_axis_off()
        self.mpl_mt_finite_figure.patch.set_alpha(0.0)
        self.mpl_mt_finite_figure.set_facecolor("None")

        self._draw_mt_finite()

    def _draw_mt_finite(self):
        if not hasattr(self, "mpl_mt_finite_ax"):
            return

        try:
            self.bb_finite.remove()
        except Exception:
            pass

        self.bb_finite = beach(
            self.finite_source.CMT.tensor / 1e16,
            xy=(0, 0),
            width=200,
            linewidth=1,
            facecolor="red",
        )
        self.mpl_mt_finite_ax.add_collection(self.bb_finite)
        self.mpl_mt_finite_ax.set_xlim(-105, 105)
        self.mpl_mt_finite_ax.set_ylim(-105, 105)
        self.mpl_mt_finite_figure.canvas.draw()

    def plot_cmt_sliprate(self):
        fig = self.ui.cmt_sliprate.fig
        fig.clf()
        fig.set_facecolor("white")
        ax = fig.add_axes([0.05, 0.2, 0.9, 0.8], frameon=False)
        ax.get_xaxis().tick_bottom()
        ax.axes.get_yaxis().set_visible(False)

        nsamp = len(self.finite_source.CMT.sliprate)
        time = np.linspace(0,
                           self.finite_source.CMT.dt * nsamp,
                           nsamp,
                           endpoint=False)

        ax.plot(time, self.finite_source.CMT.sliprate)
        ax.set_xlim(0.0, self.finite_source.rupture_duration * 2.0)
        fig.canvas.draw()

    def plot_map(self):
        self.mpl_map_figure = self.ui.map_fig.fig

        # if hasattr(self, 'mpl_map_ax'):
        #     self.mpl_map_ax.clear()

        self.mpl_map_ax = self.mpl_map_figure.add_axes(
            [0.01, 0.01, 0.98, 0.98])
        self.mpl_map_ax.set_title("Left click: Set Receiver; Right click: Set "
                                  "Source")

        self.map = Basemap(projection="moll",
                           lon_0=0,
                           resolution="c",
                           ax=self.mpl_map_ax)

        self.map.drawmapboundary(fill_color="#cccccc")

        # Define planet radii and images paths
        radii_planets = {
            "Titan": 2575e3,
            "Europa": 1561e3,
            "Enceladus": 252e3,
            "Ganymede": 2631e3,
            "Mars": 3389.5e3,
            "Venus": 6051.8e3,
            "Earth": 6371e3,
        }
        imfiles = {
            "Titan": "titan_radar_colored_800.jpg",
            "Europa": "europa_comp_800.jpg",
            "Enceladus": "enceladus_jpl_800.jpg",
            "Ganymede": "ganymede_usgs_800.jpg",
            "Mars": "mola_texture_shifted_800.jpg",
            "Venus": "venus_magellan_800.jpg",
            "Earth": "earth_marble_ng_800.jpg",
            "default": "grid.png",
        }

        imfile = os.path.join(DATA, imfiles["default"])
        if self.instaseis_db:
            for key, value in radii_planets.items():
                if abs(self.instaseis_db.info.planet_radius - value) < 10e3:
                    imfile = os.path.join(DATA, imfiles[key])

        self.map.warpimage(image=imfile, zorder=0)

        self.mpl_map_figure.patch.set_alpha(0.0)

        self.mpl_map_figure.canvas.mpl_connect("button_press_event",
                                               self._on_map_mouse_click_event)
        self.mpl_map_figure.canvas.draw()

    def _on_map_mouse_click_event(self, event):
        if None in (event.xdata, event.ydata):
            return
        # Get map coordinates by the inverse transform.
        lng, lat = self.map(event.xdata, event.ydata, inverse=True)
        # Left click: set receiver
        if event.button == 1:
            self.ui.receiver_longitude.setValue(lng)
            self.ui.receiver_latitude.setValue(lat)
        # Right click: set event
        elif event.button == 3 and self.ui.finsource_tab.currentIndex() == 0:
            self.ui.source_longitude.setValue(lng)
            self.ui.source_latitude.setValue(lat)

    def _plot_event(self):
        if self.ui.finsource_tab.currentIndex() == 0:
            s = self.source
            lng, lat = s.longitude, s.latitude
        elif self.ui.finsource_tab.currentIndex() == 1:
            s = self.finite_source
            s.find_hypocenter()
            lng, lat = s.hypocenter_longitude, s.hypocenter_latitude

        try:
            if (self.__event_map_obj.longitude == lng
                    and self.__event_map_obj.latitude == lat):
                return
        except AttributeError:
            pass

        try:
            self.__event_map_obj.remove()
        except AttributeError:
            pass

        x1, y1 = self.map(lng, lat)
        self.__event_map_obj = self.map.scatter(x1,
                                                y1,
                                                s=300,
                                                zorder=10,
                                                color="yellow",
                                                marker="*",
                                                edgecolor="k")
        self.__event_map_obj.longitude = lng
        self.__event_map_obj.latitude = lat
        self.mpl_map_figure.canvas.draw()

    def _plot_receiver(self):
        r = self.receiver
        lng, lat = r.longitude, r.latitude
        try:
            if (self.__receiver_map_obj.longitude == lng
                    and self.__receiver_map_obj.latitude == lat):
                return
        except AttributeError:
            pass

        try:
            self.__receiver_map_obj.remove()
        except AttributeError:
            pass

        x1, y1 = self.map(lng, lat)
        self.__receiver_map_obj = self.map.scatter(x1,
                                                   y1,
                                                   s=170,
                                                   zorder=10,
                                                   color="red",
                                                   marker="v",
                                                   edgecolor="k")
        self.__receiver_map_obj.longitude = lng
        self.__receiver_map_obj.latitude = lat
        self.mpl_map_figure.canvas.draw()

    def _plot_bg_receivers(self):
        try:
            self.__bg_receivers_map_obj.remove()
        except AttributeError:
            pass

        xl = []
        yl = []
        for r in self.receivers:
            lng, lat = r.longitude, r.latitude
            x1, y1 = self.map(lng, lat)
            xl.append(x1)
            yl.append(y1)

        self.__bg_receivers_map_obj = self.map.scatter(
            xl,
            yl,
            s=100,
            zorder=5,
            color="k",
            marker="v",
            edgecolor="gray",
            alpha=0.3,
        )
        self.mpl_map_figure.canvas.draw()

    @property
    def source(self):
        fm = self.focmec
        return Source(
            latitude=float(self.ui.source_latitude.value()),
            longitude=float(self.ui.source_longitude.value()),
            depth_in_m=float(self.source_depth) * 1000.0,
            m_rr=fm[0],
            m_tt=fm[1],
            m_pp=fm[2],
            m_rt=fm[3],
            m_rp=fm[4],
            m_tp=fm[5],
        )

    @property
    def receiver(self):
        return Receiver(
            latitude=float(self.ui.receiver_latitude.value()),
            longitude=float(self.ui.receiver_longitude.value()),
        )

    def update(self, force=False):

        try:
            self._plot_receiver()
            self._plot_event()
        except AttributeError:
            return

        if (not bool(self.ui.auto_update_check_box.checkState())
                and self.ui.finsource_tab.currentIndex() == 1 and not force
                and self.st_copy is None):
            return

        components = ["z", "n", "e"]
        components_map = {0: ("Z", "N", "E"), 1: ("Z", "R", "T")}

        components_choice = int(self.ui.components_combo.currentIndex())

        label_map = {
            0: {
                "z": "vertical",
                "n": "north",
                "e": "east"
            },
            1: {
                "z": "vertical",
                "n": "radial",
                "e": "transverse"
            },
        }

        for component in components:
            p = getattr(self.ui, "%s_graph" % component)
            p.setTitle(label_map[components_choice][component].capitalize() +
                       " component")

        if self.ui.finsource_tab.currentIndex() == 0:
            src_latitude = self.source.latitude
            src_longitude = self.source.longitude
            src_depth_in_m = self.source.depth_in_m
        else:
            src_latitude = self.finite_source.hypocenter_latitude
            src_longitude = self.finite_source.hypocenter_longitude
            src_depth_in_m = self.finite_source.hypocenter_depth_in_m

        rec = self.receiver
        try:
            # Grab resampling settings from the UI.
            if bool(self.ui.resample_check_box.checkState()):
                dt = float(self.ui.resample_factor.value())
                dt = self.instaseis_db.info.dt / dt
            else:
                dt = None
            if self.ui.finsource_tab.currentIndex() == 0:
                st = self.instaseis_db.get_seismograms(
                    source=self.source,
                    receiver=self.receiver,
                    dt=dt,
                    components=components_map[components_choice],
                )
            elif (not bool(self.ui.auto_update_check_box.checkState())
                  and self.ui.finsource_tab.currentIndex() == 1 and not force):
                st = self.st_copy.copy()
            else:
                prog_diag = QtGui.QProgressDialog("Calculating", "Cancel", 0,
                                                  len(self.finite_source),
                                                  self)
                prog_diag.setWindowModality(QtCore.Qt.WindowModal)
                prog_diag.setMinimumDuration(0)

                def get_prog_fct():
                    def set_value(value, count):
                        prog_diag.setValue(value)
                        if prog_diag.wasCanceled():
                            return True

                    return set_value

                prog_diag.setValue(0)
                st = self.instaseis_db.get_seismograms_finite_source(
                    sources=self.finite_source,
                    receiver=self.receiver,
                    dt=dt,
                    components=("Z", "N", "E"),
                    progress_callback=get_prog_fct(),
                )
                prog_diag.setValue(len(self.finite_source))
                if not st:
                    return

                baz = geodetics.gps2dist_azimuth(
                    self.finite_source.CMT.latitude,
                    self.finite_source.CMT.longitude,
                    rec.latitude,
                    rec.longitude,
                )[2]
                self.st_copy = st.copy()
                st.rotate("NE->RT", baz)
                st += self.st_copy
                self.st_copy = st.copy()

            if self.ui.finsource_tab.currentIndex() == 1 and bool(
                    self.ui.plot_CMT_check_box.checkState()):
                st_cmt = self.instaseis_db.get_seismograms(
                    source=self.finite_source.CMT,
                    receiver=self.receiver,
                    dt=dt,
                    components=components_map[components_choice],
                    reconvolve_stf=True,
                    remove_source_shift=False,
                )
            else:
                st_cmt = None

            # check filter values from the UI
            zp = bool(self.ui.zero_phase_check_box.checkState())
            if bool(self.ui.lowpass_check_box.checkState()):
                try:
                    freq = 1.0 / float(self.ui.lowpass_period.value())
                    st.filter("lowpass", freq=freq, zerophase=zp)
                    if st_cmt is not None:
                        st_cmt.filter("lowpass", freq=freq, zerophase=zp)
                except ZeroDivisionError:
                    # this happens when typing in the lowpass_period box
                    pass

            if bool(self.ui.highpass_check_box.checkState()):
                try:
                    freq = 1.0 / float(self.ui.highpass_period.value())
                    st.filter("highpass", freq=freq, zerophase=zp)
                    if st_cmt is not None:
                        st_cmt.filter("highpass", freq=freq, zerophase=zp)
                except ZeroDivisionError:
                    # this happens when typing in the highpass_period box
                    pass

        except AttributeError:
            return

        if bool(self.ui.tt_times.checkState()):
            great_circle_distance = geodetics.locations2degrees(
                src_latitude, src_longitude, rec.latitude, rec.longitude)
            self.tts = tau_model.get_travel_times(
                source_depth_in_km=src_depth_in_m / 1000.0,
                distance_in_degree=great_circle_distance,
            )

        for ic, component in enumerate(components):
            plot_widget = getattr(self.ui, "%s_graph" % component.lower())
            plot_widget.clear()
            tr = st.select(component=components_map[components_choice][ic])[0]
            times = tr.times()
            plot_widget.plot(times, tr.data, pen="k")
            plot_widget.ptp = tr.data.ptp()
            if st_cmt is not None:
                tr = st_cmt.select(
                    component=components_map[components_choice][ic])[0]
                times = tr.times()
                plot_widget.plot(times, tr.data, pen="r")

            if bool(self.ui.tt_times.checkState()):
                tts = []
                for tt in self.tts:
                    if tt.time >= times[-1]:
                        continue
                    tts.append(tt)
                    if tt.name[0].lower() == "p":
                        pen = "#008c2866"
                    else:
                        pen = "#95000066"
                    plot_widget.addLine(x=tt.time, pen=pen, z=-10)
                self.tts = tts
        self.set_info()

    @QtCore.Slot()
    def on_select_folder_button_released(self):
        pwd = os.getcwd()
        self.folder = str(
            QtGui.QFileDialog.getExistingDirectory(self, "Choose Directory",
                                                   pwd))
        if not self.folder:
            return
        self.instaseis_db = open_db(self.folder)

        # Adjust depth slider to the DB.
        max_rad = self.instaseis_db.info.max_radius / 1e3
        min_rad = self.instaseis_db.info.min_radius / 1e3
        self.ui.depth_slider.setMinimum(min_rad - max_rad)
        self.ui.depth_slider.setMaximum(0)

        self._setup_finite_source()

        self.plot_map()
        self.update()
        self.set_info()

    @QtCore.Slot()
    def on_select_remote_connection_button_released(self):
        text, ok = QtGui.QInputDialog.getText(
            self,
            "Remote Instaseis Connection",
            "Enter URL to remote Instaseis Server:",
        )
        if not ok:
            return
        text = str(text)

        self.instaseis_db = open_db(text)

        # Adjust depth slider to the DB.
        max_rad = self.instaseis_db.info.max_radius / 1e3
        min_rad = self.instaseis_db.info.min_radius / 1e3
        self.ui.depth_slider.setMinimum(min_rad - max_rad)
        self.ui.depth_slider.setMaximum(0)

        self._setup_finite_source()

        self.plot_map()
        self.update()
        self.set_info()

    @QtCore.Slot()
    def on_open_srf_file_button_released(self):
        pwd = os.getcwd()
        self.finite_src_file = str(
            QtGui.QFileDialog.getOpenFileName(
                self,
                "Choose *.srf or *.param File",
                pwd,
                "Standard Rupture Format (*.srf);;"
                "USGS finite source files (*.param)",
            ))
        if not self.finite_src_file:
            return
        if self.finite_src_file.endswith(".srf"):
            self.finite_source = FiniteSource.from_srf_file(
                self.finite_src_file, normalize=True)
        elif self.finite_src_file.endswith(".param"):
            self.finite_source = FiniteSource.from_usgs_param_file(
                self.finite_src_file)
        else:
            raise IOError("unknown file type *.%s" %
                          self.finite_src_file.split(".")[-1])

        self._setup_finite_source()
        self.update()
        self.set_info()

    def _setup_finite_source(self):
        if self.finite_source is None:
            return
        if self.instaseis_db is not None:
            # this is a super uggly construction: if you open a different DB,
            # it will not use the original finite source, but the one already
            # messed up for the previously used DB. Not fixing it here, but in
            # the new GUI we should.

            # self.finite_source.set_sliprate_lp(
            #     dt=self.instaseis_db.info.dt,
            # nsamp=self.instaseis_db.info.npts,
            #     freq=1.0/self.instaseis_db.info.period)

            nsamp = (
                int(self.instaseis_db.info.period / self.finite_source[0].dt) *
                50)
            self.finite_source.resample_sliprate(dt=self.finite_source[0].dt,
                                                 nsamp=nsamp)
            self.finite_source.lp_sliprate(freq=1.0 /
                                           self.instaseis_db.info.period)
            self.finite_source.resample_sliprate(
                dt=self.instaseis_db.info.dt,
                nsamp=self.instaseis_db.info.npts)

        self.finite_source.compute_centroid()
        self.plot_mt_finite()
        self.plot_cmt_sliprate()

    def set_info(self):
        info_str = ""
        if self.finite_source is not None:
            info_str += str(self.finite_source) + "\n"
        else:
            info_str += str(self.source) + "\n"
        if self.instaseis_db is not None:
            info_str += str(self.instaseis_db) + "\n"
        self.ui.info_text.setText(info_str)

    @QtCore.Slot()
    def on_load_source_button_released(self):
        pwd = os.getcwd()
        self.source_file = str(
            QtGui.QFileDialog.getOpenFileName(self, "Choose Source File", pwd))
        if not self.source_file:
            return

        s = Source.parse(self.source_file)
        self.ui.m_rr.setValue(s.m_rr)
        self.ui.m_pp.setValue(s.m_pp)
        self.ui.m_rp.setValue(s.m_rp)
        self.ui.m_tt.setValue(s.m_tt)
        self.ui.m_rt.setValue(s.m_rt)
        self.ui.m_tp.setValue(s.m_tp)

        self.ui.source_longitude.setValue(s.longitude)
        self.ui.source_latitude.setValue(s.latitude)
        self.ui.depth_slider.setValue(-s.depth_in_m / 1e3)
        self.set_info()

    @QtCore.Slot("double")
    def on_source_latitude_valueChanged(self, *args):
        self.update()

    @QtCore.Slot("double")
    def on_source_longitude_valueChanged(self, *args):
        self.update()

    @QtCore.Slot("double")
    def on_receiver_latitude_valueChanged(self, *args):
        self.update()

    @QtCore.Slot("double")
    def on_receiver_longitude_valueChanged(self, *args):
        self.update()

    @QtCore.Slot("double")
    def on_m_rr_valueChanged(self, *args):
        self._draw_mt()
        self.update()

    @QtCore.Slot("double")
    def on_m_tt_valueChanged(self, *args):
        self._draw_mt()
        self.update()

    @QtCore.Slot("double")
    def on_m_pp_valueChanged(self, *args):
        self._draw_mt()
        self.update()

    @QtCore.Slot("double")
    def on_m_rt_valueChanged(self, *args):
        self._draw_mt()
        self.update()

    @QtCore.Slot("double")
    def on_m_rp_valueChanged(self, *args):
        self._draw_mt()
        self.update()

    @QtCore.Slot("double")
    def on_m_tp_valueChanged(self, *args):
        self._draw_mt()
        self.update()

    @property
    def source_depth(self):
        value = int(-1.0 * int(self.ui.depth_slider.value()))
        return value

    @QtCore.Slot()
    def on_depth_slider_valueChanged(self, *args):
        self.ui.depth_label.setText("Depth: %i km" % self.source_depth)
        self.update()

    @QtCore.Slot()
    def on_strike_slider_valueChanged(self, *args):
        self.ui.strike_value.setText("%i" % self.ui.strike_slider.value())
        self._draw_mt()
        self.update()

    @QtCore.Slot()
    def on_dip_slider_valueChanged(self, *args):
        self.ui.dip_value.setText("%i" % self.ui.dip_slider.value())
        self._draw_mt()
        self.update()

    @QtCore.Slot()
    def on_rake_slider_valueChanged(self, *args):
        self.ui.rake_value.setText("%i" % self.ui.rake_slider.value())
        self._draw_mt()
        self.update()

    def autoRange(self):
        widgets = [getattr(self.ui, "%s_graph" % _i) for _i in ("z", "n", "e")]
        widgets.sort(key=lambda x: x.ptp)
        widgets[-1].autoRange()

    @QtCore.Slot()
    def on_reset_view_button_released(self, *args):
        self.autoRange()

    @QtCore.Slot()
    def on_resample_check_box_stateChanged(self):
        resample = bool(self.ui.resample_check_box.checkState())
        self.ui.resample_factor.setEnabled(resample)
        self.ui.sr_ref_label.setEnabled(resample)
        self.update()

    @QtCore.Slot("double")
    def on_resample_factor_valueChanged(self, *args):
        self.update()

    @QtCore.Slot()
    def on_tt_times_stateChanged(self):
        self.update()

    @QtCore.Slot()
    def on_lowpass_check_box_stateChanged(self):
        resample = bool(self.ui.lowpass_check_box.checkState())
        self.ui.lowpass_period.setEnabled(resample)
        self.ui.lowpass_label.setEnabled(resample)
        self.update()

    @QtCore.Slot("double")
    def on_lowpass_period_valueChanged(self, *args):
        self.update()

    @QtCore.Slot()
    def on_highpass_check_box_stateChanged(self):
        resample = bool(self.ui.highpass_check_box.checkState())
        self.ui.highpass_period.setEnabled(resample)
        self.ui.highpass_label.setEnabled(resample)
        self.update()

    @QtCore.Slot("double")
    def on_highpass_period_valueChanged(self, *args):
        self.update()

    @QtCore.Slot()
    def on_zero_phase_check_box_stateChanged(self):
        self.update()

    @QtCore.Slot("int")
    def on_components_combo_currentIndexChanged(self):
        self.update()

    @QtCore.Slot()
    def on_finsource_tab_currentChanged(self):
        self.update()

    @QtCore.Slot()
    def on_source_tab_currentChanged(self):
        self._draw_mt()
        self.update()
        self.autoRange()

    @QtCore.Slot()
    def on_update_button_released(self):
        self.update(force=True)

    @QtCore.Slot()
    def on_load_stations_button_released(self):
        pwd = os.getcwd()
        self.stations_file = str(
            QtGui.QFileDialog.getOpenFileName(self, "Choose Stations File",
                                              pwd))
        if not self.stations_file:
            return

        self.receivers = Receiver.parse(self.stations_file)
        recnames = []
        for _r in self.receivers:
            recnames.append("%s.%s" % (_r.network, _r.station))

        self.ui.stations_combo.clear()
        self.ui.stations_combo.addItems(recnames)

        self._plot_bg_receivers()

    @QtCore.Slot("int")
    def on_stations_combo_currentIndexChanged(self):
        idx = self.ui.stations_combo.currentIndex()
        self.ui.receiver_longitude.setValue(self.receivers[idx].longitude)
        self.ui.receiver_latitude.setValue(self.receivers[idx].latitude)

    def eventFilter(self, source, event):
        if event.type() == QtCore.QEvent.MouseMove:
            if (source.parent()
                    in [self.ui.z_graph, self.ui.n_graph, self.ui.e_graph]
                    and event.buttons() == QtCore.Qt.NoButton):
                try:
                    tt = float(
                        self.ui.z_graph.mapToView(
                            pg.Point(event.pos().x(),
                                     event.pos().y())).x())
                    closest_phase = min(self.tts,
                                        key=lambda x: abs(x.time - tt))
                    tooltipstr = ("Mouse at %6.2f s, closest phase = %s, "
                                  "arriving at %6.2f s" %
                                  (tt, closest_phase.name, closest_phase.time))
                except Exception:
                    tooltipstr = ""

                self.ui.z_graph.setToolTip(tooltipstr)
                self.ui.n_graph.setToolTip(tooltipstr)
                self.ui.e_graph.setToolTip(tooltipstr)

        return QtGui.QMainWindow.eventFilter(self, source, event)
	m.drawmapboundary(color='#787878', linewidth=0.4)

if(mproj == 'CE'):
	# define projection
	m = Basemap(projection='cyl',llcrnrlat=-90,urcrnrlat=90,area_thresh=10000,\
	llcrnrlon=30,urcrnrlon=390,resolution='l')

if(mproj == 'RB'):
	m = Basemap(projection='robin',lon_0=-150,resolution='l')

if(yyyy != '0000'):
	orig = Image.open(infile)
	bg = Image.new("RGB", orig.size, (211,211,211))
	bg.paste(orig,orig)
	bg.save("./tmp.png")
	im = m.warpimage("./tmp.png")

#orig = np.array(orig).astype(np.float) / 255
#fig.figimage(orig, logo_x, logo_y, zorder=10)

if(yyyy == '0000'):
	# draw coastlines and boundaries
	m.drawcoastlines(color='#787878',linewidth=mlw)
	m.drawcountries(color='#787878',linewidth=mlw)


#Add the NOAA logo (except for DIY)
if(imgsize != 'DIY'):
	logo_im = Image.open(logo_image)
	height = logo_im.size[1]
	# We need a float array between 0-1, rather than
Example #43
0
def createContourMapFromNOAAPSL(input,
                                index,
                                baseColor=None,
                                baseTexture=None,
                                colormap="coolwarm",
                                dataKey="",
                                debug=False,
                                filename="",
                                levels=100,
                                transparent=False):
    """Take a NetCDF file from the NOAA Physical Sciences Lab and turn it into a contour map.
    """

    if isinstance(input, netCDF4.Dataset):
        data = input
    elif isinstance(input, str):  # We probably got a CSV filename
        data = netCDF4.Dataset(input)
    else:
        print(
            "createContourMapFromNOAAPSL: Error: You must pass either a NetCDF filename or a netCDF4 Dataset instance"
        )
        return ()

    if dataKey == "":
        possible_keys = ["tmax", 'tmin', 'precip']

        for key in possible_keys:
            if key in data.variables:
                dataKey = key
                break
        if dataKey == "":  # If we haven't matched anything, user will need to supply latKey
            print(
                "createContourMapFromNOAAPSL: Error: data key not recognized. Specify with dataKey="
            )
            return ()

    plt.rcParams["figure.figsize"] = (16, 8)

    if baseTexture is not None:
        m = Basemap(projection='cyl',llcrnrlat=-90,urcrnrlat=90,\
                    llcrnrlon=0.25,urcrnrlon=359.75,resolution='l')
        m.warpimage(baseTexture)
    elif baseColor is not None:
        fig.patch.set_facecolor(baseColor)

    if not transparent:
        m.drawcoastlines()

    lat = data.variables['lat'][:]
    lon = data.variables['lon'][:]
    this_time = data.variables['time'][:]
    values = data.variables[dataKey][:]

    lons, lats = np.meshgrid(lon, lat)

    # Convert time from hours since epoch 1900-01-01
    epoch = datetime.datetime(1900, 1, 1, 0, 0)
    date = epoch + (datetime.timedelta(hours=1) * this_time)

    index_to_use = None
    if isinstance(index, (float, int)):
        index_to_use = round(index)
        if index_to_use >= len(date):
            print("createContourMapFromNOAAPSL: Error: index not present.")
            return ()
    elif isinstance(index, str):
        try:
            index_to_use = np.where(date == parser.parse(index))[0][0]
        except IndexError:
            print("createContourMapFromNOAAPSL: Error: index not present.")
            return ()
    else:
        print(
            "createContourMapFromNOAAPSL: Error: index not recognized. Provide either a numeric index or a date"
        )
        return ()

    if debug:
        print("Dataset min value:", np.min(values[index_to_use, :, :]),
              "\nDataset max value:", np.max(values[index_to_use, :, :]))
    plt.contourf(lons, lats, values[index_to_use, :, :], levels, cmap=colormap)

    plt.gcf().subplots_adjust(left=0, right=1, top=1, bottom=0)
    plt.gca().axis("off")

    if filename != "":
        plt.savefig(filename, dpi=256, transparent=transparent)
for j in range(0,nelements):
    verts = [(xnode[i1[j]],ynode[i1[j]]),\
         (xnode[i2[j]],ynode[i2[j]]),\
         (xnode[i3[j]],ynode[i3[j]]),\
         (xnode[i1[j]],ynode[i1[j]]) ]
    path = Path(verts)
    patch = patches.PathPatch(path, facecolor='none',edgecolor='grey',lw=0.5)
    m.ax.add_patch(patch)

m.ax.set_xlim(lonmin,lonmax)
m.ax.set_ylim(latmin,latmax)
#m.drawcoastlines(ax=ax,color='black')
##m.drawparallels(np.arange(latmin,latmax,dlat), linewidth=0,
##                    labels=[1, 0, 0, 0], fontname='Times New Roman',fontsize=16)
##m.drawmeridians(np.arange(lonmin,lonmax,dlon), linewidth=0,
##                    labels=[0, 0, 1, 0], fontname='Times New Roman',fontsize=16)
##


m.warpimage(image='/home/ctroupin/Software/Python/backgrounds/land_ocean_ice_cloud_2048.jpg')
#m.etopo()
m.drawcountries()
#m.drawrivers()
#m.nightshade(date)  

plt.savefig(figdir+figname+figtype, dpi=300, facecolor='w', edgecolor='w',
         transparent=False, bbox_inches='tight', pad_inches=0.1)
#plt.show()
plt.close()
Example #45
0
def plot_lc_and_brights(path, bright_file, model_curve, data_curve, bb, Rp, nstripes, outfile, number):
    #Read in the values for model and data light curves
    model_time = []
    model_flux = []
    data_time_on = []
    data_flux_on = []
    data_time_off = []
    data_flux_off = []
    
    #Read in file
    temp = []
    for line in open(bright_file):                           
        temp.append(float(line))
    brights = np.array(temp)
   
    #Define latitudes of boxes
    lat1 = bb - Rp
    lat2 = bb + Rp

    for line in open(model_curve):                            
        new_array = line.split(' ')
        model_time.append(float(new_array[0]))
        model_flux.append(float(new_array[1]))
        
    for line in open(data_curve):                            
        new_array = line.split(' ')
        if float(new_array[0]) >= model_time[0] and float(new_array[0]) <= model_time[len(model_time) - 1]:
            data_time_on.append(float(new_array[0]))
            data_flux_on.append(float(new_array[1]))
        else:
            data_time_off.append(float(new_array[0]))
            data_flux_off.append(float(new_array[1]))
    
    #Create the plot and label it
    plt.plot(model_time, model_flux, c='black', label="Model")
    plt.scatter(data_time_on, data_flux_on, c='red', marker='+', label="Brightness Map Region")
    plt.scatter(data_time_off, data_flux_off, c='green', marker = '+', label="Data")
    minimum = min(data_flux_on + data_flux_off)
    maximum = max(data_flux_on + data_flux_off)
    diff = maximum - minimum
    plt.ylim(ymax=maximum + (diff * .85))
    plt.ylim(ymin=minimum - (diff * .1))
    plt.xlabel("Orbital Phase")
    plt.ylabel("Relative Flux")
    plt.title("Model Light Curve Vs. Data - Window %d" % number)

       #Set up arrays for brightnesses and positions
    nx = nstripes * 50
    ny = nstripes * 50
    bright_stripe = np.array(brights)
    img = np.zeros((nx,ny))
    idx1_stripe = np.arange(0, nstripes, 1.)/nstripes * nx
    idx2_stripe = (np.arange(0, nstripes, 1.) + 1)/nstripes * nx - 1

    #Populate the pixel values
    for jj in range(nstripes):
        idx1 = idx1_stripe[jj]
        idx2 = idx2_stripe[jj]
        idy1 = 0
        idy2 = ny-1
        img[idy1:idy2, idx1:idx2] = bright_stripe[jj]

    ax = plt.axes([.15, .6, .32, .32])
    plt.imsave(path + "/temp.png", img, cmap='hot', vmin=0.95, vmax=1.05)
    plt.imshow(img, cmap='hot')    
    plt.clim(0.95,1.05)
    plt.colorbar(shrink=0.5)    

    #Create the plot
    bmap = Basemap(projection='moll', lon_0 = 0)
    bmap.warpimage(path + "/temp.png")

    #Create the plots of the transits
    fig = plt.gcf()
    fig.set_size_inches(18.5,11.5)
    plt.savefig(path + "/" + outfile + ".png", dpi=120)
    plt.close()
Example #46
0
class Window(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        # Injected by the compile_and_import_ui_files() function.
        self.ui = qt_window.Ui_MainWindow()  # NOQA
        self.ui.setupUi(self)

        label = {"z": "vertical", "e": "east", "n": "north"}
        for component in ["z", "n", "e"]:
            p = getattr(self.ui, "%s_graph" % component)
            p.setLabel("left", "Displacement", units="m")
            p.setLabel("bottom", "Time since event", units="s")

            p.setTitle(label[component].capitalize() + " component")

        self.ui.n_graph.setXLink(self.ui.e_graph)
        self.ui.n_graph.setXLink(self.ui.z_graph)
        self.ui.e_graph.setXLink(self.ui.z_graph)
        self.ui.n_graph.setYLink(self.ui.e_graph)
        self.ui.n_graph.setYLink(self.ui.z_graph)
        self.ui.e_graph.setYLink(self.ui.z_graph)

        # Set some random mt at startup.
        m_rr = 4.71E17
        m_tt = 3.81E15
        m_pp = -4.74E17
        m_rt = 3.99E16
        m_rp = -8.05E16
        m_tp = -1.23E17
        self.ui.m_rr.setValue(m_rr)
        self.ui.m_tt.setValue(m_tt)
        self.ui.m_pp.setValue(m_pp)
        self.ui.m_rt.setValue(m_rt)
        self.ui.m_rp.setValue(m_rp)
        self.ui.m_tp.setValue(m_tp)

        self.instaseis_db = None
        self.finite_source = None
        self.st_copy = None

        self.plot_map()
        self.plot_mt()
        self.update()

    @property
    def focmec(self):
        if self.ui.source_tab.currentIndex() == 0:
            return [float(self.ui.m_rr.value()), float(self.ui.m_tt.value()),
                    float(self.ui.m_pp.value()), float(self.ui.m_rt.value()),
                    float(self.ui.m_rp.value()), float(self.ui.m_tp.value())]
        elif self.ui.source_tab.currentIndex() == 1:
            source = Source.from_strike_dip_rake(
                latitude=float(self.ui.source_latitude.value()),
                longitude=float(self.ui.source_longitude.value()),
                depth_in_m=float(self.source_depth) * 1000.0,
                strike=float(self.ui.strike_slider.value()),
                dip=float(self.ui.dip_slider.value()),
                rake=float(self.ui.rake_slider.value()),
                M0=1E16)
            return [source.m_rr, source.m_tt,
                    source.m_pp, source.m_rt,
                    source.m_rp, source.m_tp]

    def plot_mt(self):
        self.mpl_mt_figure = self.ui.mt_fig.fig
        self.mpl_mt_ax = self.mpl_mt_figure.add_axes([0.0, 0.0, 1.0, 1.0])
        self.mpl_mt_ax.set_axis_off()
        self.mpl_mt_figure.patch.set_alpha(0.0)
        self.mpl_mt_figure.set_facecolor('None')

        self._draw_mt()

    def _draw_mt(self):
        if not hasattr(self, "mpl_mt_ax"):
            return

        try:
            self.bb.remove()
        except:
            pass

        fm = self.focmec
        fm = [_i / 1e16 for _i in fm]
        self.bb = Beach(fm, xy=(0, 0), width=200, linewidth=1,
                        facecolor="red")
        self.mpl_mt_ax.add_collection(self.bb)
        self.mpl_mt_ax.set_xlim(-105, 105)
        self.mpl_mt_ax.set_ylim(-105, 105)
        self.mpl_mt_figure.canvas.draw()

    def plot_mt_finite(self):
        self.mpl_mt_finite_figure = self.ui.mt_fig_finite.fig
        self.mpl_mt_finite_ax = self.mpl_mt_finite_figure.add_axes(
            [0.0, 0.0, 1.0, 1.0])
        self.mpl_mt_finite_ax.set_axis_off()
        self.mpl_mt_finite_figure.patch.set_alpha(0.0)
        self.mpl_mt_finite_figure.set_facecolor('None')

        self._draw_mt_finite()

    def _draw_mt_finite(self):
        if not hasattr(self, "mpl_mt_finite_ax"):
            return

        try:
            self.bb_finite.remove()
        except:
            pass

        self.bb_finite = Beach(self.finite_source.CMT.tensor / 1e16,
                               xy=(0, 0), width=200, linewidth=1,
                               facecolor="red")
        self.mpl_mt_finite_ax.add_collection(self.bb_finite)
        self.mpl_mt_finite_ax.set_xlim(-105, 105)
        self.mpl_mt_finite_ax.set_ylim(-105, 105)
        self.mpl_mt_finite_figure.canvas.draw()

    def plot_cmt_sliprate(self):
        fig = self.ui.cmt_sliprate.fig
        fig.clf()
        fig.set_facecolor('white')
        ax = fig.add_axes([0.05, 0.2, 0.9, 0.8], frameon=False)
        ax.get_xaxis().tick_bottom()
        ax.axes.get_yaxis().set_visible(False)

        nsamp = len(self.finite_source.CMT.sliprate)
        time = np.linspace(0, self.finite_source.CMT.dt * nsamp, nsamp,
                           endpoint=False)

        ax.plot(time, self.finite_source.CMT.sliprate)
        ax.set_xlim(0., self.finite_source.rupture_duration * 2.)
        fig.canvas.draw()

    def plot_map(self):
        self.mpl_map_figure = self.ui.map_fig.fig

        # if hasattr(self, 'mpl_map_ax'):
        #     self.mpl_map_ax.clear()

        self.mpl_map_ax = self.mpl_map_figure.add_axes([0.01, 0.01, .98, .98])
        self.mpl_map_ax.set_title("Left click: Set Receiver; Right click: Set "
                                  "Source")

        self.map = Basemap(projection='moll', lon_0=0, resolution="c",
                           ax=self.mpl_map_ax)

        self.map.drawmapboundary(fill_color='#cccccc')
        if self.instaseis_db and self.instaseis_db.info.planet_radius < 5e6:
            imfile = os.path.join(DATA, 'mola_texture_shifted_800.jpg')
            self.map.warpimage(image=imfile, zorder=0)
        else:
            self.map.fillcontinents(color='white', lake_color='#cccccc',
                                    zorder=0)

        self.mpl_map_figure.patch.set_alpha(0.0)

        self.mpl_map_figure.canvas.mpl_connect(
            'button_press_event', self._on_map_mouse_click_event)
        self.mpl_map_figure.canvas.draw()

    def _on_map_mouse_click_event(self, event):
        if None in (event.xdata, event.ydata):
            return
        # Get map coordinates by the inverse transform.
        lng, lat = self.map(event.xdata, event.ydata, inverse=True)
        # Left click: set receiver
        if event.button == 1:
            self.ui.receiver_longitude.setValue(lng)
            self.ui.receiver_latitude.setValue(lat)
        # Right click: set event
        elif (event.button == 3 and self.ui.finsource_tab.currentIndex() == 0):
            self.ui.source_longitude.setValue(lng)
            self.ui.source_latitude.setValue(lat)

    def _plot_event(self):
        if self.ui.finsource_tab.currentIndex() == 0:
            s = self.source
            lng, lat = s.longitude, s.latitude
        elif self.ui.finsource_tab.currentIndex() == 1:
            s = self.finite_source
            s.find_hypocenter()
            lng, lat = s.hypocenter_longitude, s.hypocenter_latitude

        try:
            if self.__event_map_obj.longitude == lng and \
                    self.__event_map_obj.latitude == lat:
                return
        except AttributeError:
            pass

        try:
            self.__event_map_obj.remove()
        except AttributeError:
            pass

        x1, y1 = self.map(lng, lat)
        self.__event_map_obj = self.map.scatter(x1, y1, s=300, zorder=10,
                                                color="yellow", marker="*",
                                                edgecolor="k")
        self.__event_map_obj.longitude = lng
        self.__event_map_obj.latitude = lat
        self.mpl_map_figure.canvas.draw()

    def _plot_receiver(self):
        r = self.receiver
        lng, lat = r.longitude, r.latitude
        try:
            if self.__receiver_map_obj.longitude == lng and \
                    self.__receiver_map_obj.latitude == lat:
                return
        except AttributeError:
            pass

        try:
            self.__receiver_map_obj.remove()
        except AttributeError:
            pass

        x1, y1 = self.map(lng, lat)
        self.__receiver_map_obj = self.map.scatter(x1, y1, s=170, zorder=10,
                                                   color="red", marker="v",
                                                   edgecolor="k")
        self.__receiver_map_obj.longitude = lng
        self.__receiver_map_obj.latitude = lat
        self.mpl_map_figure.canvas.draw()

    def _plot_bg_receivers(self):
        try:
            self.__bg_receivers_map_obj.remove()
        except AttributeError:
            pass

        xl = []
        yl = []
        for r in self.receivers:
            lng, lat = r.longitude, r.latitude
            x1, y1 = self.map(lng, lat)
            xl.append(x1)
            yl.append(y1)

        self.__bg_receivers_map_obj = self.map.scatter(
            xl, yl, s=100, zorder=5, color="k", marker="v",
            edgecolor="gray", alpha=0.3)
        self.mpl_map_figure.canvas.draw()

    @property
    def source(self):
        fm = self.focmec
        return Source(
            latitude=float(self.ui.source_latitude.value()),
            longitude=float(self.ui.source_longitude.value()),
            depth_in_m=float(self.source_depth) * 1000.0, m_rr=fm[0],
            m_tt=fm[1], m_pp=fm[2], m_rt=fm[3], m_rp=fm[4],
            m_tp=fm[5])

    @property
    def receiver(self):
        return Receiver(
            latitude=float(self.ui.receiver_latitude.value()),
            longitude=float(self.ui.receiver_longitude.value()))

    def update(self, force=False):

        try:
            self._plot_receiver()
            self._plot_event()
        except AttributeError:
            return

        if (not bool(self.ui.auto_update_check_box.checkState()) and
                self.ui.finsource_tab.currentIndex() == 1 and not force and
                self.st_copy is None):
            return

        components = ["z", "n", "e"]
        components_map = {0: ("Z", "N", "E"),
                          1: ("Z", "R", "T")}

        components_choice = int(self.ui.components_combo.currentIndex())

        label_map = {0: {"z": "vertical", "n": "north", "e": "east"},
                     1: {"z": "vertical", "n": "radial", "e": "transverse"}}

        for component in components:
            p = getattr(self.ui, "%s_graph" % component)
            p.setTitle(label_map[components_choice][component].capitalize() +
                       " component")

        if self.ui.finsource_tab.currentIndex() == 0:
            src_latitude = self.source.latitude
            src_longitude = self.source.longitude
            src_depth_in_m = self.source.depth_in_m
        else:
            src_latitude = self.finite_source.hypocenter_latitude
            src_longitude = self.finite_source.hypocenter_longitude
            src_depth_in_m = self.finite_source.hypocenter_depth_in_m

        rec = self.receiver
        try:
            # Grab resampling settings from the UI.
            if bool(self.ui.resample_check_box.checkState()):
                dt = float(self.ui.resample_factor.value())
                dt = self.instaseis_db.info.dt / dt
            else:
                dt = None
            if self.ui.finsource_tab.currentIndex() == 0:
                st = self.instaseis_db.get_seismograms(
                    source=self.source, receiver=self.receiver, dt=dt,
                    components=components_map[components_choice])
            elif (not bool(self.ui.auto_update_check_box.checkState()) and
                    self.ui.finsource_tab.currentIndex() == 1 and
                    not force):
                st = self.st_copy.copy()
            else:
                prog_diag = QtGui.QProgressDialog(
                    "Calculating", "Cancel", 0, len(self.finite_source), self)
                prog_diag.setWindowModality(QtCore.Qt.WindowModal)
                prog_diag.setMinimumDuration(0)

                def get_prog_fct():
                    def set_value(value, count):
                        prog_diag.setValue(value)
                        if prog_diag.wasCanceled():
                            return True
                    return set_value

                prog_diag.setValue(0)
                st = self.instaseis_db.get_seismograms_finite_source(
                    sources=self.finite_source, receiver=self.receiver, dt=dt,
                    components=('Z', 'N', 'E'),
                    progress_callback=get_prog_fct())
                prog_diag.setValue(len(self.finite_source))
                if not st:
                    return

                baz = geodetics.gps2DistAzimuth(
                    self.finite_source.CMT.latitude,
                    self.finite_source.CMT.longitude,
                    rec.latitude, rec.longitude)[2]
                self.st_copy = st.copy()
                st.rotate('NE->RT', baz)
                st += self.st_copy
                self.st_copy = st.copy()

            if self.ui.finsource_tab.currentIndex() == 1 \
                    and bool(self.ui.plot_CMT_check_box.checkState()):
                st_cmt = self.instaseis_db.get_seismograms(
                    source=self.finite_source.CMT, receiver=self.receiver,
                    dt=dt, components=components_map[components_choice],
                    reconvolve_stf=True)
            else:
                st_cmt = None

            # check filter values from the UI
            zp = bool(self.ui.zero_phase_check_box.checkState())
            if bool(self.ui.lowpass_check_box.checkState()):
                try:
                    freq = 1.0 / float(self.ui.lowpass_period.value())
                    st.filter('lowpass', freq=freq, zerophase=zp)
                    if st_cmt is not None:
                        st_cmt.filter('lowpass', freq=freq, zerophase=zp)
                except ZeroDivisionError:
                    # this happens when typing in the lowpass_period box
                    pass

            if bool(self.ui.highpass_check_box.checkState()):
                try:
                    freq = 1.0 / float(self.ui.highpass_period.value())
                    st.filter('highpass', freq=freq, zerophase=zp)
                    if st_cmt is not None:
                        st_cmt.filter('highpass', freq=freq, zerophase=zp)
                except ZeroDivisionError:
                    # this happens when typing in the highpass_period box
                    pass

        except AttributeError:
            return

        if bool(self.ui.tt_times.checkState()):
            great_circle_distance = geodetics.locations2degrees(
                src_latitude, src_longitude,
                rec.latitude, rec.longitude)
            self.tts = tau_model.get_travel_times(
                source_depth_in_km=src_depth_in_m / 1000.0,
                distance_in_degree=great_circle_distance)

        for ic, component in enumerate(components):
            plot_widget = getattr(self.ui, "%s_graph" % component.lower())
            plot_widget.clear()
            tr = st.select(component=components_map[components_choice][ic])[0]
            times = tr.times()
            plot_widget.plot(times, tr.data, pen="k")
            plot_widget.ptp = tr.data.ptp()
            if st_cmt is not None:
                tr = st_cmt.select(
                    component=components_map[components_choice][ic])[0]
                times = tr.times()
                plot_widget.plot(times, tr.data, pen="r")

            if bool(self.ui.tt_times.checkState()):
                tts = []
                for tt in self.tts:
                    if tt.time >= times[-1]:
                        continue
                    tts.append(tt)
                    if tt.name[0].lower() == "p":
                        pen = "#008c2866"
                    else:
                        pen = "#95000066"
                    plot_widget.addLine(x=tt.time, pen=pen, z=-10)
                self.tts = tts
        self.set_info()

    def on_select_folder_button_released(self):
        pwd = os.getcwd()
        self.folder = str(QtGui.QFileDialog.getExistingDirectory(
            self, "Choose Directory", pwd))
        if not self.folder:
            return
        self.instaseis_db = open_db(self.folder)

        # Adjust depth slider to the DB.
        max_rad = self.instaseis_db.info.max_radius / 1E3
        min_rad = self.instaseis_db.info.min_radius / 1E3
        self.ui.depth_slider.setMinimum(min_rad - max_rad)
        self.ui.depth_slider.setMaximum(0)

        self._setup_finite_source()

        self.plot_map()
        self.update()
        self.set_info()

    def on_select_remote_connection_button_released(self):
        text, ok = QtGui.QInputDialog.getText(
            self, "Remote Instaseis Connection",
            "Enter URL to remote Instaseis Server:")
        if not ok:
            return
        text = str(text)

        self.instaseis_db = open_db(text)

        # Adjust depth slider to the DB.
        max_rad = self.instaseis_db.info.max_radius / 1E3
        min_rad = self.instaseis_db.info.min_radius / 1E3
        self.ui.depth_slider.setMinimum(min_rad - max_rad)
        self.ui.depth_slider.setMaximum(0)

        self._setup_finite_source()

        self.plot_map()
        self.update()
        self.set_info()

    def on_open_srf_file_button_released(self):
        pwd = os.getcwd()
        self.finite_src_file = str(QtGui.QFileDialog.getOpenFileName(
            self, "Choose *.srf or *.param File", pwd,
            "Standard Rupture Format (*.srf);;"
            "USGS finite source files (*.param)"))
        if not self.finite_src_file:
            return
        if self.finite_src_file.endswith('.srf'):
            self.finite_source = FiniteSource.from_srf_file(
                self.finite_src_file, normalize=True)
        elif self.finite_src_file.endswith('.param'):
            self.finite_source = FiniteSource.from_usgs_param_file(
                self.finite_src_file)
        else:
            raise IOError('unknown file type *.%s' %
                          self.finite_src_file.split('.')[-1])

        self._setup_finite_source()
        self.update()
        self.set_info()

    def _setup_finite_source(self):
        if self.finite_source is None:
            return
        if self.instaseis_db is not None:
            # this is a super uggly construction: if you open a different DB,
            # it will not use the original finite source, but the one already
            # messed up for the previously used DB. Not fixing it here, but in
            # the new GUI we should.

            # self.finite_source.set_sliprate_lp(
            #     dt=self.instaseis_db.info.dt,
            # nsamp=self.instaseis_db.info.npts,
            #     freq=1.0/self.instaseis_db.info.period)

            nsamp = int(self.instaseis_db.info.period /
                        self.finite_source[0].dt) * 50
            self.finite_source.resample_sliprate(
                dt=self.finite_source[0].dt, nsamp=nsamp)
            self.finite_source.lp_sliprate(
                freq=1.0/self.instaseis_db.info.period)
            self.finite_source.resample_sliprate(
                dt=self.instaseis_db.info.dt,
                nsamp=self.instaseis_db.info.npts)

        self.finite_source.compute_centroid()
        self.plot_mt_finite()
        self.plot_cmt_sliprate()

    def set_info(self):
        info_str = ''
        if self.finite_source is not None:
            info_str += str(self.finite_source) + '\n'
        else:
            info_str += str(self.source) + '\n'
        if self.instaseis_db is not None:
            info_str += str(self.instaseis_db) + '\n'
        self.ui.info_text.setText(info_str)

    def on_load_source_button_released(self):
        pwd = os.getcwd()
        self.source_file = str(QtGui.QFileDialog.getOpenFileName(
            self, "Choose Source File", pwd))
        if not self.source_file:
            return

        s = Source.parse(self.source_file)
        self.ui.m_rr.setValue(s.m_rr)
        self.ui.m_pp.setValue(s.m_pp)
        self.ui.m_rp.setValue(s.m_rp)
        self.ui.m_tt.setValue(s.m_tt)
        self.ui.m_rt.setValue(s.m_rt)
        self.ui.m_tp.setValue(s.m_tp)

        self.ui.source_longitude.setValue(s.longitude)
        self.ui.source_latitude.setValue(s.latitude)
        self.ui.depth_slider.setValue(- s.depth_in_m / 1e3)
        self.set_info()

    def on_source_latitude_valueChanged(self, *args):
        self.update()

    def on_source_longitude_valueChanged(self, *args):
        self.update()

    def on_receiver_latitude_valueChanged(self, *args):
        self.update()

    def on_receiver_longitude_valueChanged(self, *args):
        self.update()

    def on_m_rr_valueChanged(self, *args):
        self._draw_mt()
        self.update()

    def on_m_tt_valueChanged(self, *args):
        self._draw_mt()
        self.update()

    def on_m_pp_valueChanged(self, *args):
        self._draw_mt()
        self.update()

    def on_m_rt_valueChanged(self, *args):
        self._draw_mt()
        self.update()

    def on_m_rp_valueChanged(self, *args):
        self._draw_mt()
        self.update()

    def on_m_tp_valueChanged(self, *args):
        self._draw_mt()
        self.update()

    @property
    def source_depth(self):
        value = int(-1.0 * int(self.ui.depth_slider.value()))
        return value

    def on_depth_slider_valueChanged(self, *args):
        self.ui.depth_label.setText("Depth: %i km" % self.source_depth)
        self.update()

    def on_strike_slider_valueChanged(self, *args):
        self.ui.strike_value.setText("%i" % self.ui.strike_slider.value())
        self._draw_mt()
        self.update()

    def on_dip_slider_valueChanged(self, *args):
        self.ui.dip_value.setText("%i" % self.ui.dip_slider.value())
        self._draw_mt()
        self.update()

    def on_rake_slider_valueChanged(self, *args):
        self.ui.rake_value.setText("%i" % self.ui.rake_slider.value())
        self._draw_mt()
        self.update()

    def autoRange(self):
        widgets = [getattr(self.ui, "%s_graph" % _i)
                   for _i in ("z", "n", "e")]
        widgets.sort(key=lambda x: x.ptp)
        widgets[-1].autoRange()

    def on_reset_view_button_released(self, *args):
        self.autoRange()

    def on_resample_check_box_stateChanged(self, state):
        resample = bool(state)
        self.ui.resample_factor.setEnabled(resample)
        self.ui.sr_ref_label.setEnabled(resample)
        self.update()

    def on_resample_factor_valueChanged(self, *args):
        self.update()

    def on_tt_times_stateChanged(self, state):
        self.update()

    def on_lowpass_check_box_stateChanged(self, state):
        resample = bool(state)
        self.ui.lowpass_period.setEnabled(resample)
        self.ui.lowpass_label.setEnabled(resample)
        self.update()

    def on_lowpass_period_valueChanged(self, *args):
        self.update()

    def on_highpass_check_box_stateChanged(self, state):
        resample = bool(state)
        self.ui.highpass_period.setEnabled(resample)
        self.ui.highpass_label.setEnabled(resample)
        self.update()

    def on_highpass_period_valueChanged(self, *args):
        self.update()

    def on_zero_phase_check_box_stateChanged(self, state):
        self.update()

    def on_components_combo_currentIndexChanged(self):
        self.update()

    def on_finsource_tab_currentChanged(self):
        self.update()

    def on_source_tab_currentChanged(self):
        self._draw_mt()
        self.update()
        self.autoRange()

    def on_update_button_released(self):
        self.update(force=True)

    def on_load_stations_button_released(self):
        pwd = os.getcwd()
        self.stations_file = str(QtGui.QFileDialog.getOpenFileName(
            self, "Choose Stations File", pwd))
        if not self.stations_file:
            return

        self.receivers = Receiver.parse(self.stations_file)
        recnames = []
        for _r in self.receivers:
            recnames.append('%s.%s' % (_r.network, _r.station))

        self.ui.stations_combo.clear()
        self.ui.stations_combo.addItems(recnames)

        self._plot_bg_receivers()

    def on_stations_combo_currentIndexChanged(self):
        idx = self.ui.stations_combo.currentIndex()
        self.ui.receiver_longitude.setValue(self.receivers[idx].longitude)
        self.ui.receiver_latitude.setValue(self.receivers[idx].latitude)

    def eventFilter(self, source, event):
        if event.type() == QtCore.QEvent.MouseMove:
            if source.parent() in [self.ui.z_graph, self.ui.n_graph,
                                   self.ui.e_graph] \
                    and event.buttons() == QtCore.Qt.NoButton:
                try:
                    tt = float(self.ui.z_graph.mapToView(
                        pg.Point(event.pos().x(), event.pos().y())).x())
                    closest_phase = \
                        min(self.tts, key=lambda x: abs(x.time - tt))
                    tooltipstr = 'Mouse at %6.2f s, closest phase = %s, ' \
                        'arriving at %6.2f s' % \
                        (tt, closest_phase.name, closest_phase.time)
                except:
                    tooltipstr = ''

                self.ui.z_graph.setToolTip(tooltipstr)
                self.ui.n_graph.setToolTip(tooltipstr)
                self.ui.e_graph.setToolTip(tooltipstr)

        return QtGui.QMainWindow.eventFilter(self, source, event)
Example #47
0
         (xnode[i1[j]],ynode[i1[j]]) ]
    path = Path(verts)
    patch = patches.PathPatch(path, facecolor='none', edgecolor='grey', lw=0.5)
    m.ax.add_patch(patch)

m.ax.set_xlim(lonmin, lonmax)
m.ax.set_ylim(latmin, latmax)
#m.drawcoastlines(ax=ax,color='black')
##m.drawparallels(np.arange(latmin,latmax,dlat), linewidth=0,
##                    labels=[1, 0, 0, 0], fontname='Times New Roman',fontsize=16)
##m.drawmeridians(np.arange(lonmin,lonmax,dlon), linewidth=0,
##                    labels=[0, 0, 1, 0], fontname='Times New Roman',fontsize=16)
##

m.warpimage(
    image=
    '/home/ctroupin/Software/Python/backgrounds/land_ocean_ice_cloud_2048.jpg')
#m.etopo()
m.drawcountries()
#m.drawrivers()
#m.nightshade(date)

plt.savefig(figdir + figname + figtype,
            dpi=300,
            facecolor='w',
            edgecolor='w',
            transparent=False,
            bbox_inches='tight',
            pad_inches=0.1)
#plt.show()
plt.close()
Example #48
0
def plotxy(ifile='grid_search_xy_out',xyzfile='grid_search_xyz_out',ofile='grid_search_xy.pdf',basemapflag=False,mksmin=1.,
        mksmax=30.,delta=XY_NX*XY_DX,resolution = 'h'):
    # Initialize variables
    rms  = []
    lon  = []
    lat  = []
    flag = False
    # Read file grid search XYZ
    # WARNING :: PDE from XYZ is the initial epicenter 
    if os.path.exists(xyzfile):
        latopt,lonopt,depopt,rmsopt,ilatpde,ilonpde,deppde,rmspde,lats,lons,deps,rmss,depths,rmsdep = rxyzgfile(xyzfile)
    # Read file grid search XY
    # WARNING :: PDE from XY is the solution of grid search in Z 
    latopt,lonopt,depopt,rmsopt,latpde,lonpde,rmspde,lat,lon,rms = r_xy_gfile(ifile) 
    if not os.path.exists(xyzfile):
        ilatpde=latpde
        ilonpde=lonpde
    # RMS Scale
    minrms = rmsopt    
    nrms = rms/minrms*100.
    maxrms = max(rms)/minrms*100.
    minrms = 100.
    plt.figure(figsize=(9.6125,  8.1))
    ax1 = plt.axes([0.04,0.13,0.8,0.85])
    ax2 = plt.axes([0.85,0.35,0.1,0.6])
    cm = plt.get_cmap('jet')
    for i in range(8):
        Bpos   = interp(i,8,0.,1.)
        Brms=interp(i,8,minrms,maxrms)
        mksize = ((Brms-minrms)/(maxrms-minrms))*(mksmax-mksmin)+mksmin
        plt.plot([0.5],[Bpos],'ko',ms=mksize,markerfacecolor=cm((Brms-minrms)/(maxrms-minrms)))
        plt.text(0.9,Bpos-0.02,'%7.1f'%Brms)
    ax2.set_axis_off()
    mksize = ((np.array(nrms)-minrms)/(maxrms-minrms))*(mksmax-mksmin)+mksmin    
    plt.ylim(-0.1,1.1)
    plt.xlim(0,1.6)
    plt.title('Normalized RMS')
    # DISPLAY MAP
    plt.axes(ax1)        
    if basemapflag:
        try:
            from mpl_toolkits.basemap import Basemap
        except:
            print('WARNING: No module named basemap')
            print('   The mpl_toolkits.basemap module is necessary')
            print('   if you want to plot bathymetry and coastlines')
            basemapflag = False
    if basemapflag:
        wraplons(lon)
        deltalon = delta/np.cos(np.pi*latpde/180.0)
        latll = lat.min() - delta ; latur = lat.max() + delta ;
        lonll = lon.min() - deltalon ; lonur = lon.max() + deltalon ;        
        # Basemap instance
        m = Basemap(projection='merc',llcrnrlon=lonll,llcrnrlat=latll,urcrnrlon=lonur,
                urcrnrlat=latur,resolution=resolution)
        # Bathymetry        
        ETOPO_file = os.path.expandvars('$ETOPOFILE')
        if os.path.exists(ETOPO_file):
            try:
                plot_etopo(ETOPO_file,m,ax1)
                etopoflag=True
            except:
                etopoflag=False
                print('WARNING: error encountered while plotting ETOPO')
                print('         Will not display topography/bathymetry')
        else:
            etopoflag=False
            if ETOPO_file[0]=='$':
                print('WARNING: Undefined environment variable $ETOPOFILE')
            else:
                print('WARNING: ETOPOFILE=%s does not exists'%(ETOPO_file))
                print('         Will not display topography/bathymetry')
        # Coastlines/meridians/paralells
        plt.axes(ax1)
        m.drawcoastlines(linewidth=0.5)
        m.drawmeridians(np.arange(float(int(lonll)),lonur+delta,delta),labels=[0,0,0,1],
                dashes=[1,1],linewidth=0.5,color='k')
        m.drawparallels(np.arange(float(int(latll)),latur+delta,delta),labels=[1,0,0,0],
                dashes=[1,1],linewidth=0.5,color='k')
        if not etopoflag:
            try:
                BLUEMARBLE_file = os.path.expandvars('$BLUEMARBLEFILE')
                if os.path.exists(BLUEMARBLE_file):
                    m.warpimage(image=BLUEMARBLE_file)
                else:
                    if BLUEMARBLE_file[0]=='$':
                        print('WARNING: Undefined environment variable $BLUEMARBLEFILE')
                    else:
                        print('WARNING: BLUEMARBLEFILE=%s does not exists'%(BLUEMARBLE_file))
                        print('         Will not display topography/bathymetry')
            except:
                print('WARNING: error encountered while plotting background bluemarbe image')
                print('         Will not display topography/bathymetry')
                pass
            m.fillcontinents(color='0.65', lake_color='white')
        m.drawcountries(linewidth=0.3, color='k')
        # RMS misfit
        for la,lo,err,siz in zip(lat,lon,nrms,mksize):
            x,y = m(lo,la)
            col = cm((err-minrms)/(maxrms-minrms))        
            m.plot([x],[y],c=col,marker='o',ms=siz)
        l = [ilonpde,lonopt]
        wraplons(l)
        xpde,ypde = m(l[0],ilatpde)
        xopt,yopt = m(l[1],latopt)
        m.plot([xpde],[ypde],'rv',ms=14,alpha=0.7,label='Initial PDE')
        m.plot([xopt],[yopt],'g*',ms=18,mew=1.2,alpha=0.7,label='W-Phase Centroid')
        leg = plt.legend(loc='lower center',prop={'size': 12},numpoints=1, scatterpoints=1, \
                             bbox_to_anchor=(0.5, 0.01),ncol=2, shadow=True, fancybox=True)
        leg.get_frame().set_alpha(0.6)
    else:
        deltalon = delta/np.cos(np.pi*latpde/180.0)
        latll = lat.min() - delta ; latur = lat.max() + delta ;
        lonll = lon.min() - deltalon ; lonur = lon.max() + deltalon ;
        for la,lo,err,siz in zip(lat,lon,nrms,mksize):
            col = cm((err-minrms)/(maxrms-minrms))        
            plt.plot([lo],[la],c=col,marker='o',ms=siz)
        plt.plot([lonpde],[latpde],'k+',ms=14,mew=2.5,alpha=0.7)
        plt.plot([lonopt],[latopt],'rv',ms=14,alpha=0.7)
        plt.xlim([lonll,lonur])
        plt.ylim([latll,latur])
    plt.savefig(ofile)
    # All done
    return;
Example #49
0
from __future__ import (absolute_import, division, print_function)

from mpl_toolkits.basemap import Basemap
import numpy as np
import matplotlib.pyplot as plt

# illustrate use of warpimage method to display an image background
# on the map projection region.  Default background is the 'blue
# marble' image from NASA (http://visibleearth.nasa.gov).

# create new figure
fig=plt.figure()
# define orthographic projection centered on North America.
m = Basemap(projection='ortho',lat_0=40,lon_0=-100,resolution='l')
# display a non-default image.
m.warpimage(image='earth_lights_lrg.jpg')
# draw coastlines.
m.drawcoastlines(linewidth=0.5,color='0.5')
# draw lat/lon grid lines every 30 degrees.
m.drawmeridians(np.arange(0,360,30),color='0.5')
m.drawparallels(np.arange(-90,90,30),color='0.5')
plt.title("Lights at Night image warped from 'cyl' to 'ortho' projection",fontsize=12)
print('warp to orthographic map ...')

# create new figure
fig=plt.figure()
# define projection centered on North America.
m = Basemap(projection='mbtfpq',lon_0=-100,resolution='l')
m.bluemarble(scale=0.5)
# draw coastlines.
m.drawcoastlines(linewidth=0.5,color='0.5')
Example #50
0
def define_proj (char,wlon,wlat,back=None,blat=None,blon=None):
    from    mpl_toolkits.basemap            import Basemap
    import  numpy                           as np
    import  matplotlib                      as mpl
    meanlon = 0.5*(wlon[0]+wlon[1])
    meanlat = 0.5*(wlat[0]+wlat[1])
    zewidth = np.abs(wlon[0]-wlon[1])*60000.*np.cos(3.14*meanlat/180.)
    zeheight = np.abs(wlat[0]-wlat[1])*60000.
    if blat is None:
        ortholat=meanlat
        if   wlat[0] >= 80.:   blat =  -40. 
        elif wlat[1] <= -80.:  blat = -40.
        elif wlat[1] >= 0.:    blat = wlat[0] 
        elif wlat[0] <= 0.:    blat = wlat[1]
    else:  ortholat=blat
    if blon is None:  ortholon=meanlon
    else:             ortholon=blon
    h = 50.  ## en km
    radius = 3397200.
    if   char == "cyl":     m = Basemap(rsphere=radius,projection='cyl',\
                              llcrnrlat=wlat[0],urcrnrlat=wlat[1],llcrnrlon=wlon[0],urcrnrlon=wlon[1])
    elif char == "moll":    m = Basemap(rsphere=radius,projection='moll',lon_0=meanlon)
    elif char == "ortho":   m = Basemap(rsphere=radius,projection='ortho',lon_0=ortholon,lat_0=ortholat)
    elif char == "lcc":     m = Basemap(rsphere=radius,projection='lcc',lat_1=meanlat,lat_0=meanlat,lon_0=meanlon,\
                              width=zewidth,height=zeheight)
                              #llcrnrlat=wlat[0],urcrnrlat=wlat[1],llcrnrlon=wlon[0],urcrnrlon=wlon[1])
    elif char == "npstere": m = Basemap(rsphere=radius,projection='npstere', boundinglat=blat, lon_0=0.)
    elif char == "spstere": m = Basemap(rsphere=radius,projection='spstere', boundinglat=blat, lon_0=180.)
    elif char == "nplaea":  m = Basemap(rsphere=radius,projection='nplaea', boundinglat=wlat[0], lon_0=meanlon)
    elif char == "laea":    m = Basemap(rsphere=radius,projection='laea',lon_0=meanlon,lat_0=meanlat,lat_ts=meanlat,\
                              width=zewidth,height=zeheight)
                              #llcrnrlat=wlat[0],urcrnrlat=wlat[1],llcrnrlon=wlon[0],urcrnrlon=wlon[1])
    elif char == "nsper":   m = Basemap(rsphere=radius,projection='nsper',lon_0=meanlon,lat_0=meanlat,satellite_height=h*1000.)
    elif char == "merc":    m = Basemap(rsphere=radius,projection='merc',lat_ts=0.,\
                              llcrnrlat=wlat[0],urcrnrlat=wlat[1],llcrnrlon=wlon[0],urcrnrlon=wlon[1])
    elif char == "geos":    m = Basemap(rsphere=radius,projection='geos',lon_0=meanlon)
    elif char == "robin":   m = Basemap(rsphere=radius,projection='robin',lon_0=0)
    elif char == "cass":    
             if zewidth > 60000.:  ## approx. more than one degree
                m = Basemap(rsphere=radius,projection='cass',\
                              lon_0=meanlon,lat_0=meanlat,\
                              width=zewidth,height=zeheight)
             else:
                m = Basemap(rsphere=radius,projection='cass',\
                              lon_0=meanlon,lat_0=meanlat,\
                              llcrnrlat=wlat[0],urcrnrlat=wlat[1],llcrnrlon=wlon[0],urcrnrlon=wlon[1])
    else:                   errormess("projection not supported.")
    fontsizemer = int(mpl.rcParams['font.size']*3./4.)
    if zewidth > 60000.:
        if char in ["cyl","lcc","merc","nsper","laea"]:   step = findstep(wlon)
        else:                                             step = 10.
        steplon = step*2.
    else:
        print "very small domain !"
        steplon = 0.5
        step = 0.5
    zecolor ='grey'
    zelinewidth = 1
    zelatmax = 80.
    if meanlat > 75.:  zelatmax = 90. ; step = step/2. ; steplon = steplon*2.
#    # to show gcm grid:
#    #zecolor = 'r'
#    #zelinewidth = 1
#    #step = 180./48.
#    #steplon = 360./64.
#    #zelatmax = 90. - step/3
#    if char not in ["moll","robin"]:
#        if wlon[1]-wlon[0] < 2.:  ## LOCAL MODE
#            m.drawmeridians(np.r_[-1.:1.:0.05], labels=[0,0,0,1], color=zecolor, linewidth=zelinewidth, fontsize=fontsizemer, fmt='%5.2f')
#            m.drawparallels(np.r_[-1.:1.:0.05], labels=[1,0,0,0], color=zecolor, linewidth=zelinewidth, fontsize=fontsizemer, fmt='%5.2f')
#        else:  ## GLOBAL OR REGIONAL MODE
#            m.drawmeridians(np.r_[-180.:180.:steplon], labels=[0,0,0,1], color=zecolor, linewidth=zelinewidth, fontsize=fontsizemer, latmax=zelatmax)
#            m.drawparallels(np.r_[-90.:90.:step], labels=[1,0,0,0], color=zecolor, linewidth=zelinewidth, fontsize=fontsizemer, latmax=zelatmax)
    if back is not None: 
      if back not in ["coast","sea"]:   m.warpimage(marsmap(back),scale=0.75)
      elif back == "coast":             m.drawcoastlines()
      elif back == "sea":               m.drawlsmask(land_color='white',ocean_color='aqua')
            #if not back:
            #    if not var:                                        back = "mola"    ## if no var:         draw mola
            #    elif typefile in ['mesoapi','meso','geo'] \
            #       and proj not in ['merc','lcc','nsper','laea']:  back = "molabw"  ## if var but meso:   draw molabw
            #    else:                                              pass             ## else:              draw None
    return m