Beispiel #1
0
class Carmap:
    '''
    making a map with basemap
    install basemap: http://gnperdue.github.io/yak-shaving/osx/python/matplotlib/2014/05/01/basemap-toolkit.html
    '''

    def __init__(self):

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


    def plot(self, lon, lat, color):
        '''
        making plot at the map
        :param color: which color of the dot
        '''
        lon, lat = lon, lat # Location of Boulder
        # convert to map projection coords.
        # Note that lon,lat can be scalars, lists or numpy arrays.
        xpt, ypt = self.m(lon, lat)
        self.m.plot(xpt, ypt, color)    # plot a color dot there

    def show(self):
        self.m.bluemarble()  # map style
        plt.show()
def plotme(lats,lons,contries,ymds):
	# Making the plot fullscreen
	fig = plt.figure(figsize=(20,9))
	fig.patch.set_facecolor('k')

	map = Basemap(projection='ortho', lat_0 = -90 , lon_0 = 0 ,resolution = 'l')

	# Make the globe more realistic
	map.bluemarble()

	#draw the edge of the map projection region (the projection limb)
	#map.drawmapboundary()
	#map.drawcountries()
	#map.drawstates()

	# draw lat/lon grid lines every 30 degrees.
	#map.drawmeridians(np.arange(0, 360, 30))
	#map.drawparallels(np.arange(-90, 90, 30))


	#CS = map.nightshade(ymds)

	# compute the native map projection coordinates for contries.
	x,y = map(lons,lats)

	# plot circle.
	map.plot(x,y,'rx', ms=10, mew=5)



	plt.show()
def drawMap(report):
	entries = get_site_status(report)
#	entries = {'unl.edu': [276, 0, 246, 0], 'desy.de': [107, 0, 0, 0], 'fnal.gov': [16, 0, 294, 0], 'N/A': [0, 0, 0, 0]}
	posList = get_positions(entries)

	#bounds = [(-60, -120), (60, 120)]
	#bounds = [(30, -10), (60, 40)]
	bounds = get_bounds(posList, margin = 10)

	matplotlib.pyplot.subplots_adjust(left=0, right=1, top=1, bottom=0, wspace=0, hspace=0)
	fig = matplotlib.pyplot.figure(figsize=(12, 6))
	ax = matplotlib.pyplot.subplot(111)
	m = Basemap(projection='cyl', lat_0=0, lon_0=0,
		llcrnrlon=bounds[0][0], llcrnrlat=bounds[0][1],
		urcrnrlon=bounds[1][0], urcrnrlat=bounds[1][1])

	map_positions(m, posList)
	#posList = remove_all_overlap(posList)
	#print posList

	m.bluemarble()
	for pos in posList:
		draw_pie(ax, pos['info'], (pos['x'], pos['y']), pos['size'])
		ax.text(pos['x']+5, pos['y']+5, pos['site'], color='white', fontsize=8)
	fig.savefig(os.path.expanduser('~/map.png'), dpi=300)
Beispiel #4
0
class MapDrawer:
    
    mymap = None;
    projection = 'hammer';
    
    def __init__(self, projection = 'hammer', lon_0 = 0, resolution = 'c'):
        self.mymap = Basemap(projection, lon_0, resolution);
        self.mymap.bluemarble()
    
    def show_map(self):
        self.mymap.show();
        
    def draw_markers(self, lats, longs, title = '', clever_mode = 0):
        
        # draw parallels and meridians.
        lats = np.array(lats)
        longs = np.array(longs)
        if clever_mode:
            print "Clever mode is under construction" 
        xpt,ypt = self.mymap(longs,lats)
        print xpt;
        self.mymap.plot(xpt, ypt, 'ro')
        if title:
            plt.title('Tweets about ' + title) 
            plt.show()        
        
        #mymap = Basemap(projection = 'hammer', lon_0 = 0, resolution = 'c');
        #xpt,ypt = mymap(longs,lats)
        #mymap.plot(xpt, ypt, 'ro')
Beispiel #5
0
def displaymap(region=__AUSREGION__,
               subregions=[], labels=[], colors=[], linewidths=[],
               fontsize='small', bluemarble=True, drawstates=True):
    '''
        regions are [lat,lon,lat,lon]
    '''
    m = Basemap(projection='mill', resolution='f',
        llcrnrlon=region[1], llcrnrlat=region[0],
        urcrnrlon=region[3], urcrnrlat=region[2])
    if bluemarble:
        m.bluemarble()
    else:
        m.drawcountries()
    if drawstates:
        m.drawstates()

    # Add lats/lons to map
    add_grid_to_map(m,xy0=(-10,-80),xyres=(10,10),dashes=[1,1e6],labels=[1,0,0,1])
    for r in subregions:
        if len(labels)<len(r):
            labels.append('')
        if len(colors)<len(r):
            colors.append('k')
        if len(linewidths)<len(r):
            linewidths.append(1)
    # add subregions and little lables:
    for r,l,c,lw in zip(subregions, labels, colors, linewidths):
        plot_rec(m,r,color=c, linewidth=lw)
        lon,lat=r[1],r[2]
        x,y = m(lon,lat)
        plt.text(x+100,y-130,l,fontsize=fontsize,color=c)

    return m
Beispiel #6
0
def plotPointsOnUSMap(points, blueMarble=False, bkcolor='#85A6D9', returnBaseMapObject = False, pointLabels=[], *args, **kwargs):
    from mpl_toolkits.basemap import Basemap
    m = Basemap(llcrnrlon=-125.15625, llcrnrlat=20, urcrnrlon=-59.765625, urcrnrlat=49.61071, projection='mill', lat_1=24, lat_2=50, lon_0=-98, resolution='l', area_thresh=10000)
    m.drawmapboundary(fill_color='#85A6D9')
    
    if blueMarble: m.bluemarble()
    else:
        m.drawmapboundary(fill_color=bkcolor)
        m.fillcontinents(color='white',lake_color=bkcolor)
        m.drawcoastlines(color='#6D5F47', linewidth=.4)
        m.drawcountries(color='#6D5F47', linewidth=.4)
        m.drawstates(color='#6D5F47', linewidth=.4)
    
#    m.fillcontinents(color='white',lake_color='#85A6D9')
#    m.drawstates(color='#6D5F47', linewidth=.4)
#    m.drawcoastlines(color='#6D5F47', linewidth=.4)
#    m.drawcountries(color='#6D5F47', linewidth=.4)
    
#    m.drawmeridians(n.arange(-180, 180, 30), color='#bbbbbb')
#    m.drawparallels(n.arange(-90, 90, 30), color='#bbbbbb')
    lats, lngs = zip(*points)
    
    x,y = m(lngs,lats)
    scatterPlot = m.scatter(x, y, zorder = 2, *args, **kwargs)
    
    for population, xpt, ypt in zip(pointLabels, x, y):
        label_txt = str(population)
        plt.text( xpt, ypt, label_txt, color = 'black', size='small', horizontalalignment='center', verticalalignment='center', zorder = 3)
    if not returnBaseMapObject: return scatterPlot
    else: return (scatterPlot, m)
Beispiel #7
0
    def plot(self):
        ''' plot some random stuff '''
        # random data
        '''data = [random.random() for i in range(2)]

        # create an axis
        ax = self.figure.add_subplot(111)

        # discards the old graph
        ax.hold(False)

        # plot data
        ax.plot(data, '*-')'''
        m = Basemap(projection='robin',lon_0=0,resolution='c')#,latlon=True)
        m.bluemarble(scale=0.2)
        for friend in rpc.bridge.getFriendList():
          print ''
          pd = rpc.bridge.getPeerDetails(friend)
          print pd['name']
          print pd['extAddr']
          ld = gi.record_by_addr(pd['extAddr'])
          print ld
          if ld:
            print ld['latitude'],ld['longitude']
            x, y = m(ld['longitude'],ld['latitude'])
            #m.scatter(x, y,30,marker='o',color='k')
            plt.plot(x, y,'ro')
            plt.text(x,y,pd['name'],fontsize=9,
                    ha='center',va='top',color='r',
                    bbox = dict(boxstyle="square",ec='None',fc=(1,1,1,0.5)))
            #plt.text(x,y,pd['name'],fontsize=14,fontweight='bold',
            #        ha='center',va='center',color='r')
        # refresh canvas
        self.canvas.draw()
def plotMap(longitude1, latitude1, longitude2, latitude2, tag1, tag2):
    '''
    Plots tag points on their appropriate latitude and longitude 
    coordinates on the world map. 
    '''
    map = Basemap(projection='robin', resolution = 'l', area_thresh = 1000.0,
              lat_0=0, lon_0=-130)
    map.drawcoastlines()
    map.drawcountries()
    map.bluemarble()
    map.drawmapboundary()
    map.drawmeridians(np.arange(0, 360, 30))
    map.drawparallels(np.arange(-90, 90, 30))

    min_marker_size = 10
    #This will plot the latitudes and longitues for Tag1
    for lon, lat in zip(longitude1, latitude1):
        x,y = map(lon, lat)
        msize = min_marker_size
        marker_string = get_marker_color(1)
        map.plot(x, y, marker_string, markersize=msize)
    #This will plot latitudes and longitues for Tag2
    for lon, lat in zip(longitude2, latitude2):
        x,y = map(lon, lat)
        msize =  min_marker_size
        marker_string = get_marker_color(2)
        map.plot(x, y, marker_string, markersize=msize)

    title_string = "#" + tag1 +"(green) and #" + tag2 + "(red) currently trending\n"
    plt.title(title_string)
    plt.show()
def generate_map(output, latlng, wesn=None):
    """
    Using Basemap and the matplotlib toolkit, this function generates a map and
    puts a red dot at the location of every IP addresses found in the list.
    The map is then saved in the file specified in `output`.
    """
    print("Generating map and saving it to {}".format(output))
    lats=[]
    lngs=[]
    for i in latlng:
        if i[1]:
            lats.append(i[1])
            lngs.append(i[2])

    if wesn:
        wesn = [float(i) for i in wesn.split('/')]
        m = Basemap(projection='cyl', resolution='l',
                llcrnrlon=wesn[0], llcrnrlat=wesn[2],
                urcrnrlon=wesn[1], urcrnrlat=wesn[3])
    else:
        m = Basemap(projection='cyl', resolution='l')
    m.bluemarble()
    x, y = m(lngs, lats)
    m.scatter(x, y, s=1, color='#ff0000', marker='o', alpha=0.3)
    plt.savefig(output, dpi=300, bbox_inches='tight')
Beispiel #10
0
def map_polygons(groups):
    
    # Set some hardcoded defaults and map settings    
    nLAT=89
    sLAT=-89
    wLON=-179
    eLON=179
    cLAT=sLAT + (nLAT-sLAT)/2
    cLON=wLON + (eLON-wLON)/2
    scale_map=0.4
    font = {'weight' : 'normal',
            'size'   : 2}
    
    matplotlib.rc('font', **font) 
    
    # Read data into vertices
    polygons = dict()
    polygons['labels'] = dict(zip(range(len(groups.index)),groups.index))
    polygons['LONS'] = dict(zip(range(len(groups.index)),[ [x,y,z,k] for x,y,z,k in zip(groups['xmin'],groups['xmin'],groups['xmax'],groups['xmax'])]))
    polygons['LATS'] = dict(zip(range(len(groups.index)),[ [x,y,z,k] for x,y,z,k in zip(groups['ymin'],groups['ymax'],groups['ymax'],groups['ymin'])]))
                                        
    keys=sorted([x for x in polygons['LATS'].keys()])
    
    # 1. CREATE OBJECTS FOR MAP
    fig = plt.figure(figsize=(8, 14), dpi=150)
    ax = fig.add_subplot(111)
    
    myMap = Basemap(projection='cyl', 
                  lat_0=cLAT, lon_0=cLON,
                  llcrnrlat=sLAT,urcrnrlat=nLAT,
                  llcrnrlon=wLON,urcrnrlon=eLON,
                  resolution=None)
    #myMap.shadedrelief(scale=scale_map)
    myMap.bluemarble(scale=scale_map)
    #path_effectsTxt=[path_effects.withSimplePatchShadow()]
    
    # 2. NOW ADD POLYGONS
    ax.grid(color='k')
    for key in keys:
        xyList = [[a,b] for a,b in zip(polygons['LONS'][key], polygons['LATS'][key])]#list(zip(polygons['LONS'][key], polygons['LATS'][key]))
        p = Polygon(xyList, alpha=0.3,facecolor='yellow',edgecolor=None)
        ax.add_artist(p)
        plt.text(polygons['LONS'][key][2],polygons['LATS'][key][1],polygons['labels'][key],weight='bold',va='bottom',ha='right',color='yellow') #,path_effects=path_effectsTxt)
    
    path_effectsLine=[path_effects.SimpleLineShadow(),
                           path_effects.Normal()]
    #plt.show()
    # 3. SAVE OR RETURN FIG
    return fig
    
    #polygons['color']={3:'Blue', \
    #                    1: 'Cyan', \
    #                    2: 'Cyan', \
    #                    6: 'Magenta', \
    #                    4:'Lime',\
    #                    5:'Lime',\
    #                    0:'Gray'}
def run_main():
   """ Main """
   

   tempdir = tempfile.mkdtemp() 
   print "Downloading shape files from MODIS rapid fire... ",
   download(URL_FIRE_SHAPES, "shapes.zip")
   zipf = zipfile.ZipFile('shapes.zip') 

   for name in zipf.namelist():
      data    = zipf.read(name)
      outfile = os.path.join(tempdir, name)
      f       = open(outfile, 'wb')
      f.write(data)
      f.close() 
   zipf.close()
   print "done !"

   print "Parsing shapefile... ",

   shape_path = os.path.join(tempdir, 'Global_%s' % FIRE_LASTS)
   r     = shapefile.Reader(shape_path)
  # print r.fields
   print
   sr= r.shapeRecords()
   print
   total=len(sr)
   print
   xlist=[]
   ylist=[]
   confidence=[]
   
   for i in xrange(total):
      
      sr_test=sr[i]
      
      xlist.append( sr_test.shape.points[0][0]) #longitude
      ylist.append( sr_test.shape.points[0][1]) #latitude
      confidence.append( sr_test.record[8])
         
      
   print "list size: ",len(xlist)
   

   print "done "

   print "Rendering... ",
   
   m = Basemap(projection='cyl')   
   m.bluemarble()
   m.scatter(xlist, ylist, 20, c=confidence, cmap=p.cm.YlOrRd, marker='o', edgecolors='none', zorder=10)
   
   
   p.title("The recent fire hotspots for last %s \n Pixel size: %s | Current Date: %s" % (FIRE_LASTS, RAPIDFIRE_RES,time.strftime("%d/%m/%Y")))
   p.show()
   print "done !"
   os.remove("shapes.zip")
def generate_image(year, month, xs=500, ys=500, elev=60, azim=-90, colormap=cm.seismic):
    m = Basemap(width=12000000,height=12000000,
                rsphere=(6378137.00,6356752.3142),\
                resolution='l',area_thresh=1000.,projection='lcc',\
                lat_0=45,lon_0=170)

    ssl_loc = '/home/guy/Data/cci-ssl/ESACCI-SEALEVEL-L4-MSLA-MERGED-%04d%02d15000000-fv01.nc' % (year, month)
    lons_proj, lats_proj, XX, YY, sla = reproject_data(ssl_loc,'sla', m, xsize=xs, ysize=ys, filter=0)
    sst_loc = '/mnt/surft/data/SST_CCI_L4_monthly_mean_anomalies/%04d%02d--ESACCI-L4_GHRSST-SSTdepth-OSTIA-GLOB_LT-v02.0-fv01.0_anomalies.nc' %(year, month)
    lons_proj, lats_proj, XX, YY, sst = reproject_data(sst_loc,'sst_anomaly', m, xsize=xs, ysize=ys, filter=None)
    
    min_sst = -4
    max_sst = 4
    
    colors = np.empty(sst.shape, dtype=np.dtype((float, (4))))
    for y in range(sst.shape[1]):
        for x in range(sst.shape[0]):
            val = sst[x, y]
            if(np.ma.getmask(sst[x,y]) == True):
                colors[x,y] = (1,0,0,0)
            else:
                zero_to_one = (val - min_sst) / (max_sst - min_sst)
                colors[x, y] = colormap(zero_to_one)
    
    fig = plt.figure(figsize=(19.2,9.6))
    
    ax = plt.subplot(121, projection='3d')
       
    # ax = fig.gca(projection='3d')
    ax.view_init(elev=elev, azim=azim)
    ax.set_axis_off()
     
    surf = ax.plot_surface(XX, YY, sla, rstride=1, cstride=1, facecolors=colors,#cmap=cm.coolwarm,
                           linewidth=0, antialiased=False)
    ax.set_zlim(-3, 3)
    ax.set_xlim((0.22 * xs, 0.78 * xs))
    ax.set_ylim((0.18 * ys, 0.82 * ys))
    
    ax2d = plt.subplot(122, aspect=1)
    m.bluemarble(ax=ax2d, scale=0.2)
    #m.imshow(sst, ax=ax, cmap=cm.coolwarm)
    x, y = m(lons_proj, lats_proj)
    m.pcolor(x,y, sst, ax=ax2d, cmap=colormap, vmin=min_sst, vmax=max_sst)
    
    #matplotlib.rcParams['contour.negative_linestyle'] = 'dashed'
    m.contour(x,y, sla, np.linspace(-1,1,11), colors='k', ax=ax2d)
    # m.pcolor(XX, YY, sla, ax=ax)
    #ax.pcolormesh(XX,YY,sst, vmin=min_sst, vmax=max_sst, cmap=cm.coolwarm)
    
    
    # ax = fig.gca()
    # surf = ax.pcolormesh(XX,YY,sla, vmin=-limit, vmax=limit)
    # fig.colorbar(surf, shrink=0.5, aspect=5)
    
    fig.tight_layout()
    return fig
def mapTut(dLat, dLon):

     m = Basemap(width=12000000,height=9000000,projection='lcc',
            resolution=None,lat_1=45.,lat_2=55,lat_0=50,lon_0=-107.)
     m.bluemarble()

     for i in xrange(len(dLat)):
	    x,y = m(dLon[i],dLat[i])
	    m.plot(x,y, 'ro')
	    plt.title("Geo Plotting")
     plt.show()
def draw_america():
    plt.figure(figsize=(10, 10), facecolor='w')
    m = Basemap(width=7000*1000, height=7000*1000, projection='lcc', resolution='c', lat_0=50, lon_0=-107)
    m.drawcoastlines(linewidth=0.3, antialiased=False, color='#303030')  # 海岸线
    m.drawcountries(linewidth=1, linestyle='-.', antialiased=False, color='k')  # 国界
    m.drawstates(linewidth=0.5, linestyle='--', antialiased=True, color='k')   # 州界
    m.drawparallels(np.arange(0, 90, 10), labels=[True, True, False, False])  # 绘制平行线(纬线) [left,right,top,bottom]
    m.drawmeridians(np.arange(0, 360, 15), labels=[False, False, False, True], linewidth=1)  # 绘制子午线
    m.bluemarble()  # NASA Blue Marble
    plt.tight_layout(4)
    plt.title('北美及附近区域遥感图', fontsize=21)
    plt.show()
Beispiel #15
0
def generate_map(output, lats=[], lons=[]):
    """
    Using Basemap and the matplotlib toolkit, this function generates a map and
    puts a red dot at the location of every IP addresses found in the list.
    The map is then saved in the file specified in `output`.
    """
    print("Generating map and saving it to {}".format(output))
    m = Basemap(projection='cyl', resolution='l')
    m.bluemarble()
    x, y = m(lons, lats)
    m.scatter(x, y, s=1, color='#ff0000', marker='o', alpha=0.3)
    plt.savefig(output, dpi=300, bbox_inches='tight')
Beispiel #16
0
def setup_axes():
    """setup a headless basemap figure with a geostationary projection"""
    fig = headlessmpl.figure(width, height)
    axes = fig.add_subplot(111)
    globe = Basemap(projection='geos', llcrnrlon=low_long,
            llcrnrlat=low_lat, urcrnrlon=high_long, urcrnrlat=high_lat,
            lon_0=150,resolution = 'h', area_thresh = 1000, ax=axes)
    globe.bluemarble()
    globe.drawcoastlines()
    globe.drawcountries()
    globe.drawstates()
    return globe, axes, fig
Beispiel #17
0
def pierce_point_plot(st, pierce_h5,**kwargs):
   """
   Plot source and reciever on map
   """
   save = kwargs.get('save',False)
   f = h5py.File('/home/samhaug/anaconda2/lib/python2.7/site-packages/seispy'+
                 pierce_h5,'r')
   pierce_array = f['pierce'][...]

   fig = plt.figure(figsize=(8,8))
   ax = fig.add_axes([0.1,0.1,0.8,0.8])
   lon_0 = st[0].stats.sac['evlo']
   lat_0 = st[0].stats.sac['evla']
   m = Basemap(llcrnrlon=-90.,llcrnrlat=-20,urcrnrlon=-50.,urcrnrlat=10.,\
              resolution='l',area_thresh=1000.,projection='poly',\
                          lat_0=-0.,lon_0=-70.)
   #m = Basemap(projection='nsper',lon_0=lon_0,lat_0=lat_0,
   #        satellite_height=800*1000.,resolution='l')
   m.drawcoastlines()
   m.drawcountries()
   m.drawparallels(np.arange(-90.,120.,10.))
   meridians = np.arange(180.,360.,10.)
   m.drawmeridians(meridians)
   coord_list = stat_coord(st)
   title = os.getcwd().split('/')
   ax = plt.gca()

   for ii in pierce_array:
       bearing = ii[1]
       origin = geopy.Point(lat_0,lon_0)
       destination = VincentyDistance(kilometers=111*np.degrees(ii[0])).destination(origin,bearing)
       lat = destination[0]
       lon = destination[1]
       x,y = m(lon,lat)
       m.scatter(x,y,8,marker='o',color='yellow',lw=0)

   try:
       x,y = m(st[0].stats.sac['evlo'],st[0].stats.sac['evla'])
       b = beachball(st[0],xy=(x,y),plot='map',width=0.3e6,alpha=0.5)
       b.set_zorder(2)
       ax.add_collection(b)
   except KeyError:
       print('No focal mechanism found')

   ax.set_title('{} \n Depth (km): {} '.format(
               title[5],pierce_h5.split('_')[0]))

   m.bluemarble()
   if save != False:
       plt.savefig(save+'/map.pdf',format='pdf')
   if save == False:
       plt.show()
Beispiel #18
0
def plotmap():
    fig = plt.figure(figsize=(20, 9))
    ax = fig.add_axes([0.01, 0.01, 0.98, 0.98])

    map = Basemap(projection="cyl", resolution="c")
    map.drawcoastlines()
    # map.fillcontinents(color='coral',lake_color='aqua')
    # map.drawmapboundary(fill_color='aqua')
    map.bluemarble(scale=0.2)
    # draw the edge of the map projection region
    map.drawcountries()
    map.drawstates()

    return fig
def draw_eastasia():
    size = 6500*1000    # 6500km
    plt.figure(figsize=(10, 10), facecolor='w')
    m = Basemap(width=size,height=size, projection='lcc', resolution='c', lat_0=35.5, lon_0=103.3)
    m.drawcoastlines(linewidth=0.3, antialiased=False, color='#202020')     # 海岸线
    m.drawrivers(linewidth=0.05, linestyle='-', color=(0.1, 0.1, 0.1), antialiased=False)  # 河流
    m.drawcountries(linewidth=1, linestyle='-.', antialiased=False)         # 国界
    m.drawparallels(np.arange(0, 90, 10), labels=[True, True, False, False])   # 绘制平行线(纬线) [left,right,top,bottom]
    m.drawmeridians(np.arange(0, 360, 15), labels=[False, False, False, True], linewidth=1, dashes=[2,2])   # 绘制子午线
    # m.etopo()   # 地形高程
    m.bluemarble()
    plt.tight_layout(4)
    plt.title('东亚及附近区域遥感图', fontsize=21)  # 东亚及附近区域地理地形图
    plt.show()
Beispiel #20
0
def plot_domains(dlist):
  from mpl_toolkits.basemap import Basemap
  import matplotlib.pyplot as plt
  import ticks

  wrf = {}
  for i in range(1, len(dlist)+1):
    wrf['d%02d'%i] = get(dlist[i-1])

  if wrf['d01'].nc.MAP_PROJ == 1:
    proj = 'lcc'
  elif wrf['d01'].nc.MAP_PROJ == 3:
    proj = 'merc'
  else:
    return('Projection not suported')

  lat_1 = wrf['d01'].nc.TRUELAT1
  lat_2 = wrf['d01'].nc.TRUELAT2
  lon_0 = wrf['d01'].nc.CEN_LON
  lat_0 = wrf['d01'].nc.CEN_LAT
  llcrnrlat = wrf['d01'].lat().min() - 5
  urcrnrlat = wrf['d01'].lat().max() + 5
  llcrnrlon = wrf['d01'].lon().min() - 5
  urcrnrlon = wrf['d01'].lon().max() + 5

  plt.figure()
  ax = plt.axes()
  m = Basemap(projection=proj, llcrnrlat=llcrnrlat, urcrnrlat=urcrnrlat, \
  llcrnrlon=llcrnrlon, urcrnrlon=urcrnrlon, lat_1=lat_1, \
  lat_2=lat_2, lat_0=lat_0, lon_0=lon_0, resolution='i')

  #m.drawcoastlines(color='black', linewidth=2)
  #m.drawcountries(linewidth=1.5)
  m.bluemarble()

  parallels = ticks.loose_label(llcrnrlat, urcrnrlat)
  m.drawparallels(parallels, labels=[1, 0, 0, 0], fontsize=14)
  meridians = ticks.loose_label(llcrnrlon, urcrnrlon)
  m.drawmeridians(meridians, labels=[0, 0, 0, 1], fontsize=14)

  for i in range(1,len(dlist)+1):
    xb = var_border(wrf['d%02d'%i].lon())
    yb = var_border(wrf['d%02d'%i].lat())

    x, y = m(xb,yb)
    tx, ty = m(wrf['d%02d'%i].lon()[-1,0], wrf['d%02d'%i].lat()[-1,0]+0.5)
    colors = ['lightblue', 'pink', 'lightgreen', 'lightsalmon', 'silver', 'khaki']

    ax.plot(x,y, lw=2, c=colors[i-1])
    ax.annotate('d%02d'%i, xy=(tx, ty), fontsize=16, color=colors[i-1])
Beispiel #21
0
def make_map(df):
  m = Basemap(llcrnrlon=-119, llcrnrlat=22, urcrnrlon=-64, urcrnrlat=49, projection='lcc', lat_1=33, lat_2=45,
              lon_0=-95, resolution='h', area_thresh=10000)
  
  trump_places = df.loc[df['party'] == 'Trump']
  print trump_places.head(10)
  #Tplaces_count = trump_places[['location']].groupby('location').tolist()
  Tplaces=trump_places['location'].unique().tolist()
  
  Tlat, Tlng = [], []
  for place in Tplaces:
    try:
      spot = get_location(place)
      Tlat.append(spot[0])
      Tlng.append(spot[1])
    except:
      print "The twitter location: %s cannot be located" % place

  hillary_places = df.loc[df['party'] == 'Hillary']
  #print hillary_places.head(10)
  #Hplaces_count = hillary_places[['location']].groupby('location').size().tolist()
  Hplaces=hillary_places['location'].unique().tolist()

  Hlat, Hlng, spoth = [], [], []
  for place in Hplaces:
    try:
      spoth = get_location(place)
      Hlat.append(spoth[0])
      Hlng.append(spoth[1])
    except:
      print "H: The twitter location: %s cannot be located" % place
  
  print "length of hlat: ", len(Hlat)
  m.bluemarble()
  m.drawcoastlines()
  m.drawcountries(linewidth=3)
  m.drawmapboundary()
  m.drawstates()
  m.drawparallels(np.arange(25,65,20),labels=[1,0,0,0])
  m.drawmeridians(np.arange(-120,-40,20),labels=[0,0,0,1])

  x,y=m(Tlng, Tlat)
  m.scatter(x, y, marker='D', color='r')
  xh,yh=m(Hlng, Hlat)
  m.scatter(xh, yh, marker='D', color='b')
  Title = plt.title("Politics & Twitter: Where are the Tweets?")

  plt.show()
  return
Beispiel #22
0
    def SOLO_maplot(self, centro_lat, centro_lon, llat, llon, ulat, ulon):

        # Note that we're drawing on a regular matplotlib figure, so we set the
        # figure size just like we would any other.
        plt.figure(figsize=(6, 6))

        # Create the Basemap
        event_map = Basemap(projection='lcc',
                            resolution= None,
                            lat_0 = centro_lat, lon_0=centro_lon,  # Map center
                            llcrnrlon=llon, llcrnrlat=llat,  # Lower left corner
                            urcrnrlon=ulon, urcrnrlat=ulat)  # Upper right corner
        # Draw important features
        event_map.bluemarble()

        plt.show()
def groundmap():
    # Determine position of groundstation
    gsx, gsy, gsz, gsvx, gsvy, gsvz = gs_pos()

    # BaseMap drawings
    gmap = Basemap(projection="cyl", llcrnrlat=-90, urcrnrlat=90, llcrnrlon=-180, urcrnrlon=180, resolution="c")
    # gmap.drawcoastlines(linewidth=.25)
    # gmap.drawcountries(linewidth=.25)
    # gmap.fillcontinents(color='g',lake_color='b')
    gmap.drawmapboundary(fill_color="b")
    gmap.drawmeridians(np.arange(0, 360, 30))
    gmap.drawparallels(np.arange(-90, 90, 30))
    gmap.bluemarble()
    tlong = np.arange(trange, trange + t_dif_sec + 1, 1)

    # Converting from xyz j2000 to longitude and latitude
    longref = (EarthRotAngle % (2 * np.pi)) * (180.0 / np.pi)
    longref = 360 - longref
    longgs = (180.0 / np.pi) * np.arctan2(gsy, gsx)
    latgs = (180.0 / np.pi) * np.arctan2(gsz, np.sqrt(gsx * gsx + gsy * gsy))
    # Compensates for the rotation of the earth for groundstation
    for i in range(len(tlong)):
        longgs[i] += longref
        longgs[i] = longgs[i] % (360)

    # Converts xyz of TLE files to longitude and latitude
    for k in range(len(filelist)):
        fname = filelist[k]
        lcolor = ["y", "y", "y"]
        x, y, z, vx, vy, vz = tle_import(fname)
        longsat = (180.0 / np.pi) * np.arctan2(y, x)
        latsat = (180.0 / np.pi) * np.arctan2(z, np.sqrt(x * x + y * y))
        for j in range(len(tlong)):
            longsat[j] += longref
            longsat[i] = longsat[i] % (360)
        # Rescales satellite coordinates for map draw and draws the track
        x, y = gmap(longsat, latsat)

        gmap.plot(x, y, color=lcolor[k], linewidth=2)

    # Rescales groundstation coordinates for map draw and draws the position
    gsx, gsy = gmap(longgs, latgs)

    gmap.plot(gsx, gsy, color="aqua", linewidth=5)
    EarthRotAngle
    return plt.show()
Beispiel #24
0
def plotme(Elats, Elons, plotEclipse, Clats, Clons, plotConflict):
    count = 0

    d = os.path.dirname("globeframes/")
    if not os.path.exists(d):
        os.mkdir(d)

    # Rotate the earth
    for l in range((DEGPERTURN * count - 180), 180, DEGPERTURN):
        fig = plt.figure(figsize=(10, 10))
        map = Basemap(projection="ortho", lat_0=23.4, lon_0=l, resolution="l")

        # Make the globe more realistic
        map.bluemarble(scale=0.2)

        if plotEclipse:
            # compute the native map projection coordinates for countries.
            x, y = map(Elons, Elats)

            # plot filled circles at the locations of the contry.
            map.plot(x, y, "yo", ms=15, picker=5, mew=2)

        if plotConflict:

            x, y = map(Clons, Clats)
            map.plot(x, y, "rx", ms=10, picker=5, mew=4)

            # plot solar eclipse positions
            map.plot(x, y, "rx", ms=6)

        plt.savefig("globeframes/frame{0}".format((str(count).rjust(3, "0"))), facecolor="k")
        count += 1
        plt.clf()
        plt.close(fig)
        print("Percent completed: {} %".format((count * DEGPERTURN / 360) * 100))

    frames = []

    # Put all the frame names in a list
    for i in range(count):
        frames.append("./globeframes/frame{0}.png".format((str(i).rjust(3, "0"))))

    # Create a video file from the frames
    clip = ImageSequenceClip(frames, fps=FPS)
    clip.write_videofile("SpinningGlobe.mp4", fps=FPS)
Beispiel #25
0
def plotBase(fig, dt=None):
    m = Basemap(projection='merc',
                lon_0=0,lat_0=0,lat_ts=0,
                llcrnrlat=0,urcrnrlat=50,
                llcrnrlon=-100,urcrnrlon=-50,
                resolution='l')
    m.drawcountries(linewidth=1, color='k')
    m.drawmapscale(-90, 5, -90, 5, 1000, barstyle='fancy')
    m.bluemarble(scale=1)

    # Get Position of NYC, longitude -74.0064, latitude 40.7142
    x,y    = m(-74.0064, 40.7142)
    # Plot NYC
    m.scatter(x, y, s=100,  marker='*', color='0.5', alpha=1)
    plt.text(x,y,'NYC', fontsize='15')

    if dt is not None: m.nightshade(dt, alpha = 0.3)
    return m
def plotgrid(locations, cities, demand):
	print('plotgrid')
	cities = sorted(cities)

	m = Basemap(
			projection='merc',
	        llcrnrlon=-15,
	        llcrnrlat=30,
	        urcrnrlon=40,
	        urcrnrlat= 60,
	        lat_ts=0,
	        resolution='i',
	        suppress_ticks=True)

	pos = {}
	G=nx.Graph()
	edges = []

	for key in locations:
		for i in range(0,len(locations)):
			edges.append([key, cities[i]])

	for keys, values in locations.iteritems():
		pos[keys] = m(values[1],values[0])

	G.add_edges_from(edges)
	G.edges()

	nodesize_demand = []
	nodes = []
	# strip demand size 
	for keys, values in demand.iteritems():
		nodesize_demand.append(values)

	print('drawing map')
	pos = OrderedDict(sorted(pos.items(), key=lambda t: t[0]))
	
	nx.draw_networkx(G,pos,node_size= 200 ,node_color='blue')

	m.drawcountries()
	m.drawstates()
	m.bluemarble()
	plt.title('European Cities')
	plt.show()
Beispiel #27
0
def basemap_data(axes, draw_map=False, draw_bg=False, draw_coastlines=False,
        draw_states=False):
    """Add coastlines, satellite background etc"""
    min_point = np.array([axes.get_xlim()[0], axes.get_ylim()[0]])
    max_point = np.array([axes.get_xlim()[1], axes.get_ylim()[1]])
    globe = Basemap(projection='cyl', llcrnrlon=min_point[0],
            llcrnrlat=min_point[1], urcrnrlon=max_point[0],
            urcrnrlat=max_point[1], resolution='i', area_thresh=1000,
            ax=axes, suppress_ticks=False, fix_aspect=False)
    if draw_map:
        globe.drawmapboundary()
    if draw_bg:
        globe.bluemarble()
    if draw_coastlines:
        globe.drawcoastlines()
    if draw_states:
        globe.drawstates()
        globe.drawcountries()
    return axes
def _plot_globe(ax, data, lons, lats, lon0, lat0, cmap, symmetrical=False):  
    """
    Plots data onto a globe
    Args:
    ax - the axis to plot onto
    data - a 2d numpy array containing the data to plot (latitude axis first)
    lons - a 1d numpy array containing the longitude values of the data
    lats - a 1d numpy array containing the latitude values of the data 
    """  
    m = Basemap(projection='nsper', lon_0=lon0, lat_0=lat0, resolution='l')
    X, Y = np.meshgrid(lons, lats)
    x, y = m(X, Y)
    
    if(symmetrical):
        scale = np.abs(data).max()
        m.contourf(x, y, data, np.linspace(-scale, scale, 100), cmap=plt.get_cmap(cmap), ax=ax)
    else: 
        m.contourf(x, y, data, 100, cmap=plt.get_cmap(cmap), ax=ax)
    m.bluemarble(ax=ax)
Beispiel #29
0
def plotPointsOnWorldMap(
    points,
    blueMarble=False,
    bkcolor="#85A6D9",
    returnBaseMapObject=False,
    pointLabels=[],
    resolution="l",
    *args,
    **kwargs
):
    from mpl_toolkits.basemap import Basemap

    m = Basemap(
        projection="mill", llcrnrlon=-180.0, llcrnrlat=-60, urcrnrlon=180.0, urcrnrlat=80, resolution=resolution
    )
    if blueMarble:
        m.bluemarble()
    else:
        m.drawmapboundary(fill_color=bkcolor)
        m.fillcontinents(color="white", lake_color=bkcolor)
        m.drawcoastlines(color="#6D5F47", linewidth=0.4)
        m.drawcountries(color="#6D5F47", linewidth=0.4)

    lats, lngs = zip(*points)

    x, y = m(lngs, lats)
    scatterPlot = m.scatter(x, y, zorder=2, *args, **kwargs)
    for population, xpt, ypt in zip(pointLabels, x, y):
        label_txt = str(population)
        plt.text(
            xpt,
            ypt,
            label_txt,
            color="black",
            size="small",
            horizontalalignment="center",
            verticalalignment="center",
            zorder=3,
        )
    if not returnBaseMapObject:
        return scatterPlot
    else:
        return (scatterPlot, m)
Beispiel #30
0
def globmap(**kwargs):
    from mpl_toolkits.basemap import Basemap
    from scipy.io.netcdf import netcdf_file
    
    print "Drawing selection map"
    
    # draw and set up map
    fig = figure(figsize=[10,4],dpi=100)
    m = Basemap(projection='cyl',
                llcrnrlon=-180, llcrnrlat=-90,
                urcrnrlon= 180, urcrnrlat= 90,
                resolution='c')
    m.bluemarble(scale=.1)

    parallels = [-60, -30,0,30, 60]
    meridians = [-120,-60,0,60,120]   
    m.drawparallels(parallels,color='k',labels=[1,0,0,1],linewidth=1)
    m.drawmeridians(meridians,color='k',labels=[1,0,0,1],linewidth=1)
    
    fig.subplots_adjust(left=0.06, right=0.67)
    instr = kwargs.get("instructions","")
    
    figtext(0.69, 0.91, instr, 
            va='top', ha='left',
            size=8)
    
    if kwargs.get('rectangle'):
        from matplotlib.widgets import  RectangleSelector
        toggle.RS = RectangleSelector(gca(), onselect, 
                                        useblit=True,
                                        drawtype='box',
                                        button=[1],
                                        rectprops = dict( facecolor='orange', 
                                                    edgecolor = 'black',
                                                    alpha=0.3, fill=True))
        connect('button_press_event', toggle)
        connect('button_press_event', remove_rect)
        connect('key_press_event', reset_fig)
        connect('key_press_event', adjust_lims)
    
    show()
Beispiel #31
0
if len(sys.argv) < 2 or scal == 0 or scal >= 1:

    # create default map
    m = Basemap(projection='cyl',
                resolution=None,
                llcrnrlat=-90,
                urcrnrlat=90,
                llcrnrlon=-180,
                urcrnrlon=180,
                ax=ax)
    draw_map(m)

    #m.bluemarble(scale=0.1)
    #m.bluemarble(scale=0.5)
    m.bluemarble()

else:
    # create map with scale arg
    m = Basemap(projection='cyl',
                resolution=None,
                llcrnrlat=-90,
                urcrnrlat=90,
                llcrnrlon=-180,
                urcrnrlon=180,
                ax=ax)
    draw_map(m)

    m.bluemarble(scale=scal)

#m = Basemap(projection='mill', resolution=None,
Beispiel #32
0
@author: vchrombie
"""

import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap

# loading the dataset using pandas
DATA_URL = 'http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/4.5_month.csv'
df = pd.read_csv(DATA_URL)

# creating the basic plots
fig, ax = plt.subplots()
earth = Basemap(ax=ax)

# creating the earth map
earth.drawcoastlines(color='#556655', linewidth=0.5)

# plotting the data on the map
ax.scatter(df['longitude'],
           df['latitude'],
           df['mag']**2,
           c='red',
           alpha=0.5,
           zorder=10)

# saving the plot
ax.set_xlabel("4.5M+ earthquakes monthly plot")
fig.savefig('usgs-4.5m-plain.png', dpi=350)
earth.bluemarble(alpha=0.42)
fig.savefig('usgs-4.5m-earth.png', dpi=350)
Beispiel #33
0
def draw_satellite_map(basemap_params, colored_attribute='orient'):
    '''
    Input:
    basemap_params: <dict> 'basemap parameter': value
    colored_attribute: 'orient''elevation', which attributes to be used in colormap
    '''
    llcrnrlon = basemap_params.get('llcrnrlon')
    llcrnrlat = basemap_params.get('llcrnrlat')
    urcrnrlon = basemap_params.get('urcrnrlon')
    urcrnrlat = basemap_params.get('urcrnrlat')
    projection = basemap_params.get('projection', 'cyl')
    lat_0 = basemap_params.get('lat_0')
    lon_0 = basemap_params.get('lon_0')

    if colored_attribute == 'orient':
        cmap = cm.get_cmap('hsv')  # cyclic colormap for angles
    elif colored_attribute == 'elevation':
        cmap = cm.get_cmap('Oranges')
    else:
        raise ValueError('Unknown color encoding attributes.')

    ## 从网络导入空间站数据
    from skyfield.api import Topos, load
    stations_url = 'http://celestrak.com/NORAD/elements/stations.txt'
    satellites = load.tle(stations_url)
    satellite = satellites['ISS (ZARYA)']

    load = Loader(directory='.', expire=False)
    # expire=False: use local files
    ts = load.timescale()
    hours = np.arange(0, 3, 0.01)
    time = ts.utc(2019, 6, 13, hours)

    all_stations_names = list(satellites.keys())
    all_stations = list(satellites.values())

    # 获取卫星的初始位置
    t = time[0]

    all_geocentric = [sate.at(t) for sate in all_stations]

    # 避免不停地写list的向量运算np.vectorize一切, 我们
    vecfun_subpoint = np.vectorize(lambda x: x.subpoint())
    vecfun_lon = np.vectorize(lambda x: x.longitude.degrees)
    vecfun_lat = np.vectorize(lambda x: x.latitude.degrees)
    vecfun_ele = np.vectorize(lambda x: x.elevation.m)

    all_subpoint = vecfun_subpoint(all_geocentric)
    all_lon = vecfun_lon(all_subpoint)
    all_lat = vecfun_lat(all_subpoint)
    all_ele = vecfun_ele(all_subpoint)

    # 初始化画布
    fig, ax = plt.subplots(figsize=(8, 8))

    m = Basemap(llcrnrlon=llcrnrlon,
                llcrnrlat=llcrnrlat,
                urcrnrlon=urcrnrlon,
                urcrnrlat=urcrnrlat,
                lat_0=lat_0,
                lon_0=lon_0,
                projection=projection)
    m.bluemarble()

    # 初始画图

    # 全体位置
    x, y = m(all_lon, all_lat)
    # 全体方位


    all_velocity = [station.ITRF_position_velocity_error(t)[1] \
        for station in all_stations]
    all_orient = [np.mod(np.rad2deg(np.angle(v[0] + v[1]*1j)) - 90, 360) \
        for v in all_velocity]
    if colored_attribute == 'orient':
        all_color_value = [orient / 360 for orient in all_orient]
    elif colored_attribute == 'elevation':
        all_color_value = (all_ele - np.nanmin(all_ele)) / (
            np.nanmax(all_ele) - np.nanmin(all_ele))

    scat = []
    for i in range(len(x)):
        scat.append(
            m.scatter(x[i],
                      y[i],
                      marker=(3, 0, all_orient[i]),
                      color=cmap(all_color_value[i])))
    '''内嵌的函数init, update 用于动画'''
    def init():
        # return scat,
        # return scat,sate_text
        return scat

    def update(frame):
        t = time[frame]
        all_geocentric = [sate.at(t) for sate in all_stations]

        all_subpoint = vecfun_subpoint(all_geocentric)

        all_subpoint = vecfun_subpoint(all_geocentric)
        all_lon = vecfun_lon(all_subpoint)
        all_lat = vecfun_lat(all_subpoint)
        all_ele = vecfun_ele(all_subpoint)

        x, y = m(all_lon, all_lat)
        all_velocity = [station.ITRF_position_velocity_error(t)[1] \
            for station in all_stations]
        all_orient = [np.mod(np.rad2deg(np.angle(v[0] + v[1]*1j)) - 90, 360) \
            for v in all_velocity]
        if colored_attribute == 'orient':
            all_color_value = [orient / 360 for orient in all_orient]
        elif colored_attribute == 'elevation':
            all_color_value = (all_ele - np.nanmin(all_ele)) / (
                np.nanmax(all_ele) - np.nanmin(all_ele))

        scat = []
        for i in range(len(x)):
            scat.append(
                m.scatter(x[i],
                          y[i],
                          marker=(3, 0, all_orient[i]),
                          color=cmap(all_color_value[i])))

        # scat = m.scatter(x, y, marker=(3, 0, 40), zorder=10, color=[0.2,0.2,0.9])
        # sate_text = plt.text(x+8, y-8, all_stations_names, color=[0.9,0.2,0.2])

        # return scat,
        # return scat,sate_text
        return scat

    ani = FuncAnimation(fig,
                        update,
                        frames=np.arange(len(hours)),
                        init_func=init,
                        blit=True,
                        interval=200)
    plt.show()
Beispiel #34
0
]
# compute the native map projection coordinates for cities.
xc, yc = map(lons, lats)
# make up some data on a regular lat/lon grid.
nlats = 73
nlons = 145
delta = 2. * np.pi / (nlons - 1)
lats = (0.5 * np.pi - delta * np.indices((nlats, nlons))[0, :, :])
lons = (delta * np.indices((nlats, nlons))[1, :, :])
wave = 0.75 * (np.sin(2. * lats)**8 * np.cos(4. * lons))
mean = 0.5 * np.cos(2. * lats) * ((np.sin(2. * lats))**2 + 2.)
# compute native map projection coordinates of lat/lon grid.
# (convert lons and lats to degrees first)
x, y = map(lons * 180. / np.pi, lats * 180. / np.pi)
# draw map boundary
map.drawmapboundary(color="0.9")
# draw graticule (latitude and longitude grid lines)
map.drawmeridians(np.arange(0, 360, 30), color="0.9")
map.drawparallels(np.arange(-90, 90, 30), color="0.9")
# plot filled circles at the locations of the cities.
map.plot(xc, yc, 'wo')
# plot the names of five cities.
for name, xpt, ypt in zip(cities, xc, yc):
    plt.text(xpt + 100000, ypt + 100000, name, fontsize=9, color='w')
# contour data over the map.
cs = map.contour(x, y, wave + mean, 15, linewidths=1.5)
# draw blue marble image in background.
# (downsample the image by 50% for speed)
map.bluemarble(scale=0.5)
plt.show()
    def runOverallGa(self):
        possible_solutions = m.factorial(self.number_of_cities - 1)
        ninitpop = self.initial_pop_size
        ## create an empty dataframe to store the solutions
        all_solutions_generated = pd.DataFrame(columns=['Route', 'Cost'])
        #start a for loop and run the whole process for mentioned number of times
        print("Starting {} iterations of the GA".format(self.noverall))
        #generating initial population
        """We only generate a population initially, after  the first run ,
		we take the best solutions from the previous run and continue with the process"""
        if all_solutions_generated.shape[0] == 0:
            initial_pop_cost = self.initialPopCost()
            sorted_init_pop = initial_pop_cost.sort_values('Cost')
        else:
            sorted_init_pop = all_solutions_generated.head(
                self.initial_pop_size)

# selecting the elite few
        elite_few_df = self.theEliteFew()
        best_sol = []
        for i in range(self.noverall):
            # Generating a random number based on which we either mutate or do a crossover
            matingFactor = np.random.uniform(
                0, 1, 1)  # Random pick to decide on Mutation / crossover
            if matingFactor < 0.15:
                mutatedPopulationWthCost = self.mutationFunction(
                    all_solutions_generated)
                all_solutions_generated.append(mutatedPopulationWthCost)
            else:
                crossoverPopulation = self.routesAfterCrossOver()
                all_solutions_generated = all_solutions_generated.append(
                    crossoverPopulation)

            all_solutions_generated.Route = all_solutions_generated.Route.map(
                lambda x: tuple(x))
            unique_sols_generated = all_solutions_generated.drop_duplicates(
            ).sort_values('Cost')
            all_solutions_generated = all_solutions_generated.sort_values(
                'Cost').head(
                    ninitpop)  # only take the top ninitpop number of solutions
            all_solutions_generated.Route = all_solutions_generated.Route.map(
                lambda x: list(x))

        print(
            "-------------------------------------------------------------------------------------------"
        )
        print(
            "Best solution for initial population size of {} and number of runs {} is \n {}"
            .format(self.initial_pop_size, self.noverall,
                    all_solutions_generated.sort_values('Cost').head(1)))
        print("Generated {}({}%) of the {} solutions".format(
            all_solutions_generated.shape[0],
            np.round((len(all_solutions_generated) / possible_solutions) * 100,
                     3), possible_solutions))
        final_sol = all_solutions_generated.sort_values('Cost').head(1)

        #### Final Solution ( Cities)
        final_route = []
        starting_point = self.dist_mat.index[0]
        for i in final_sol.Route.values[0]:
            final_route.append(self.cities_mapping[i])
        final_route = [starting_point] + final_route + [starting_point]

        total_cost = self.fitnessFunction(list(final_sol.Route.values[0]))

        print(
            "Total distance travelled to cover the final route of \n {} is {} KM. (Generated from initial population size of {})"
            .format(" => ".join(final_route), total_cost,
                    self.initial_pop_size))
        print(
            "-------------------------------------------------------------------------------------------"
        )
        best_sol.append(final_sol)

        # Basemap is available for Linux distributions
        try:
            city_list = final_route
            cities = city_list
            scale = 1
            map = Basemap(width=1000000,
                          height=800000,
                          projection='lcc',
                          resolution='l',
                          llcrnrlon=67,
                          llcrnrlat=5,
                          urcrnrlon=99,
                          urcrnrlat=37,
                          lat_0=27,
                          lon_0=77)

            plt.figure(figsize=(12, 10))
            map.bluemarble()
            city_loc_df = pd.read_csv("data/city_lat_lon.csv")
            city_loc_df.columns = ['city', 'Lat', 'Lon']

            # Get the location of each city and plot it
            X_list = []
            Y_list = []
            geolocator = Nominatim()
            for city in city_list + [city_list[0]]:
                x, y = city_loc_df.loc[
                    city_loc_df['city'] == city].Lat.values, city_loc_df.loc[
                        city_loc_df['city'] == city].Lon.values
                plt.annotate(city, xy=(x, y))
                X_list.append(x)
                Y_list.append(y)

            plt.plot(X_list, Y_list, 'ro--', color='red')
            plt.title(
                "Solution from GA covering {} kilometers with an initial population size of {}"
                .format(total_cost, self.initial_pop_size),
                fontsize=14)
            #     plt.show()
            img_file_name = "GA Solution for initial population size of {} and ({} KM).jpg".format(
                self.initial_pop_size, total_cost)
            plt.savefig(img_file_name)
            HTML('<img src = {}>'.format(img_file_name))
        except:
            warnings.warn("Could not generate plot")
            pass
        return (final_sol,
                self.fitnessFunction(list(final_sol.Route.values[0])))
Beispiel #36
0
def plot_stations(projection='merc',
                  data='processed',
                  channels=['BHZ', 'LHZ'],
                  locations=['', '00', '10'],
                  bluemarble=False):

    # figure out station IDS and their coordinates
    ids = []
    stations = []
    lats = []
    lons = []

    files = os.listdir(os.path.join('data', data))
    for f in files:
        infs = os.path.basename(f).split('.')
        if len(infs) < 4: continue
        ids.append('{}.{}'.format(*infs[0:2]))
    ids = list(set(ids))

    if ids == []:
        print('No data found.')
        return ()

    # look up station xml files, get coordinates
    for i in ids:
        station = stainfo(i)

        staxml = os.path.join('meta', 'stationxml', i + '.xml')
        if os.path.exists(staxml) == False:
            continue

        inv = read_inventory(staxml)

        for j in range(len(locations)):
            for k in range(len(channels)):

                if station.lat is not None: break

                try:
                    c = inv.get_coordinates(i + '.' + locations[j] + '.' +
                                            channels[k])
                    station.lat = c['latitude']
                    station.lon = c['longitude']
                    lats.append(c['latitude'])
                    lons.append(c['longitude'])
                except:
                    continue

        if station.lat == None:
            print('No coordinates found for station %s\
for locations \'\',00,10.' % i)
            continue
        else:
            stations.append(station)

    fig = plt.figure()

    # if min(lons) < 0:
    #   lons += 180.
    #   shift_lons = True
    # if min(lats) < 0:
    #   lats += 90.
    #   shift_lats = True

    # xmin, xmax, ymin, ymax and central meridian of map
    xmin = min(lons) - 10
    if xmin < -180:
        xmin = -180.
    xmax = max(lons) + 10
    if xmax > 180.:
        xmax = 180.
    ymin = min(lats) - 5
    if ymin < -90.:
        ymin = -90.
    ymax = max(lats) + 5
    if ymax > 90.:
        ymax = 90.

    mid_merid = (max(lons) - min(lons)) * 0.5
    mid_paral = (max(lats) - min(lats)) * 0.5

    # basemap
    m = Basemap(rsphere=6378137,
                resolution='l',
                projection=projection,
                lat_0=mid_paral,
                lon_0=mid_merid,
                llcrnrlat=ymin,
                urcrnrlat=ymax,
                llcrnrlon=xmin,
                urcrnrlon=xmax)

    if bluemarble:
        m.bluemarble()
        textcol = 'w'
    else:
        m.drawcoastlines()
        textcol = 'k'

    #draw the meridians and parallels
    parallels = np.arange(round(ymin), round(ymax), 10)
    #labels = [left,right,top,bottom]
    m.drawparallels(parallels, labels=[False, True, True, False])
    meridians = np.arange(round(xmin), round(xmax), 20)
    m.drawmeridians(meridians, labels=[True, False, False, True])

    # plot stations on map
    for sta in stations:

        m.plot(sta.lon, sta.lat, 'rv', markersize=12., latlon=True)
        x, y = m(sta.lon, sta.lat)
        plt.text(x, y, '   ' + sta.id, fontweight='bold', color=textcol)
    # save map in test folder
    plt.show()
def plot_2D_density(Year, MapStyle):
    '''
    Parameters
        - Year      : between 1970-2015     | str
        - MapStyle  : style palette         | str
    Return
        A 2D Geo Map: The denser the red marker in a country,
                      the more severe damages had taken place.
    '''
    # use regular expression to check the format
    if not re.match(r'[\[|\(][0-9]{4}\,\s?[0-9]{4}[\]|\)]$', str(Year)):
        raise NotIntervalError

    # the starting year should be less than the ending yer
    elif Year[0] >= Year[1]:
        raise IntervalReverseError

    # catch the missing value exceptions in 1993
    elif Year == (1993, 1993):
        print('Data of 1993 is not available in Global Terrorism Database.\n\
Click the link to learn why.\nhttps://www.start.umd.edu/gtd/faq/')

    # catch the out of range yer interval input errors
    elif (Year[0] < 1970) or (Year[1] > 2015):
        raise IntervalLeakError

    else:
        if Year[0] == Year[
                1]:  # catch the excetion the starting year and the ending year converge
            df_gt = data.load_df()
            df = df_gt[df_gt.year == Year[0]]
        else:
            df = ut.df_sel_btw_years(Year)

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

        m = Basemap('mill')
        m.drawcountries(linewidth=0.5,
                        linestyle='solid',
                        color='white',
                        antialiased=1,
                        ax=None,
                        zorder=None)

        # Background settings
        if MapStyle == 'Blue Marble':
            m.drawcoastlines()
            m.bluemarble()
        elif MapStyle == 'Etopo':
            m.etopo()
        else:
            m.drawcoastlines(color='w')
            m.drawcountries(color='w')
            m.drawstates(color='w')
            m.fillcontinents(color='lightblue', lake_color='w')
            m.drawmapboundary(fill_color='w', color='w')

        # get latitude and longitude
        lat = ut.make_array(df, 'latitude')
        lon = ut.make_array(df, 'longitude')

        x, y = m(lon, lat)
        m.plot(x, y, 'r^', marker='o', markersize=4, alpha=.3)

        plt.title('Global Attack Density Plot: {}-{}'.format(Year[0], Year[1]),
                  size=16)
        plt.show()
Beispiel #38
0
def run_main():
    """ Main """

    tempdir = tempfile.mkdtemp()
    print "Downloading shape files from MODIS rapid fire... ",
    download(URL_FIRE_SHAPES, "shapes.zip")
    zipf = zipfile.ZipFile('shapes.zip')

    for name in zipf.namelist():
        data = zipf.read(name)
        outfile = os.path.join(tempdir, name)
        f = open(outfile, 'wb')
        f.write(data)
        f.close()
    zipf.close()
    print "done !"

    print "Parsing shapefile... ",

    shape_path = os.path.join(tempdir, 'Global_%s' % FIRE_LASTS)
    r = shapefile.Reader(shape_path)
    # print r.fields
    print
    sr = r.shapeRecords()
    print
    total = len(sr)
    print
    xlist = []
    ylist = []
    confidence = []

    for i in xrange(total):

        sr_test = sr[i]

        xlist.append(sr_test.shape.points[0][0])  #longitude
        ylist.append(sr_test.shape.points[0][1])  #latitude
        confidence.append(sr_test.record[8])

    print "list size: ", len(xlist)

    print "done "

    print "Rendering... ",

    m = Basemap(projection='cyl')
    m.bluemarble()
    m.scatter(xlist,
              ylist,
              20,
              c=confidence,
              cmap=p.cm.YlOrRd,
              marker='o',
              edgecolors='none',
              zorder=10)

    p.title(
        "The recent fire hotspots for last %s \n Pixel size: %s | Current Date: %s"
        % (FIRE_LASTS, RAPIDFIRE_RES, time.strftime("%d/%m/%Y")))
    p.show()
    print "done !"
    os.remove("shapes.zip")
Beispiel #39
0
    https://colab.research.google.com/drive/11Ewz0xLhaaWyqwjpbfTY0PN--4qsVLbd
"""

!apt-get install libgeos-3.5.0
!apt-get install libgeos-dev
!pip install https://github.com/matplotlib/basemap/archive/master.zip

# Commented out IPython magic to ensure Python compatibility.
# %matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap

plt.figure(figsize=(8, 8))
m = Basemap(projection='ortho', resolution=None, lat_0=50, lon_0=-100)
m.bluemarble(scale=0.5);

fig = plt.figure(figsize=(8, 8))
m = Basemap(projection='lcc', resolution=None,
            width=8E6, height=8E6, 
            lat_0=45, lon_0=-100,)
m.etopo(scale=0.5, alpha=0.5)

# Map (long, lat) to (x, y) for plotting
x, y = m(-122.3, 47.6)
plt.plot(x, y, 'ok', markersize=5)
plt.text(x, y, ' Seattle', fontsize=12);

from itertools import chain

def draw_map(m, scale=0.2):
Beispiel #40
0
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')
# draw lat/lon grid lines every 30 degrees.
m.drawmeridians(np.arange(0,360,60),color='0.5')
m.drawparallels(np.arange(-90,90,30),color='0.5')
plt.title("Blue Marble image warped from 'cyl' to 'mbtfpq' projection",fontsize=12)
print('warp to McBryde-Thomas Flat-Polar Quartic map ...')

# create new figure
fig=plt.figure()
# define projection centered on North America.
m = Basemap(projection='hammer',lon_0=-100,resolution='l')
m.bluemarble(scale=0.5)
# draw coastlines.
m.drawcoastlines(linewidth=0.5,color='0.5')
        "capital_city"] + "\nIncome Level: " + country_dict[c][
            "income_level"] + "\nGDP Growth(" + str(
                dictGDPGrowthY[c]) + "): " + str(
                    dictGDPGrowth[c])[:5] + " %" + "\nGNI per Capita(" + str(
                        dictGNIY[c]) + "): $" + str(
                            dictGNI[c]) + "\nGDP(" + str(
                                dictGDPY[c]) + "): $" + str(
                                    float(dictGDP[c] / 1000000000000)
                                )[:5] + " Trillion" + "\n\n"

# Make and plot legend for income level
# Draw the coastlines on worldmap
m.drawcoastlines()
# Draw the country bounderis on worldmap
m.drawcountries()
# Draw the NASA 'Blue marble' Image
m.bluemarble()
z = randn(10)
# Defining legends
red_dot, = plt.plot(z, "ro", markersize=6)
yellow_dot, = plt.plot(z, "yo", markersize=6)
blue_dot, = plt.plot(z, "bo", markersize=6)
green_dot, = plt.plot(z, "go", markersize=6)
plt.legend([red_dot, yellow_dot, blue_dot, green_dot], [
    "Low income", "Lower middle income", "Upper middle income", "High income"
],
           loc=4)
plt.text(0, 0, text_add, fontsize=8, weight='bold', color='r')
#Show the graph showing the text, map and legends
plt.show()
Beispiel #42
0
def combined(sim_file, lattice_files, datetime, centre, xco2_lims=None, map_bkgd='bluemarble', cmap='jet', out='show', **kwargs):
    """
    Create a combined plot 
    """

    _, (xco2_ax, cld_ax, ret_ax) = plt.subplots(nrows=1, ncols=3, figsize=(15,8))
    
    
    ##############################################################
    
    plt.sca(xco2_ax)
    
    
    xco2, xco2_lats, xco2_lons = ec_cas.global_XCO2(datetime)
    
    proj_xco2 = Basemap(projection='ortho', lat_0=centre[0], lon_0=centre[1], resolution='l')
    
    proj_xco2.drawcoastlines(linewidth=0.75)
    proj_xco2.drawcountries(linewidth=0.5)
    proj_xco2.drawmeridians(np.arange(-180, 181, 30), latmax=90, linewidth=0.5)
    proj_xco2.drawparallels(np.arange(-90, 91, 15), latmax=90, linewidth=0.5)
    
    
    lon, lat = np.meshgrid(xco2_lons, xco2_lats)
    x,y = proj_xco2(lon, lat)
    
    xco2_mask = np.ma.masked_greater(x, 1e15).mask
    xco2_masked = np.ma.array(xco2, mask=xco2_mask)
    
    if xco2_lims:
        vmin_xco2, vmax_xco2 = xco2_lims
    else:
        vmin_xco2 = xco2.min() // 1.
        vmax_xco2 = xco2.max() // 1. + 1.
    
    sm_xco2 = ScalarMappable(Normalize(vmin=vmin_xco2, vmax=vmax_xco2), cmap=cmap)
    levs_xco2 = np.linspace(vmin_xco2, vmax_xco2, 256)
    clevs_xco2 = [sm_xco2.to_rgba(lev) for lev in levs_xco2]
    
    xco2_ctr = plt.contourf(x, y, xco2_masked, levs_xco2, colors=clevs_xco2, extend='both')
    
    xco2_cbar = plt.colorbar(xco2_ctr, orientation='horizontal', fraction=0.1, aspect=40)
    xco2_cbar.set_label('Xco$_2$ [ppm]')
    xco2_cbar.set_ticks(np.arange(vmin_xco2, vmax_xco2 + 1, 1))
    
    plt.title(datetime.strftime('EC-CAS Run %d %b %Y %H:%M:%S'))
    
    
    ##############################################################
    
    plt.sca(cld_ax)
    
    
    mission = retrievals.Mission(sim_file, *lattice_files, **kwargs)
    
    obs_time = time_utils.Time(datetime, mission.satellite.times[0].ref)        
        
    # find the closest apogee point to obs_time
    apogees = mission.satellite.get_apogees()
    apogee_ind = time_utils.closest_index(obs_time, apogees)
    
    # create the ObservationPeriod instance, and generate the Retrieval instances
    obs = retrievals.ObservationPeriod(mission, apogees[apogee_ind], mission.lattice_files[apogee_ind%2])
    obs.main_filter()
    obs.generate_retrievals()
    
    # find the closest segment of the observation period
    obs_ind = time_utils.closest_index(obs_time, obs.obs_middle)
    
    # clat, clon = centre
    proj_cld = Basemap(projection='ortho', lat_0=centre[0], lon_0=centre[1], resolution='c')
    
    # draw cloud data that was used to determine FOV locations
    obs.cloud_collection.show_clouds_ortho(obs.cloud_times[obs_ind], centre, map_bkgd=map_bkgd, out='')
    
    proj_cld.nightshade(datetime)
    
    # draw a red border around each of the selected FOVs
    for ret in obs.retrievals[obs_ind]:
        
        lats = np.concatenate([ret.pixel_lats[:,0], ret.pixel_lats[-1,:], ret.pixel_lats[::-1,-1], ret.pixel_lats[0,::-1]])
        lons = np.concatenate([ret.pixel_lons[:,0], ret.pixel_lons[-1,:], ret.pixel_lons[::-1,-1], ret.pixel_lons[0,::-1]])
        
        x,y = proj_cld(lons, lats)
        coords = np.vstack([x,y]).T
        
        if not np.sum(coords > 1e15):
        
            p = Polygon(coords, fill=False, edgecolor='r', zorder=10)
            plt.gca().add_patch(p)
        
    plt.title('FoV Selections {0} - {1} UTC'.format(obs.obs_times[obs_ind].strf('%d %B %Y %H:%M'), obs.obs_times[obs_ind+1].strf('%H:%M')))
    
    
    ##############################################################
    
    plt.sca(ret_ax)
    
    
    proj_ret = Basemap(projection='ortho', lat_0=centre[0], lon_0=centre[1], resolution='l')
    
    if map_bkgd == 'bluemarble':
        proj_ret.bluemarble()
    elif map_bkgd == 'etopo':
        proj_ret.etopo()
    elif map_bkgd == 'mask':
        proj_ret.drawlsmask(land_color='limegreen', ocean_color='dodgerblue', resolution='l')
        
        proj_ret.drawcoastlines(linewidth=0.75)
        proj_ret.drawcountries(linewidth=0.5)
        proj_ret.drawmeridians(np.arange(-180, 181, 30), latmax=90, linewidth=0.5)
        proj_ret.drawparallels(np.arange(-90, 91, 15), latmax=90, linewidth=0.5)
    else:
        raise ValueError('invalid map background specification')
    
    proj_ret.nightshade(datetime)
    
    
    sm_ret = ScalarMappable(Normalize(vmin=vmin_xco2, vmax=vmax_xco2), cmap=cmap)
    levs_ret = np.linspace(vmin_xco2, vmax_xco2, 256)
    clevs_ret = [sm_ret.to_rgba(lev) for lev in levs_ret]
    
    xco2_interp = RegularGridInterpolator((xco2_lats, xco2_lons), xco2, bounds_error=False, fill_value=None)
    
    for ret in obs.retrievals[obs_ind]:
                
        x,y = proj_ret(ret.pixel_lons, ret.pixel_lats)
                
        if not np.sum(x > 1e15):
        
            latlon_arr = np.dstack([ret.pixel_lats, ret.pixel_lons])
            xco2_ret = xco2_interp(latlon_arr)
            
            retmask = ret.valid_retrievals == 0
            xco2_ret_masked = np.ma.array(xco2_ret, mask=retmask)
            
            ret_ctr = plt.contourf(x, y, xco2_ret_masked, levs_ret, colors=clevs_ret, extend='both')
        
    
    ret_cbar = plt.colorbar(ret_ctr, orientation='horizontal', fraction=0.1, aspect=40)
    ret_cbar.set_label('Xco$_2$ [ppm]')
    ret_cbar.set_ticks(np.arange(vmin_xco2, vmax_xco2 + 1, 1))
    
    plt.title('AIM-North Retrievals {0} - {1} UTC'.format(obs.obs_times[obs_ind].strf('%d %B %Y %H:%M'), obs.obs_times[obs_ind+1].strf('%H:%M')))   
            
    
    ##############################################################
    
    
    plt.suptitle('AIM-North Observing Strategy')
    plt.subplots_adjust(wspace=0.05, left=0.05, right=0.95, top=1., bottom=0.1)
    
    cld_ax.set_position([0.35, 0.2525, 0.3, 0.675])
        
    
    if out == 'show':
        plt.show()
    elif out == '':
        pass
    else:
        plt.savefig(os.path.join('../figures/combined_plots/', out))
        plt.close()
def plot_map(df, variable, title, saveFig=False):
    # How much to zoom from coordinates (in degrees)
    zoom_scale = 0
    lats = df['Center Lat'].tolist()
    lons = df['Center Long'].tolist()
    prob = df[variable].tolist()

    # Setup the bounding box for the zoom and bounds of the map
    bbox = [np.min(lats)-zoom_scale,np.max(lats)+zoom_scale,\
            np.min(lons)-zoom_scale,np.max(lons)+zoom_scale]

    fig, ax = plt.subplots(figsize=(20, 10))
    ax.set_title(title, fontsize=24, loc='center')
    matplotlib.rcParams.update({'font.size': 14})
    # Define the projection, scale, the corners of the map, and the resolution.
    m = Basemap(projection='cyl',
                llcrnrlat=29.75,
                urcrnrlat=46.25,
                llcrnrlon=-6,
                urcrnrlon=36.5,
                lat_ts=10,
                resolution='h')
    m.bluemarble()

    # Draw coastlines and fill continents and water with color
    m.drawcoastlines()
    #m.fillcontinents(color='#CCCCCC',lake_color='lightblue')

    # draw parallels, meridians, and color boundaries
    m.drawparallels(np.arange(29.75, 46.25, (46.25 - 30) / 5),
                    labels=[1, 0, 0, 0])
    m.drawmeridians(np.arange(-6, 36.5, (36.5 + 6) / 5),
                    labels=[0, 0, 0, 1],
                    rotation=15)
    m.drawmapboundary(fill_color='lightblue')

    # format colors for elevation range
    alt_min = np.min(prob)
    alt_max = np.max(prob)
    cmap = plt.get_cmap('jet')  #jet,nipy_spectral,YlOrRd,hot_r
    normalize = matplotlib.colors.Normalize(vmin=alt_min, vmax=alt_max)

    from matplotlib.patches import Rectangle
    from matplotlib.patches import FancyBboxPatch

    # the range [50,250] can be changed to create different colors and ranges
    for ii in range(0, len(prob)):
        x, y = m(lons[ii], lats[ii])
        color_interp = np.interp(prob[ii], [alt_min, alt_max], [50, 250])
        rect = plt.Rectangle(xy=(x - 0.25, y - 0.25),
                             linewidth=0.6,
                             width=0.5,
                             height=0.5,
                             fill=True,
                             alpha=0.8,
                             color=cmap(int(color_interp)))
        border = plt.Rectangle(xy=(x - 0.25, y - 0.25),
                               linewidth=0.2,
                               width=0.5,
                               height=0.5,
                               fill=False,
                               alpha=0.7,
                               color="#000088")
        ax.add_patch(rect)
        ax.add_patch(border)

    # format the colorbar
    divider = make_axes_locatable(ax)
    cax = divider.append_axes("right", size="3%", pad=0.05)
    cbar = matplotlib.colorbar.ColorbarBase(cax, cmap=cmap, norm=normalize)

    # save the figure and show it
    if (saveFig == True):
        plt.savefig(title + '.png', format='png', dpi=500, transparent=True)
    plt.show()
Beispiel #44
0
def plot_distribution(mode='lcc', plot_name=True):
    """绘制行政区域确诊分布数据
    
    mode        - 投影模式,可选项:
                -- 'lcc'            兰博托投影
                -- 'ortho'          正射投影
                -- 'etopo'          全球等经纬投影模式,etopo风格
                -- 'shadedrelief'   全球等经纬投影模式,shadedrelief风格
                -- 'bluemarble'     全球等经纬投影模式,bluemarble风格
    plot_name   - 是否打印行政区域名
    """

    data = catch_distribution()

    font_14 = FontProperties(fname='res/simsun.ttf', size=14)
    font_11 = FontProperties(fname='res/simsun.ttf', size=11)

    if mode in ['etopo', 'shadedrelief', 'bluemarble']:
        width = 1600
        height = 800
        rect = [0, 0, 1, 1]
        lat_min = -90
        lat_max = 90
        lon_min = 0
        lon_max = 360
    else:
        width = 1200
        height = 800
        rect = [0.1, 0.12, 0.8, 0.8]
        lat_min = 0
        lat_max = 60
        lon_min = 77
        lon_max = 140

    handles = [
        matplotlib.patches.Patch(color='#ffaa85', alpha=1, linewidth=0),
        matplotlib.patches.Patch(color='#ff7b69', alpha=1, linewidth=0),
        matplotlib.patches.Patch(color='#bf2121', alpha=1, linewidth=0),
        matplotlib.patches.Patch(color='#7f1818', alpha=1, linewidth=0),
    ]
    labels = ['1-9人', '10-99人', '100-999人', '>1000人']

    provincePos = {
        "辽宁省": [121.7, 40.9],
        "吉林省": [124.5, 43.5],
        "黑龙江省": [125.6, 46.5],
        "北京市": [116.0, 39.9],
        "天津市": [117.0, 38.7],
        "内蒙古自治区": [110.0, 41.5],
        "宁夏回族自治区": [105.2, 37.0],
        "山西省": [111.0, 37.0],
        "河北省": [114.0, 37.8],
        "山东省": [116.5, 36.0],
        "河南省": [111.8, 33.5],
        "陕西省": [107.5, 33.5],
        "湖北省": [111.0, 30.5],
        "江苏省": [119.2, 32.5],
        "安徽省": [115.5, 31.8],
        "上海市": [121.0, 31.0],
        "湖南省": [110.3, 27.0],
        "江西省": [114.0, 27.0],
        "浙江省": [118.8, 28.5],
        "福建省": [116.2, 25.5],
        "广东省": [113.2, 23.1],
        "台湾省": [120.5, 23.5],
        "海南省": [108.0, 19.0],
        "广西壮族自治区": [107.3, 23.0],
        "重庆市": [106.5, 29.5],
        "云南省": [101.0, 24.0],
        "贵州省": [106.0, 26.5],
        "四川省": [102.0, 30.5],
        "甘肃省": [103.0, 35.0],
        "青海省": [95.0, 35.0],
        "新疆维吾尔自治区": [85.5, 42.5],
        "西藏自治区": [85.0, 31.5],
        "香港特别行政区": [115.1, 21.2],
        "澳门特别行政区": [112.5, 21.2]
    }

    fig = matplotlib.figure.Figure()
    fig.set_size_inches(width / 100, height / 100)  # 设置绘图板尺寸
    axes = fig.add_axes(rect)

    if mode == 'lcc':  # 兰博托投影模式
        m = Basemap(projection='lcc',
                    llcrnrlon=77,
                    llcrnrlat=14,
                    urcrnrlon=140,
                    urcrnrlat=51,
                    lat_1=33,
                    lat_2=45,
                    lon_0=100,
                    ax=axes)

        # 兰博托投影模式,全图
        #m = Basemap(projection='lcc', llcrnrlon=80, llcrnrlat=0, urcrnrlon=140, urcrnrlat=51, lat_1=33, lat_2=45, lon_0=100, ax=axes)
    elif mode == 'ortho':  # 正射投影模式
        m = Basemap(projection='ortho',
                    lat_0=36,
                    lon_0=102,
                    resolution='l',
                    ax=axes)
    else:  # 全球等经纬投影模式,
        m = Basemap(llcrnrlon=lon_min,
                    urcrnrlon=lon_max,
                    llcrnrlat=lat_min,
                    urcrnrlat=lat_max,
                    resolution='l',
                    ax=axes)
        if mode == 'etopo':
            m.etopo()
        elif mode == 'shadedrelief':
            m.shadedrelief()
        else:
            m.bluemarble()

    m.readshapefile('res/china-shapefiles-master/china',
                    'province',
                    drawbounds=True)
    m.readshapefile('res/china-shapefiles-master/china_nine_dotted_line',
                    'section',
                    drawbounds=True)
    m.drawcoastlines(color='black')  # 洲际线
    m.drawcountries(color='black')  # 国界线

    if mode in ['etopo', 'shadedrelief', 'bluemarble']:
        m.drawparallels(np.arange(lat_min, lat_max, 30), labels=[1, 0, 0,
                                                                 0])  #画经度线
        m.drawmeridians(np.arange(lon_min, lon_max, 30), labels=[0, 0, 0,
                                                                 1])  #画纬度线
    else:
        m.drawparallels(np.arange(lat_min, lat_max, 10), labels=[1, 0, 0,
                                                                 0])  #画经度线
        m.drawmeridians(np.arange(lon_min, lon_max, 10), labels=[0, 0, 0,
                                                                 1])  #画纬度线

    pset = set()
    for info, shape in zip(m.province_info, m.province):
        pname = info['OWNER'].strip('\x00')
        fcname = info['FCNAME'].strip('\x00')
        if pname != fcname:  # 不绘制海岛
            continue

        for key in data.keys():
            if key in pname:
                if data[key] == 0:
                    color = '#f0f0f0'
                elif data[key] < 10:
                    color = '#ffaa85'
                elif data[key] < 100:
                    color = '#ff7b69'
                elif data[key] < 1000:
                    color = '#bf2121'
                else:
                    color = '#7f1818'
                break

        poly = Polygon(shape, facecolor=color, edgecolor=color)
        axes.add_patch(poly)

        if plot_name:
            pos = provincePos[pname]
            text = pname.replace("自治区", "").replace("特别行政区", "").replace(
                "壮族", "").replace("维吾尔",
                                  "").replace("回族",
                                              "").replace("省",
                                                          "").replace("市", "")
            if text not in pset:
                x, y = m(pos[0], pos[1])
                axes.text(x, y, text, fontproperties=font_11, color='#00FFFF')
                pset.add(text)

    axes.legend(handles,
                labels,
                bbox_to_anchor=(0.5, -0.11),
                loc='lower center',
                ncol=4,
                prop=font_14)
    axes.set_title("2019-nCoV疫情地图", fontproperties=font_14)
    FigureCanvasAgg(fig)
    fig.savefig('fb/2019-nCoV疫情地图_%s.png' % mode)
Beispiel #45
0
normalize = matplotlib.colors.Normalize(vmin = cap_min,vmax = cap_max)

loop_size = len(year_sort)
num_gifs = len(np.unique(year_sort))

for pp in range(0,loop_size):
    if year_sort[pp]==curr_year:
        x,y = m(lons_sort[pp],lats_sort[pp])
        x_array.append(x)
        y_array.append(y)
        cap_array.append(np.interp(capacity_sort[pp],[cap_min,cap_max],[30,200]))
        color_array.append(capacity_sort[pp])
        if pp!=loop_size-1:
            continue
    else:
        curr_year = year_sort[pp]

    # recreate figure each loop
    fig = plt.figure(figsize=(12,7))
    m = Basemap(projection='merc',llcrnrlat=bbox[0],urcrnrlat=bbox[1],\
                llcrnrlon=bbox[2],urcrnrlon=bbox[3],lat_ts=10,resolution=None)
    m.bluemarble() # this plots the earth-like contour to the U.S. map

    # scatter new data with the color and size changes
    scat1 = plt.scatter(x_array,y_array,s=cap_array,c = color_array,edgecolors='#444444',alpha=0.5,cmap=colormap,norm=normalize)
    plt.colorbar(scat1,label='Average Power [kW]')
    plt.ylabel(str(year_sort[pp-1])) # updated year

    gif_maker('wind_turbine_yearly_with_colors.gif',png_dir,gif_indx,num_gifs,90)
    gif_indx+=1
Beispiel #46
0
            llcrnrlat=-90,
            urcrnrlat=90,
            llcrnrlon=-180,
            urcrnrlon=180,
            resolution='c')

m.drawcountries()
m.drawcoastlines()

user_des = mapTypes()

if (user_des == 1):
    m.drawmapboundary(fill_color='aqua')
    m.fillcontinents(color='lightgreen', lake_color='aqua', alpha=1)
elif (user_des == 2):
    m.bluemarble(scale=0.2)
elif (user_des == 3):
    m.drawlsmask()
elif (user_des == 4):
    m.shadedrelief(scale=0.07)
else:
    sys.exit()

m.drawparallels(np.arange(-90, 90, 10), labels=[True, False, False, False])
m.drawmeridians(np.arange(-180, 180, 30), labels=[False, False, False, True])

plot.title('Current ISS-Location', fontsize=20)

#Main cycle
while (True):
    os.system("cls")
def plotExtremeGlobal(metric):
    """
    this function plots the chosen metric 
    globallly using the basemap library

    metric = {'corr', 'rmse', 'nse'}

    """
    #call processData here
    if metric == 'corr':
        dat = starter()[0]
        #remove tg that have negative correlation
        dat = dat[~(dat['Correlation'] < 0)]
        varToPlot = 'Correlation'
        title = 'Pearson\'s Correlation - 1980-2010 - above 95%ile'
        bubbleSizeMultiplier = 250
    elif metric == 'nse':
        dat = starter()[2]
        varToPlot = 'NSE(%)'
        title = 'NSE - 1980-2010'
        bubbleSizeMultiplier = 900
    else:
        dat = starter()[1]
        varToPlot = 'RMSE(cm)'
        title = 'RMSE(cm) - 1980-2010 - above 95%ile'
        bubbleSizeMultiplier = 4

    #increase plot font size
    sns.set_context('notebook', font_scale=1.5)

    plt.figure(figsize=(20, 10))
    m = Basemap(projection='cyl',
                lat_ts=20,
                llcrnrlon=-180,
                urcrnrlon=180,
                llcrnrlat=-90,
                urcrnrlat=90,
                resolution='c')
    x, y = m(dat['lon'].tolist(), dat['lat'].tolist())
    m.drawcoastlines()

    #draw parallels and meridians
    parallels = np.arange(-80, 81, 20.)
    meridians = np.arange(-180., 180., 40.)
    m.drawparallels(parallels, labels=[True, False, False, False], linewidth=0)
    m.drawparallels(parallels,
                    labels=[True, True, False, False],
                    linewidth=0.5)
    m.drawmeridians(meridians,
                    labels=[False, False, False, True],
                    linewidth=0.5)
    m.bluemarble(alpha=0.8)

    #define markers
    markers = {
        "20CR": "o",
        "ERA-20C": "o",
        "ERA-Interim": 'o',
        "MERRA": 'o',
        "ERA-FIVE": 'o'
    }
    #define palette
    color_dict = dict({
        '20CR': 'green',
        'ERA-20C': 'magenta',
        'ERA-Interim': 'black',
        'MERRA': 'red',
        'ERA-FIVE': 'aqua'
    })
    #define bubble sizes
    minSize = min(dat[varToPlot]) * bubbleSizeMultiplier
    if minSize < 0:
        minSize = 0
    maxSize = max(dat[varToPlot]) * bubbleSizeMultiplier

    sns.scatterplot(x = x, y = y, markers = markers, style = 'Reanalysis',\
                    size = varToPlot, sizes=(minSize, maxSize),\
                        hue = 'Reanalysis',  palette = color_dict, data = dat)
    plt.legend(loc='lower left', ncol=12)
    plt.title(title)
    os.chdir(
        "G:\\data\\allReconstructions\\validation\\commonPeriodValidationExtremes\\percentile\\plotFiles"
    )
    saveName = 'allReanalysesExtremes' + metric + '.svg'
def plotonmap(obs,
              sun_lat,
              sun_lon,
              city_lat,
              city_lon,
              city,
              projection='ortho',
              redraw=False,
              bluemarble=False):
    if os.path.exists("movies/%s.mp4" % city):
        return

    filename = "images/%s/plot_%s_00.png" % (
        city, obs.date.datetime().strftime("%Y%m%d"))

    if not redraw and os.path.exists(filename):
        return
    else:
        plt.style.use('dark_background')
        plt.figure(figsize=(19.2, 10.80))
        m = Basemap(projection=projection,
                    resolution='l',
                    lat_0=20,
                    lon_0=city_lon)
        m.bluemarble()

        # draw terminator
        _ = m.nightshade(
            obs.date.datetime(),
            delta=0.7,
            alpha=0.5,
        )

        # draw tropics and equator
        draw_parallel(m,
                      23.5,
                      city_lon,
                      color='ivory',
                      label="Tropic of\nCancer")
        draw_parallel(m,
                      -23.5,
                      city_lon,
                      color='ivory',
                      label="Tropic of\nCapricorn")
        draw_parallel(m, 0, city_lon, color='ivory', label='Equator')

        # mark city
        citydot(m, city_lat, city_lon, 'white')

        # mark sun position
        sundot(m, sun_lat, sun_lon, 'y', label='subsolar')
        draw_parallel(m, sun_lat, city_lon, color='yellow')

        datestring = obs.date.datetime().strftime("%Y-%m-%d")
        frames = 1
        if '6-21' in datestring or '12-21' in datestring or '6-.8020' in datestring:
            datestring += " Solstice"
            frames = 20
        if '3-19' in datestring or '9-23' in datestring:
            datestring += " Equinox"
            frames = 40
        plt.annotate(datestring,
                     xy=(10, 10),
                     fontsize=20,
                     textcoords='data',
                     color='w')
        plt.savefig(filename, transparent=True)
        plt.close()
        from PIL import Image
        fg = Image.open(filename, 'r')
        bg = Image.open('starfield.png', 'r')
        text_img = Image.new('RGBA', (1920, 1080), (0, 0, 0, 0))
        text_img.paste(bg, (0, 0))
        text_img.paste(fg, (0, 0), mask=fg)
        text_img.save(filename, format="png")

        for x in range(1, frames):
            filename2 = "images/%s/plot_%s_%02d.png" % (
                city, obs.date.datetime().strftime("%Y%m%d"), x)
            shutil.copyfile(filename, filename2)
Beispiel #49
0
countcluster = np.bincount(labels[labels >= 0])

indexlength = np.size(countcluster)

rangetobeindexed = np.arange(indexlength)

newarr = np.column_stack((countcluster, rangetobeindexed))

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

#increase/decrease figure size
plt.figure(figsize=(12, 6))

#set latitude longitude for rotation,set areathresh for better details ,set resolution
map = Basemap(projection='robin', lat_0=0, lon_0=0, area_thresh=1000)
map.bluemarble(scale=0.3)

#to draw countires
map.drawcountries()

#draw longitude and latitude lines
map.drawmeridians(np.arange(0, 360, 30))
map.drawparallels(np.arange(-90, 90, 30))

#map.drawmapboundary(fill_color='aqua')

#use below line for coloring continent
#map.fillcontinents(color='coral',lake_color='aqua')

#to draw border around continets
map.drawcoastlines()
Beispiel #50
0
def plotContoursOverHSTTrack(data, hst_start, hst_stop, tlefile, ephemerisOnline = False, SAA_zoomed = False, hold_on = False):
    num_points = int((hst_stop - hst_start)/ephem.minute) + 1
    
    # Read in the HST Two-Line ephemeris
    if ephemerisOnline:
        import urllib2
        hand = urllib2.open('http://celestrak.com/NORAD/elements/science.txt')
        data = hand.readlines()
        hand.close()
        HST = [[d[val], d[val+1], d[val+2]] for val, line in enumerate(d) if 'HST' in line]
        hst = ephem.readtle(string.strip(HST[0][0]), string.strip(HST[0][1]), string.strip(HST[0][2]))
    else:
        temp = open(tlefile, 'r').readlines()
        hst = ephem.readtle(string.strip(temp[0]), string.strip(temp[1]), string.strip(temp[2]))
                        
    cur_time = hst_start
    
    hst_longs = []
    hst_lats  = []
    for i in range(0,num_points):
        hst.compute(cur_time)
        hst_longs.append(hst.sublong.znorm*180.0/math.pi)
        hst_lats.append(hst.sublat*180.0/math.pi)
        cur_time = cur_time + ephem.minute
        
    hst_longs = N.array(hst_longs)
    hst_lats = N.array(hst_lats)
    
    #projection
    lon_0 = 335
    lat_0 = -20
    llcrnrlat = -60
    llcrnrlon = -100
    urcrnrlat = 20
    urcrnrlon = 60
    # use these values to setup Basemap instance.
    width  = 14000000
    height = 10000000
    
    #SAA
    if SAA_zoomed:
        m = Basemap(width = width, height = height, resolution = 'c', projection = 'aeqd', lat_0 = lat_0, lon_0 = lon_0)
        sz = 100
    else:
        m = Basemap(resolution='c', projection='mbtfpq', lon_0 = lon_0)
        sz = 35
    #OTHER PROJECTIONS    
    # crashed?
    #m = Basemap(resolution='c', projection='aeqd', lat_0 = lat_0, lon_0 = lon_0)
    # Full map, good
    #m = Basemap(resolution='c', projection='mbtfpq', lon_0 = lon_0)
    # Full map, diff projection
    #m = Basemap(resolution='c', projection='moll', lon_0 = lon_0)
    # Globe, SAA well presented
    #m = Basemap(resolution='c', projection='ortho', lon_0 = lon_0, lat_0 = lat_0)
    # Square, SAA well presented.
    #m = Basemap(resolution='c',projection='cyl',llcrnrlat=llcrnrlat,llcrnrlon=llcrnrlon,urcrnrlat=urcrnrlat,urcrnrlon=urcrnrlon)
    
    p = FontProperties()
    font1 = p.copy()
    font1.set_size('small')
    
    # draw coasts and fill continents.
    m.drawcoastlines(linewidth = 0.5)
    #m.fillcontinents()
    
    m.drawparallels(arange(-80,81,10),labels=[1,1,0,0],fontproperties=font1,labelstyle="+/-")
    m.drawmeridians(arange(-180,180,20),labels=[0,0,0,1],fontproperties=font1,labelstyle="+/-")
    
    m.bluemarble()
    m.drawmapboundary()
    
    # SAA 02
    x2,y2 = m([357.4-360,357.6-360,356.9-360,355.0-360,352.3-360,348.7-360,342.9-360,336.4-360,324.8-360,303.2-360,292.1-360,289.0-360,285.9-360,283.5-360,282.5-360,282.4-360,282.7-360,357.4-360], \
              [-28.3,-26.1,-23.7,-21.2,-18.8,-16.3,-13.0,-10.6, -9.1,-11.9,-14.9,-17.0,-19.1,-21.3,-23.7,-26.0,-28.6,-28.3])
    # SAA 03
    x3,y3 = m([ 20.0, 21.0, 19.0, 7.5,347.0-360,336.4-360,324.8-360,303.2-360,292.1-360,285.9-360,283.5-360,282.5-360,282.4-360,282.7-360, 20.0], \
              [-28.3,-27.5,-26.1,-19.8, -9.6, -7.6, -6.0, -7.9,-12.0,-17.1,-20.3,-23.5,-26.0,-28.6,-28.3])
    # SAA 04
    x4,y4 = m([ 25.0,  7.0,351.0-360,341.0-360,318.0-360,300.0-360,290.0-360,284.0-360,278.0-360,273.0-360,275.0-360, 25.0], \
              [-28.5,-16.0, -6.5, -2.0,  1.0, -3.0, -7.0,-10.0,-15.0,-20.0,-30.0,-28.5])
    # SAA 05,23
    x5,y5 = m([300.0-360, 45.0, 40.0, 30.0, 10.0, 0.0,341.0-360,318.0-360,300.0-360,283.0-360,273.0-360,275.0-360,300.0-360], \
              [-50.0,-30.0,-25.0,-21.0,-15.0,-10.2, -2.0,  1.0, -3.0, -8.0,-20.0,-30.0,-50.0])
    # SAA 06
    x6,y6 = m([ 20.0, 21.0, 19.0, 7.5,347.0-360,336.4-360,324.8-360,303.2-360,292.1-360,285.9-360,283.5-360,282.5-360,282.4-360,282.7-360, 20.0], \
              [-28.3,-27.5,-26.1,-19.8, -9.6, -7.6, -6.0, -7.9,-12.0,-17.1,-20.3,-23.5,-26.0,-28.6,-28.3])

    #SAA
    saa02 = m.plot(x2,y2,marker='D',markersize=4.0,markeredgewidth=0.0,color='turquoise',linestyle='-',label='02')
    saa03 = m.plot(x3,y3,marker='v',markersize=4.0,markeredgewidth=0.0,color='white',linestyle='-',label='03')
    saa04 = m.plot(x4,y4,marker='^',markersize=4.0,markeredgewidth=0.0,color='orange',linestyle='-',label='04')
    saa05 = m.plot(x5,y5,marker='s',markersize=4.0,markeredgewidth=0.0,color='green',linestyle='-',label='05')
    saa06 = m.plot(x6,y6,marker='x',markersize=4.0,markeredgewidth=1.0,color='magenta',linestyle='-',label='06')
    
    # HST observation ground track
    xhst, yhst = m(hst_longs, hst_lats)    
    #hst = m.plot(xhst,yhst,marker='+',markersize=4.0,markeredgewidth=1.0,color='red',linestyle='-',linewidth=0.7,label='hst')
    
    #scatter plot
    if hold_on:
        scatter = m.scatter(xhst[:-1], yhst[:-1], s = sz, c = data, cmap = cm.jet, linestyle = 'solid', zorder = 11, hold = 'on')
    else:
        fig = P.figure(1)
        points = N.array([xhst, yhst]).T.reshape(-1, 1, 2)
        segments = N.concatenate([points[:-1], points[1:]], axis=1)
        ax = P.axes()
        lc = LineCollection(segments, cmap = P.get_cmap('jet'), norm = P.Normalize(0, 10000))
        lc.set_array(data)
        lc.set_linewidth(5)
        
        ax.add_collection(lc)
        
        axcb = fig.colorbar(lc)
        axcb.set_label('EVENTS')

    #contour plot
    #cs = m.contour(xhst, yhst, data, 15, linewidths = 1.5)    
    #mx = N.max(data)
    #cbar = map.colorbar(s, ticks=[N.max(data), mx//2., mx], orientation='vertical')
    
    hst_label = 'HST once per minute'
    
    font = p.copy()
    #font.set_size('xx-small')
    font.set_size('small')
    leg=legend((saa02,saa03,saa04,saa05,saa06,hst), \
           ('PASS SAA Level 1 - FGS Guidance & STIS LV', \
            'PASS SAA Level 2 - STIS', \
            'PASS SAA Level 3 - ACS & WFC3', \
            'PASS SAA Level 4 - Astrometry & NICMOS', \
            'PASS SAA Level 5 - COS', \
            hst_label), \
           prop=font,numpoints=2,borderpad=0.3,loc='upper center',borderaxespad=0.0,ncol=2)
    leg.get_frame().set_alpha(0.7)
    # draw the title.
    P.title('HST from %s to %s' % (str(arg1),str(arg2)))
    
    if hold_on == False: P.show()
Beispiel #51
0
def plotHSTtrack(hst_start, hst_stop, tlefile, ephemerisOnline = False):
    num_points = int((hst_stop - hst_start)/ephem.minute) + 1
    
    # Read in the HST Two-Line ephemeris
    if ephemerisOnline:
        import urllib2
        hand = urllib2.open('http://celestrak.com/NORAD/elements/science.txt')
        data = hand.readlines()
        hand.close()
        HST = [[d[val], d[val+1], d[val+2]] for val, line in enumerate(d) if 'HST' in line]
        hst = ephem.readtle(string.strip(HST[0][0]), string.strip(HST[0][1]), string.strip(HST[0][2]))
    else:
        temp = open(tlefile, 'r').readlines()
        hst = ephem.readtle(string.strip(temp[0]), string.strip(temp[1]), string.strip(temp[2]))
                        
    cur_time = hst_start
    
    hst_longs = []
    hst_lats  = []
    for i in range(0,num_points):
        hst.compute(cur_time)
        hst_longs.append(hst.sublong.znorm*180.0/math.pi)
        hst_lats.append(hst.sublat*180.0/math.pi)
        cur_time = cur_time + ephem.minute
    
    lon_0 = 335
    lat_0 = -20
    llcrnrlat = -60
    llcrnrlon = -100
    urcrnrlat = 20
    urcrnrlon = 60
    
    # use these values to setup Basemap instance.
    width  = 14000000
    height = 10000000
    #m = Basemap(width=width,height=height,\
    #            resolution='c',projection='aeqd',\
    #            lat_0=lat_0,lon_0=lon_0)
    #m = Basemap(resolution='c',projection='aeqd',lat_0=lat_0,lon_0=lon_0)
    #m = Basemap(width=width,height=height,\
    #            resolution='c',projection='aea',\
    #            lat_0=lat_0,lon_0=lon_0)
    m = Basemap(resolution='c', projection='mbtfpq', lon_0=lon_0)
    #m = Basemap(resolution='c',projection='moll',lon_0=lon_0)
    #m = Basemap(resolution='c',projection='ortho',lon_0=lon_0,lat_0=lat_0)
    #m = Basemap(resolution='c',projection='cyl',llcrnrlat=llcrnrlat,llcrnrlon=llcrnrlon,urcrnrlat=urcrnrlat,urcrnrlon=urcrnrlon)
    
    p = FontProperties()
    font1 = p.copy()
    font1.set_size('small')
    
    # draw coasts and fill continents.
    m.drawcoastlines(linewidth = 0.5)
    #m.fillcontinents()
    
    m.drawparallels(arange(-80,81,10),labels=[1,1,0,0],fontproperties=font1,labelstyle="+/-")
    m.drawmeridians(arange(-180,180,20),labels=[0,0,0,1],fontproperties=font1,labelstyle="+/-")
    
    m.bluemarble()
    m.drawmapboundary()
    
    # SAA 02
    x2,y2 = m([357.4-360,357.6-360,356.9-360,355.0-360,352.3-360,348.7-360,342.9-360,336.4-360,324.8-360,303.2-360,292.1-360,289.0-360,285.9-360,283.5-360,282.5-360,282.4-360,282.7-360,357.4-360], \
              [-28.3,-26.1,-23.7,-21.2,-18.8,-16.3,-13.0,-10.6, -9.1,-11.9,-14.9,-17.0,-19.1,-21.3,-23.7,-26.0,-28.6,-28.3])
    # SAA 03
    #x3,y3 = m([294.4-360,301.4-360,350.0-360,358.4-360,335.8-360,304.6-360,295.5-360,279.4-360,282.6-360,294.4-360], \
    #          [-41.0,-42.8,-30.0,-20.9,-4.9,-4.9,-7.0,-21.9,-32.7,-41.0])
    x3,y3 = m([ 20.0, 21.0, 19.0,  7.5,347.0-360,336.4-360,324.8-360,303.2-360,292.1-360,285.9-360,283.5-360,282.5-360,282.4-360,282.7-360, 20.0], \
              [-28.3,-27.5,-26.1,-19.8, -9.6, -7.6, -6.0, -7.9,-12.0,-17.1,-20.3,-23.5,-26.0,-28.6,-28.3])
    # SAA 04
    #x4,y4 = m([335.0-360,345.0-360,349.0-360,346.0-360,330.0-360,314.0-360,310.0-360,303.0-360,310.0-360,325.0-360,335.0-360], \
    #          [-33.0,-27.0,-24.0,-23.0,-25.0,-30.0,-32.2,-39.0,-40.0,-37.0,-33.0])
    x4,y4 = m([ 25.0,  7.0,351.0-360,341.0-360,318.0-360,300.0-360,290.0-360,284.0-360,278.0-360,273.0-360,275.0-360, 25.0], \
              [-28.5,-16.0, -6.5, -2.0,  1.0, -3.0, -7.0,-10.0,-15.0,-20.0,-30.0,-28.5])
    # SAA 05,23
    x5,y5 = m([300.0-360, 45.0, 40.0, 30.0, 10.0,  0.0,341.0-360,318.0-360,300.0-360,283.0-360,273.0-360,275.0-360,300.0-360], \
              [-50.0,-30.0,-25.0,-21.0,-15.0,-10.2, -2.0,  1.0, -3.0, -8.0,-20.0,-30.0,-50.0])
    # SAA 06
    #x6,y6 = m([359.0-360,360.0-360,335.4-360,323.0-360,290.0-360,280.0-360,276.0-360,280.0-360,359.0-360], \
    #          [-28.0,-20.9,-3.4,-0.0,-7.0,-12.6,-20.9,-30.0,-28.0])
    x6,y6 = m([ 20.0, 21.0, 19.0,  7.5,347.0-360,336.4-360,324.8-360,303.2-360,292.1-360,285.9-360,283.5-360,282.5-360,282.4-360,282.7-360, 20.0], \
              [-28.3,-27.5,-26.1,-19.8, -9.6, -7.6, -6.0, -7.9,-12.0,-17.1,-20.3,-23.5,-26.0,-28.6,-28.3])
    # SAA 07
    x7,y7 = m([300.0-360,359.0-360,5.0,341.0-360,318.0-360,300.0-360,283.0-360,273.0-360,275.0-360,300.0-360], \
              [-50.0,-41.0,-23.0,-2.0,1.0,-3.0,-8.0,-20.0,-30.0,-50.0])
    # SAA 24,25,28,31,32
    x24,y24=m([ 20.0, 21.0, 19.0,  7.5,347.0-360,336.4-360,324.8-360,303.2-360,292.1-360,285.9-360,283.5-360,282.5-360,282.4-360,282.7-360, 20.0], \
              [-28.3,-27.5,-26.1,-19.8, -9.6, -7.6, -6.0, -7.9,-12.0,-17.1,-20.3,-23.5,-26.0,-28.6,-28.3])
    # SAA 26,27,29,30
    x26,y26=m([ 25.0,  7.0,351.0-360,341.0-360,318.0-360,300.0-360,290.0-360,284.0-360,278.0-360,273.0-360,275.0-360, 25.0], \
              [-28.5,-16.0, -6.5, -2.0,  1.0, -3.0, -7.0,-10.0,-15.0,-20.0,-30.0,-28.5])
    # HST observation ground track
    xhst,yhst = m(hst_longs, hst_lats)
    
    saa02 = m.plot(x2,y2,marker='D',markersize=4.0,markeredgewidth=0.0,color='turquoise',linestyle='-',label='02')
    saa03 = m.plot(x3,y3,marker='v',markersize=4.0,markeredgewidth=0.0,color='white',linestyle='-',label='03')
    saa04 = m.plot(x4,y4,marker='^',markersize=4.0,markeredgewidth=0.0,color='orange',linestyle='-',label='04')
    saa05 = m.plot(x5,y5,marker='s',markersize=4.0,markeredgewidth=0.0,color='green',linestyle='-',label='05')
    saa06 = m.plot(x6,y6,marker='x',markersize=4.0,markeredgewidth=1.0,color='magenta',linestyle='-',label='06')
    #saa07 = m.plot(x7,y7,marker='>',markersize=4.0,markeredgewidth=0.0,color='darkorchid',linestyle='-',label='07')
    #saa24 = m.plot(x24,y24,marker='x',markersize=4.0,markeredgewidth=1.0,color='green',linestyle='-',label='24') 
    #saa26 = m.plot(x26,y26,marker='^',markersize=4.0,markeredgewidth=0.0,color='maroon',linestyle='-',label='26')
    
    hst = m.plot(xhst,yhst,marker='+',markersize=4.0,markeredgewidth=1.0,color='red',linestyle='-',linewidth=0.7,label='hst')
    #SMN:
    #cnts must be sampled similar as xhst and yhst!
    #cs = m.contour(xhst,yhst,cnts,15,linewidths=1.5)
    
    hst_label = 'HST once per minute'
    
    font = p.copy()
    #font.set_size('xx-small')
    font.set_size('small')
    leg=legend((saa02,saa03,saa04,saa05,saa06,hst), \
           ('PASS SAA Level 1 - FGS Guidance & STIS LV', \
            'PASS SAA Level 2 - STIS', \
            'PASS SAA Level 3 - ACS & WFC3', \
            'PASS SAA Level 4 - Astrometry & NICMOS', \
            'PASS SAA Level 5 - COS', \
            #'07 - GHRS', \
            #'24/25/31/32 - STIS CCD/STIS MAMA/COS FUV/COS NUV', \
            #'26/27/28/29/30 - WFPC2/ACS CCD/ACS SBC/WFC3 UVIS/WFC3 IR', \
            hst_label), \
           prop=font,numpoints=2,borderpad=0.3,loc='upper center',borderaxespad=0.0,ncol=2)
    leg.get_frame().set_alpha(0.7)
    #figlegend((saa02,saa05,saa24,saa26),('02','05','24','26'),'upper right')
    # draw the title.
    title('HST from %s to %s' % (str(arg1),str(arg2)))
    show()
Beispiel #52
0
def plotRSPlatlon_winput(data_dir, subdir, f_date, platform, lat_1, lat_2,
                         lat_0, lon_0, m_width, m_height):

    # import moduls
    import numpy as np
    import scipy as sio
    from os import listdir
    from os.path import isfile, join
    from os import walk
    import pandas as pd
    import glob
    import matplotlib
    import matplotlib.pyplot as plt
    import matplotlib.colors as colors
    from matplotlib import cm
    from matplotlib import gridspec
    from matplotlib.collections import LineCollection
    from matplotlib.patches import Polygon
    from matplotlib.patches import Polygon
    from mpl_toolkits.basemap import Basemap
    from mpl_toolkits.axes_grid1 import make_axes_locatable
    import shapefile
    get_ipython().magic(u'matplotlib inline')

    # list all files in folder to plot
    expres = data_dir + subdir + '//' + f_date + "T*lut_scale*.txt"
    flist = glob.glob(expres)
    print "files to process: "
    print flist

    ## initialize arrays
    data = pd.DataFrame([])
    # read and concatanate files:
    for f in range(len(flist)):
        print flist[f]
        if (platform == "ER-2"):
            tmp = pd.read_table(flist[f],
                                sep='\s+',
                                header=None,
                                names=[
                                    "UTC_hr", "Alt_m", "Latitude", "Longitude",
                                    "SZA", "RelativeAzimuth",
                                    "Effective_Radius", "Effective_Variance",
                                    "COT"
                                ])
        elif (platform == "P-3"):
            tmp = pd.read_table(flist[f],
                                sep='\s+',
                                header=None,
                                names=[
                                    "UTC_hr", "Latitude", "Longitude", "Alt_m",
                                    "SZA", "RelativeAzimuth",
                                    "Effective_Radius", "Effective_Variance",
                                    "COT"
                                ])

        print tmp.head()
        # concat arrays
        data = data.append(pd.DataFrame(tmp))
        print "tmp.shape"
        print tmp.shape

    print "data.shape"
    print data.shape

    ## plot lat/lon with COT/Reff
    ##---------------------------

    fig, axes = plt.subplots(1, 2)

    projection = 'lcc'
    #llcrnrlon  = -5
    #llcrnrlat  = -30
    #urcrnrlon  = 20
    #urcrnrlat  = 5
    resolution = 'i'
    # ORACLES 2016
    #lat_1 = -30.
    #lat_2 = 5.
    #lat_0 = -15.
    #lon_0 = 5.
    m_min = lon_0 + (-10.)
    m_max = lon_0 + 15.

    parallels = np.arange(lat_1, lat_2, 5)
    meridians = np.arange(m_min, m_max, 5)

    # the fisrt subplot - COT
    axes[0].set_title('COT ' + f_date)
    m0 = Basemap(width=m_width,
                 height=m_height,
                 projection=projection,
                 lat_1=lat_1,
                 lat_2=lat_2,
                 lat_0=lat_0,
                 lon_0=lon_0,
                 resolution=resolution,
                 ax=axes[0])
    m0.bluemarble(scale=0.25)
    m0.drawparallels(parallels, labels=[1, 0, 0, 0], fontsize=8, linewidth=1.)
    m0.drawmeridians(meridians, labels=[0, 0, 0, 1], fontsize=8, linewidth=1.)

    # the fisrt subplot - COT
    axes[1].set_title('Effective Radius ' + f_date)
    m1 = Basemap(width=m_width,
                 height=m_height,
                 projection=projection,
                 lat_1=lat_1,
                 lat_2=lat_2,
                 lat_0=lat_0,
                 lon_0=lon_0,
                 resolution=resolution,
                 ax=axes[1])
    m1.bluemarble(scale=0.25)
    m1.drawparallels(parallels, labels=[1, 0, 0, 0], fontsize=8, linewidth=1.)
    m1.drawmeridians(meridians, labels=[0, 0, 0, 1], fontsize=8, linewidth=1.)

    #plt.title(f_date, fontsize=16)

    # read lats and lons (representing centers of grid boxes).
    lats = np.array(data['Latitude'])
    lons = np.array(data['Longitude'])
    dat0 = np.array(data['COT'])
    dat1 = np.array(data['Effective_Radius'])

    # create an axes on the bottom/right etc. side of ax. The width of cax will be 5%
    # of ax and the padding between cax and ax will be fixed at 0.05 inch.
    divider0 = make_axes_locatable(axes[0])
    #cax0 = divider0.append_axes("bottom", size="5%", pad=0.05)
    cax0 = divider0.append_axes("bottom", size="5%", pad=0.30)

    divider1 = make_axes_locatable(axes[1])
    cax1 = divider1.append_axes("bottom", size="5%", pad=0.30)

    #plt.colorbar(im, cax=cax)

    map0 = m0.scatter(lons, lats, c=dat0, cmap=plt.cm.OrRd,
                      latlon=True)  #plt.cm.gist_ncar
    cbar0 = plt.colorbar(map0,
                         ticks=[0, 5, 10, 15, 20, 25, 30],
                         cax=cax0,
                         orientation='horizontal')

    map1 = m1.scatter(lons, lats, c=dat1, cmap=plt.cm.OrRd, latlon=True)
    cbar1 = plt.colorbar(map1,
                         ticks=[0, 5, 10, 15, 20],
                         cax=cax1,
                         orientation='horizontal')

    #cbar.set_label(cbar_title, fontsize = 14)3 orientation='horizontal'
    plt.show()

    #fig.savefig(filepath + title + '.png')

    # save figure
    # as pdf
    fi1 = '../../py_figs/oracles_NN/' + 'NN_RSP_' + f_date + "_" + platform + '_cot_reff_latlon_' + subdir + '.pdf'
    #fig = matplotlib.pyplot.gcf()
    #fig.set_size_inches(13, 9, forward=True)
    fig.savefig(fi1, bbox_inches='tight', dpi=1000)
    # as png
    fi2 = '../../py_figs/oracles_NN/' + 'NN_RSP_' + f_date + "_" + platform + '_cot_reff_latlon_' + subdir + '.png'
    #fig = matplotlib.pyplot.gcf()
    #fig.set_size_inches(13, 9, forward=True)
    fig.savefig(fi2, bbox_inches='tight', dpi=1000)
    # or set axes interactively
    #for ax in fig.axes:
    #    ax.set_xlim(10, 20)

    return
Beispiel #53
0
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt

peta = Basemap(projection='merc',
               lat_0=0,
               lon_0=125,
               resolution='l',
               area_thresh=0.1,
               llcrnrlon=90,
               llcrnrlat=-15,
               urcrnrlon=155,
               urcrnrlat=15)

plt.figure()
peta.drawcoastlines()
peta.drawcountries()
peta.bluemarble()

lon = [
    107.668710,
    107.668663,
    107.668610,
    107.574970,
    107.575090,
]
lat = [-6.972280, -6.972270, -6.972270, -6.943540, -6.943390]
x, y = peta(lon, lat)
peta.plot(x, y, 'ro', markersize=5)

plt.show()
places['lon'] = None

geolocator = Nominatim()
for index, row in places.iterrows():
    if index > 1347:
        counter = counter + 1
        city = row['city']
        location = geolocator.geocode(city)
        if hasattr(location, 'latitude') and hasattr(location, 'longitude'):
            row['lat'] = location.latitude
            row['lon'] = location.longitude
            print location.latitude, location.longitude, index
        else:
            row['lat'] = None
            row['lon'] = None
            print "Invalid Address", index
        sleep(0.8)
    else:
        pass

places = places.dropna(how='any')
places.to_csv('geo.csv')

fix, ax = plt.subplots(figsize=(14, 8))
earth = Basemap()
earth.bluemarble(alpha=0.3)
earth.drawcoastlines(color='#555566', linewidth=1)
ax.scatter(places['lon'], places['lat'], 8, c='red', alpha=0.5, zorder=10)
ax.set_xlabel("Tweets about #Facebook")
plt.savefig('tweets2.png', dpi=350, bbox_inches='tight')
def plotMetricVariance(metric):
    """
    this function plots the variance of 
    the validation metrics for the reconstructed
    surges
    """

    #directories for the common period validation
    csvPath = "G:\\data\\allReconstructions\\validation\\commonPeriodValidationExtremes\\percentile"
    os.chdir(csvPath)

    #define validation output files
    validationFiles = {
        'corr': 'allCorr.csv',
        'rmse': 'allRMSE.csv',
        'nnse': 'allNNSE.csv',
        'rrmse': 'RRMSEOnly.csv'
    }

    chosenMetric = validationFiles[metric]

    #read the validation file of choice
    dat = pd.read_csv(chosenMetric)
    #compute standard deviation of metrics for all reanalysis
    metricColumns = dat[[
        '20CR', 'ERA-20C', 'ERA-Interim', 'MERRA', 'ERA-FIVE'
    ]]
    # metricColumns.to_csv('justMetrics.csv')
    #dat['metricStd'] = np.std(metricColumns, axis = 1)
    # dat.to_csv("metricSTDNse.csv")

    #plotting
    if metric == 'corr':
        dat['Metric STD'] = dat['metricSTD']
        bubbleSize = 800
        title = 'Pearson\'s Correlation - Variation of Model Accuracy among Reanalyses'
    elif metric == 'rmse':
        #multiply by 100 to get values in cms
        dat['Metric STD'] = 100 * dat['metricSTD']
        bubbleSize = 4000
        title = 'RMSE - Metric Variation of Model Accuracy among Reanalyses (cm)'
    elif metric == 'rrmse':
        dat['Metric STD'] = dat['metricSTD']
        bubbleSize = 50
        title = 'RRMSE - Variation of Model Accuracy among Reanalyses'
    else:
        dat['Metric STD'] = dat['metricSTD']
        bubbleSize = 50
        title = 'NNSE - Variation of Model Accuracy among Reanalyses'

    sns.set_context('notebook', font_scale=1.5)

    plt.figure(figsize=(20, 10))
    m = Basemap(projection='cyl',
                lat_ts=20,
                llcrnrlon=-180,
                urcrnrlon=180,
                llcrnrlat=-90,
                urcrnrlat=90,
                resolution='c')
    x, y = m(dat['lon'].tolist(), dat['lat'].tolist())
    m.drawcoastlines()

    #draw parallels and meridians
    parallels = np.arange(-80, 81, 20.)
    m.drawparallels(parallels, labels=[True, False, False, False], linewidth=0)

    #define bubble sizes
    minSize = min(dat['metricSTD']) * bubbleSize
    maxSize = max(dat['metricSTD']) * bubbleSize

    m.bluemarble(alpha=0.8)
    sns.scatterplot(x=x,
                    y=y,
                    color='red',
                    size='metricSTD',
                    hue='Reanalysis',
                    sizes=(minSize, maxSize),
                    palette={
                        'ERA-Interim': 'black',
                        'ERA-FIVE': 'cyan',
                        'MERRA': 'red',
                        'ERA-20C': 'magenta',
                        '20CR': 'green'
                    },
                    data=dat)
    plt.title(title)
    os.chdir(
        'D:\\OneDrive - Knights - University of Central Florida\\UCF\\Projekt.28\\Report\\05-Spring-2020\\#2Paper\\p28DataDescriptor\\reView\\figures\\r1c25'
    )
    saveName = 'allReanalyses' + metric + 'STD.svg'
    plt.savefig(saveName, dpi=400)
Beispiel #56
0
            llcrnrlon=-180,
            urcrnrlon=180,
            llcrnrlat=-90,
            urcrnrlat=90,
            resolution='c')
x, y = m(dat['lon'].tolist(), dat['lat'].tolist())
m.drawcoastlines()

#get degree signs
parallels = np.arange(-80, 81, 20.)
meridians = np.arange(-180., 180., 40.)
#labels = [left,right,top,bottom]
m.drawparallels(parallels, labels=[True, True, False, False], linewidth=0.5)
m.drawmeridians(meridians, labels=[False, False, False, True], linewidth=0.5)

m.bluemarble(alpha=0.8)

plt.scatter(x,
            y,
            100,
            marker='o',
            edgecolors='black',
            c=dat['baseMinusSstRmse'],
            cmap='seismic_r')
m.colorbar(location='bottom')

plt.clim(-12.5, 12.5)
plt.title('Difference in RMSE (mm) between Base Case and SST Case')

os.chdir('G:\\data\manuscriptFiles\\figures')
saveName = 'figure1b.svg'
numDetectedEvents = len(detectedEventList)

detectedThetaList = [event.theta for event in detectedEventList]
detectedPhiList = [event.phi for event in detectedEventList]
detectedXList = [event.X for event in detectedEventList]
detectedYList = [event.Y for event in detectedEventList]
detectedThetaPhiPoints = [event.thetaPhiPoint for event in detectedEventList]
detectedXYPoints = [event.XYPoint for event in detectedEventList]

#Plotting inits
fig, ax = plt.subplots()

#Globemap
m = Basemap(projection='robin', lon_0=0, resolution='c')
m.bluemarble(scale=1)

#For testing purposes
#Transforming to to lattitude and longitude coordinates
detectedLonList = [math.degrees(phi) for phi in detectedPhiList]
detectedLatList = [
    math.degrees(theta - math.pi / 2) for theta in detectedThetaList
]
detectedLonLatList = list(zip(detectedLonList, detectedLatList))

#Fractional items
detectionFractionList = [.33, .5, .66]
sharpnessList = [2.3, 2.3, 2.3]
numFrac = len(detectionFractionList)
clusterDictDict = {}
for i, detectionFraction in enumerate(detectionFractionList):
Beispiel #58
0
]
routes_df = pd.read_csv("E:\\data/size.csv",
                        encoding='GB2312',
                        names=route_cols)

startnum = np.zeros((18, 8), np.int)

fig = plt.figure(figsize=(8, 8))
# fig = plt.figure(figsize=(16,12))
ax1 = fig.add_axes([0.1, 0.1, 0.8, 0.8])
map = Basemap(projection='ortho',
              lat_0=60,
              lon_0=-170,
              area_thresh=1000.0,
              ax=ax1)
map.bluemarble()
map.drawcoastlines()
map.drawcountries()
# map.fillcontinents(color = 'coral',alpha = .1)
map.drawmapboundary()
map.drawmeridians(np.arange(0, 360, 30))
map.drawparallels(np.arange(-90, 90, 30))


#定义一个勾勒两点之间线段的函数:
def create_great_circles(df):
    for index, row in df.iterrows():
        start_lon = row['cflon']
        start_lat = row['cflat']
        end_lon = row['ddlon']
        end_lat = row['ddlat']
Beispiel #59
0
def combined_all_ghgs(sim_file, lattice_files, datetime, centre, xco2_lims=None, xco_lims=None, xch4_lims=None, map_bkgd='bluemarble', cmap='jet', out='show', **kwargs):

    fig = plt.figure(figsize=(15,12))
    
    xco2_ax = fig.add_subplot(231)
    xco_ax = fig.add_subplot(232)
    xch4_ax = fig.add_subplot(233)
    cld_ax = fig.add_subplot(223)
    ret_ax = fig.add_subplot(224)
    
    
    #####################################
    
    plt.sca(xco2_ax)
    
    
    xco2, xco2_lats, xco2_lons = ec_cas.global_XCO2(datetime)
    
    proj_xco2 = Basemap(projection='ortho', lat_0=centre[0], lon_0=centre[1], resolution='l')
    
    proj_xco2.drawcoastlines(linewidth=0.75)
    proj_xco2.drawcountries(linewidth=0.5)
    proj_xco2.drawmeridians(np.arange(-180, 181, 30), latmax=90, linewidth=0.5)
    proj_xco2.drawparallels(np.arange(-90, 91, 15), latmax=90, linewidth=0.5)
    
    
    lon, lat = np.meshgrid(xco2_lons, xco2_lats)
    x,y = proj_xco2(lon, lat)
    
    xco2_mask = np.ma.masked_greater(x, 1e15).mask
    xco2_masked = np.ma.array(xco2, mask=xco2_mask)
    
    if xco2_lims:
        vmin_xco2, vmax_xco2 = xco2_lims
    else:
        vmin_xco2 = xco2_masked.min() // 1.
        vmax_xco2 = xco2_masked.max() // 1. + 1.
    
    sm_xco2 = ScalarMappable(Normalize(vmin=vmin_xco2, vmax=vmax_xco2), cmap=cmap)
    levs_xco2 = np.linspace(vmin_xco2, vmax_xco2, 256)
    clevs_xco2 = [sm_xco2.to_rgba(lev) for lev in levs_xco2]
    
    xco2_ctr = plt.contourf(x, y, xco2_masked, levs_xco2, colors=clevs_xco2, extend='both')
    
    xco2_cbar = plt.colorbar(xco2_ctr, orientation='vertical', fraction=0.05, aspect=40, shrink=0.75)
    xco2_cbar.set_label('XCO$_2$ [ppm]')
    xco2_cbar.set_ticks(np.arange(vmin_xco2, vmax_xco2+0.25, 0.5))
    
    plt.title(datetime.strftime('XCO$_2$ %d %b %Y %H:%M:%S'))
    
    
    ######################################
    
    plt.sca(xco_ax)
    
    xco, xch4, xlats, xlons = ec_cas.global_ghg(datetime)
    
    proj_xco = Basemap(projection='ortho', lat_0=centre[0], lon_0=centre[1], resolution='l')
    
    proj_xco.drawcoastlines(linewidth=0.75)
    proj_xco.drawcountries(linewidth=0.5)
    proj_xco.drawmeridians(np.arange(-180, 181, 30), latmax=90, linewidth=0.5)
    proj_xco.drawparallels(np.arange(-90, 91, 15), latmax=90, linewidth=0.5)
    
    
    lon, lat = np.meshgrid(xlons, xlats)
    x,y = proj_xco(lon, lat)
    
    xco_mask = np.ma.masked_greater(x, 1e15).mask
    xco_masked = np.ma.array(xco, mask=xco_mask)
    
    if xco_lims:
        vmin_xco, vmax_xco = xco_lims
    else:
        vmin_xco = xco_masked.min() // 1.
        vmax_xco = xco_masked.max() // 1. + 1.
    
    sm_xco = ScalarMappable(Normalize(vmin=vmin_xco, vmax=vmax_xco), cmap=cmap)
    levs_xco = np.linspace(vmin_xco, vmax_xco, 256)
    clevs_xco = [sm_xco.to_rgba(lev) for lev in levs_xco]
    
    xco_ctr = plt.contourf(x, y, xco_masked, levs_xco, colors=clevs_xco, extend='both')
    
    xco_cbar = plt.colorbar(xco_ctr, orientation='vertical', fraction=0.1, aspect=40, shrink=0.75)
    xco_cbar.set_label('XCO [ppb]')
    xco_cbar.set_ticks(np.int64(np.arange(vmin_xco, vmax_xco+1, 10)))
    
    plt.title(datetime.strftime('XCO %d %b %Y %H:%M:%S'))
    
    
    #######################################
    
    plt.sca(xch4_ax)
    
    proj_xch4 = Basemap(projection='ortho', lat_0=centre[0], lon_0=centre[1], resolution='l')
    
    proj_xch4.drawcoastlines(linewidth=0.75)
    proj_xch4.drawcountries(linewidth=0.5)
    proj_xch4.drawmeridians(np.arange(-180, 181, 30), latmax=90, linewidth=0.5)
    proj_xch4.drawparallels(np.arange(-90, 91, 15), latmax=90, linewidth=0.5)
    
    
    lon, lat = np.meshgrid(xlons, xlats)
    x,y = proj_xch4(lon, lat)
    
    xch4_mask = np.ma.masked_greater(x, 1e15).mask
    xch4_masked = np.ma.array(xch4, mask=xch4_mask)
    
    if xch4_lims:
        vmin_xch4, vmax_xch4 = xch4_lims
    else:
        vmin_xch4 = xch4_masked.min() // 1.
        vmax_xch4 = xch4_masked.max() // 1. + 1.
    
    sm_xch4 = ScalarMappable(Normalize(vmin=vmin_xch4, vmax=vmax_xch4), cmap=cmap)
    levs_xch4 = np.linspace(vmin_xch4, vmax_xch4, 256)
    clevs_xch4 = [sm_xch4.to_rgba(lev) for lev in levs_xch4]
    
    xch4_ctr = plt.contourf(x, y, xch4_masked, levs_xch4, colors=clevs_xch4, extend='both')
    
    xch4_cbar = plt.colorbar(xch4_ctr, orientation='vertical', fraction=0.1, aspect=40, shrink=0.75)
    xch4_cbar.set_label('XCH$_4$ [ppb]')
    xch4_cbar.set_ticks(np.int64(np.arange(vmin_xch4, vmax_xch4 + 1, 20)))
    
    plt.title(datetime.strftime('XCH$_4$ %d %b %Y %H:%M:%S'))
    
    
    ##############################################################
    
    plt.sca(cld_ax)
    
    
    mission = retrievals.Mission(sim_file, *lattice_files, **kwargs)
    
    obs_time = time_utils.Time(datetime, mission.satellite.times[0].ref)        
        
    # find the closest apogee point to obs_time
    apogees = mission.satellite.get_apogees()
    apogee_ind = time_utils.closest_index(obs_time, apogees)
    
    # create the ObservationPeriod instance, and generate the Retrieval instances
    obs = retrievals.ObservationPeriod(mission, apogees[apogee_ind], mission.lattice_files[apogee_ind%2])
    obs.main_filter()
    obs.generate_retrievals()
    
    # find the closest segment of the observation period
    obs_ind = time_utils.closest_index(obs_time, obs.obs_middle)
    
    clat, clon = centre
    proj_cld = Basemap(projection='ortho', lat_0=centre[0], lon_0=centre[1], resolution='c')
    
    # draw cloud data that was used to determine FOV locations
    obs.cloud_collection.show_clouds_ortho(obs.cloud_times[obs_ind], centre, map_bkgd=map_bkgd, out='')
    
    proj_cld.nightshade(datetime)
    
    # draw a red border around each of the selected FOVs
    for ret in obs.retrievals[obs_ind]:
        
        lats = np.concatenate([ret.pixel_lats[:,0], ret.pixel_lats[-1,:], ret.pixel_lats[::-1,-1], ret.pixel_lats[0,::-1]])
        lons = np.concatenate([ret.pixel_lons[:,0], ret.pixel_lons[-1,:], ret.pixel_lons[::-1,-1], ret.pixel_lons[0,::-1]])
        
        x,y = proj_cld(lons, lats)
        coords = np.vstack([x,y]).T
        
        if not np.sum(coords > 1e15):
        
            p = Polygon(coords, fill=False, edgecolor='r', zorder=10)
            plt.gca().add_patch(p)
        
    plt.title('FoV Selections {0} - {1} UTC'.format(obs.obs_times[obs_ind].strf('%d %B %Y %H:%M'), obs.obs_times[obs_ind+1].strf('%H:%M')))
    
    
    ##############################################################
    
    plt.sca(ret_ax)
    
    
    proj_ret = Basemap(projection='ortho', lat_0=centre[0], lon_0=centre[1], resolution='l')
    
    if map_bkgd == 'bluemarble':
        proj_ret.bluemarble()
    elif map_bkgd == 'etopo':
        proj_ret.etopo()
    elif map_bkgd == 'mask':
        proj_ret.drawlsmask(land_color='limegreen', ocean_color='dodgerblue', resolution='l')
        
        proj_ret.drawcoastlines(linewidth=0.75)
        proj_ret.drawcountries(linewidth=0.5)
        proj_ret.drawmeridians(np.arange(-180, 181, 30), latmax=90, linewidth=0.5)
        proj_ret.drawparallels(np.arange(-90, 91, 15), latmax=90, linewidth=0.5)
    else:
        raise ValueError('invalid map background specification')
    
    proj_ret.nightshade(datetime)
    
    
    
    for ret in obs.retrievals[obs_ind]:
                
        x,y = proj_ret(ret.pixel_lons, ret.pixel_lats)
                
        if not np.sum(x > 1e15):
        
            
            ret_mask = ret.valid_retrievals == 0
            ret_masked = np.ma.array(np.ones(ret.pixel_lats.shape), mask=ret_mask)
            
            ret_ctr = plt.contourf(x, y, ret_masked, [0,1], colors=['red'], extend='both')
        
    
    plt.title('AIM-North Retrievals {0} - {1} UTC'.format(obs.obs_times[obs_ind].strf('%d %B %Y %H:%M'), obs.obs_times[obs_ind+1].strf('%H:%M')))   
            
    ##############################################################
    
    plt.subplots_adjust(left=0.01, right=0.95, bottom=0.025, top = 0.975, wspace=0.175, hspace=0.1)
    
    if out == 'show':
        plt.show()
    elif out == '':
        pass
    else:
        plt.savefig(os.path.join('../figures/combined_plots/', out))
        plt.close()
Beispiel #60
0
def geramapa(star,
             data,
             title,
             labelx,
             nameimg,
             mapstyle='1',
             resolution='l',
             centermap=None,
             lats=None,
             erro=None,
             ring=None,
             atm=None,
             clat=None,
             sitearq='sites.dat',
             fmt='png',
             dpi=100,
             mapsize=None,
             cpoints=60,
             off=0):
    lon = star.ra - data.sidereal_time('mean', 'greenwich')
    center_map = EarthLocation(lon.value, star.dec.value)
    fig = plt.figure(figsize=(mapsize[0].to(u.imperial.inch).value,
                              mapsize[1].to(u.imperial.inch).value))
    if not centermap == None:
        center_map = EarthLocation(centermap[0], centermap[1])
#    m = Basemap(projection='ortho',lat_0=center_map.latitude.value,lon_0=center_map.longitude.value,resolution=resolution)
    m = Basemap(projection='ortho',
                lat_0=center_map.latitude.value,
                lon_0=center_map.longitude.value,
                resolution=resolution,
                llcrnrx=-4000000.,
                llcrnry=-4130000.,
                urcrnrx=1000000.,
                urcrnry=0000000.)
    kx = fig.add_axes([0.105, 0.1, 0.894, 0.894])
    kx.set_rasterization_zorder(1)
    m.nightshade(data.datetime, alpha=0.3,
                 zorder=0.5)  ## desenha a sombra da noite
    m.drawcoastlines(linewidth=0.5)  ## desenha as linhas da costa
    m.drawcountries(linewidth=0.5)  ## desenha os paises
    #    m.drawstates(linewidth=0.5)    ## Desenha os estados
    m.drawmeridians(np.arange(0, 360, 30))  ## desenha os meridianos
    m.drawparallels(np.arange(-90, 90, 30))  ## desenha os paralelos
    m.drawmapboundary()  ## desenha o contorno do mapa
    style = {
        '1': {
            'ptcolor': 'red',
            'lncolor': 'blue',
            'ercolor': 'blue',
            'rncolor': 'blue',
            'atcolor': 'blue',
            'outcolor': 'red'
        },
        '2': {
            'ptcolor': 'red',
            'lncolor': 'blue',
            'ercolor': 'red',
            'rncolor': 'black',
            'atcolor': 'black',
            'outcolor': 'red'
        },
        '3': {
            'ptcolor': 'red',
            'lncolor': 'blue',
            'ercolor': 'red',
            'rncolor': 'black',
            'atcolor': 'black',
            'outcolor': 'red'
        },
        '4': {
            'ptcolor': 'red',
            'lncolor': 'red',
            'ercolor': 'red',
            'rncolor': 'black',
            'atcolor': 'black',
            'outcolor': 'red'
        },
        '5': {
            'ptcolor': 'red',
            'lncolor': 'red',
            'ercolor': 'red',
            'rncolor': 'black',
            'atcolor': 'black',
            'outcolor': 'red'
        }
    }
    if mapstyle == '2':
        m.drawmapboundary(fill_color='aqua')
        m.fillcontinents(color='coral', lake_color='aqua')
    elif mapstyle == '3':
        m.shadedrelief()
    elif mapstyle == '4':
        m.bluemarble()
    elif mapstyle == '5':
        m.etopo()
    if not lats == None:
        xs, ys = m(lats[0], lats[1])
        xs = [i for i in xs if i < 1e+30]
        ys = [i for i in ys if i < 1e+30]
        m.plot(xs, ys, color=style[mapstyle]['lncolor'])
        xt, yt = m(lats[2], lats[3])
        xt = [i for i in xt if i < 1e+30]
        yt = [i for i in yt if i < 1e+30]
        m.plot(xt, yt, color=style[mapstyle]['lncolor'])
        m.plot(lats[4],
               lats[5],
               color=style[mapstyle]['outcolor'],
               zorder=-0.2)
        m.plot(lats[6],
               lats[7],
               color=style[mapstyle]['outcolor'],
               zorder=-0.2)
#    else:
#        m.plot(lats[4], lats[5], color=style[mapstyle]['outcolor'], clip_on=False, zorder=0.2)
#        m.plot(lats[6], lats[7], color=style[mapstyle]['outcolor'], clip_on=False, zorder=0.2)
    if not erro == None:
        xs, ys = m(erro[0], erro[1])
        xs = [i for i in xs if i < 1e+30]
        ys = [i for i in ys if i < 1e+30]
        m.plot(xs, ys, '--', color=style[mapstyle]['ercolor'])
        xt, yt = m(erro[2], erro[3])
        xt = [i for i in xt if i < 1e+30]
        yt = [i for i in yt if i < 1e+30]
        m.plot(xt, yt, '--', color=style[mapstyle]['ercolor'])
    if not ring == None:
        xs, ys = m(ring[0], ring[1])
        xs = [i for i in xs if i < 1e+30]
        ys = [i for i in ys if i < 1e+30]
        m.plot(xs, ys, '--', color=style[mapstyle]['rncolor'])
        xt, yt = m(ring[2], ring[3])
        xt = [i for i in xt if i < 1e+30]
        yt = [i for i in yt if i < 1e+30]
        m.plot(xt, yt, '--', color=style[mapstyle]['rncolor'])
    if not atm == None:
        xs, ys = m(atm[0], atm[1])
        xs = [i for i in xs if i < 1e+30]
        ys = [i for i in ys if i < 1e+30]
        m.plot(xs, ys, color=style[mapstyle]['atcolor'])
        xt, yt = m(atm[2], atm[3])
        xt = [i for i in xt if i < 1e+30]
        yt = [i for i in yt if i < 1e+30]
        m.plot(xt, yt, color=style[mapstyle]['atcolor'])
    if not clat == None:
        xc, yc, lab = [], [], []
        cp = Time(clat[5], format='iso')
        vec = np.arange(0, (cp[-1] - data).sec, cpoints)
        vec = np.sort(np.concatenate((vec, -vec[1:]), axis=0)) * u.s
        for i in vec:
            g = data + TimeDelta(i) + TimeDelta(off * u.s)
            if g.iso in clat[2]:
                a = np.where(np.array(clat[2]) == g.iso)
                x, y = m(np.array(clat[0])[a], np.array(clat[1])[a])
                xc.append(x)
                yc.append(y)
                lab.append(g.iso.split()[1][0:8])
            elif g.iso in clat[5]:
                a = np.where(np.array(clat[5]) == g.iso)
                xc.append(np.array(clat[3])[a])
                yc.append(np.array(clat[4])[a])
                lab.append(g.iso.split()[1][0:8])
            else:
                if len(clat[2]) == 0:
                    a = [0]
                else:
                    co = Time(clat[2], format='iso')
                    a = np.argsort(np.absolute(co - g))[0:2]
                if 0 not in a and len(co) - 1 not in a:
                    b = np.absolute((co[a] - g).sec)
                    x, y = m(np.array(clat[0])[a], np.array(clat[1])[a])
                    xc.append(np.sum(x * (1 / b)) / np.sum(1 / b))
                    yc.append(np.sum(y * (1 / b)) / np.sum(1 / b))
                    lab.append(g.iso.split()[1][0:8])
                else:
                    co = Time(clat[5], format='iso')
                    a = np.argsort(np.absolute(co - g))[0:2]
                    b = np.absolute((co[a] - g).sec)
                    xc.append(
                        np.sum(np.array(clat[3])[a] * (1 / b)) / np.sum(1 / b))
                    yc.append(
                        np.sum(np.array(clat[4])[a] * (1 / b)) / np.sum(1 / b))
                    lab.append(g.iso.split()[1][0:8])
        m.plot(xc,
               yc,
               'o',
               color=style[mapstyle]['ptcolor'],
               markersize=mapsize[0].value * 8 / 46)
        m.plot(clat[6][0],
               clat[6][1],
               'o',
               color=style[mapstyle]['ptcolor'],
               markersize=mapsize[0].value * 20 / 46)

#    for label, axpt, bypt in zip(lab, xc, yc):
#        plt.text(axpt + 0, bypt + 350000, label, rotation=60, weight='bold')

#    m.plot(ax,by, 'o', color=ptcolor, markersize=int(mapsize[0].value*20/46))
#    m.plot(ax2.to(u.m),by2.to(u.m), 'o', color=ptcolor, markersize=int(mapsize[0].value*12/46))
#    m.plot(ax3.to(u.m), by3.to(u.m), color='red')
#    m.plot(ax4.to(u.m), by4.to(u.m), color='red')
#    m.quiver(a-0*u.m,b-600000*u.m, 20, 0, width=0.005)

#    ax2 = a + dista*np.sin(pa) + [(i - datas).sec for i in temposplot]*u.s*vel*np.cos(paplus)
#    by2 = b + dista*np.cos(pa) - [(i - datas).sec for i in temposplot]*u.s*vel*np.sin(paplus)
#
#    labels = [i.iso.split()[1][0:8] for i in temposplot]
#    m.plot(ax2, by2, 'ro')

    if os.path.isfile(sitearq) == True:
        sites = np.loadtxt(sitearq,
                           dtype={
                               'names': ('lat', 'lon', 'alt', 'nome'),
                               'formats': ('f8', 'f8', 'f8', 'S30')
                           })
        xpt, ypt = m(sites['lon'], sites['lat'])
        m.plot(xpt, ypt, 'go')
#        offset = [[xpt[0] + 100000,xpt[0] + 100000,xpt[0] + 100000,xpt[3] + 400000,xpt[3] +400000,xpt[3] +400000,xpt[3] +400000,xpt[3] +400000,xpt[3] +400000],[10000,-30000,-60000,70000,30000,-20000,-70000,-30000,-70000]]
#        for i in np.arange(len(xpt)):
#            ax.text(offset[0][i],ypt[i]+offset[1][i],sites['nome'][i], weight='bold')

#    m.plot(ax5.to(u.m), by5.to(u.m), '--', color=dscolor, label='+-{} error'.format(erro))
#    m.plot(ax6.to(u.m), by6.to(u.m), '--', color=dscolor)
#    plt.legend(fontsize=mapsize[0].value*21/46)

    m.plot(5761981.38333,
           4121691.04177,
           '+',
           color='black',
           markersize=mapsize[0].value * 20 / 46)

    #    fig = plt.gcf()
    #    fig.set_size_inches(mapsize[0].to(u.imperial.inch).value, mapsize[1].to(u.imperial.inch).value)
    #    plt.title(title, fontsize=mapsize[0].value*25/46, fontproperties='FreeMono', weight='bold')
    #    plt.xlabel(labelx, fontsize=mapsize[0].value*21/46, fontproperties='FreeMono', weight='bold')
    e, w = m(center_map.longitude.value, center_map.latitude.value)
    plt.xscale(u'linear')
    plt.xticks(np.arange(0, 5000000, 500000) + e - 4000000,
               np.arange(0.0, 5.0, 0.5),
               fontsize=sizel)
    plt.xlabel(r'$\times 10^{3}$(km)', fontsize=sizel)
    plt.yscale(u'linear')
    plt.yticks(np.arange(0, 4500000, 500000) + w - 4130000,
               np.arange(0.0, 4.5, 0.5),
               fontsize=sizel)  #, rotation=90)
    plt.ylabel(r'$\times 10^{3}$(km)', fontsize=sizel)
    plt.savefig('{}.{}'.format(nameimg, fmt), format=fmt, dpi=dpi)
    print 'Gerado: {}.{}'.format(nameimg, fmt)
    plt.clf()