Example #1
0
def globe(travel, colors):
    """
    This customize map chart from Basemap(plt as aliased above) 
    Args:
        df: dataframe 
        column: x-axis column
        label: string to label the graph
        figsize: figure size to make chart small or big
        
    Returns:
        None
    """
    plt.figure(figsize=(16, 16))
    m = Basemap(projection='ortho', lat_0=0, lon_0=0)
    m.drawmapboundary(fill_color='#5D9BFF')
    m.fillcontinents(color='#0D9C29', lake_color='#008ECC')
    m.drawcountries(color='#585858', linewidth=1)
    m.drawcoastlines()
    countries = list(travel.Source.unique())
    for item in countries:
        for index, row in travel[travel.Source ==
                                 item].drop_duplicates().iterrows():
            x2, y2 = m.gcpoints(row["Source_Lat"], row["Source_Lon"],
                                row["Dest_Lat"], row["Dest_Lon"], 20)
            plt.plot(x2,
                     y2,
                     color=colors[countries.index(item)],
                     linewidth=0.8)
    plt.show()
Example #2
0
File: z.py Project: leier/z_py
def sat_error():
    boxsize = 6000
    lat, lon = 52.52437, 13.41053  # centre Berlin map
    m = Basemap(projection='ortho',
                lon_0=lon,
                lat_0=lat,
                resolution='l',
                area_thresh='l',
                llcrnrx=-boxsize,
                llcrnry=-boxsize,
                urcrnrx=+boxsize,
                urcrnry=+boxsize)

    x0, y0 = m(lo_sat[0], la_sat[0])
    x1, y1 = m(lo_sat[1], la_sat[1])
    dog = sqrt((x1 - x0)**2. + (y1 - y0)**2.)
    print x0 + 0.5 * (x1 - x0), y0 + 0.5 * (y1 - y0)
    print distance_on_earth(la_sat[0], lo_sat[0], la_sat[1], lo_sat[1])

    x, y = m.gcpoints(lo_sat[0], la_sat[0], lo_sat[1], la_sat[1], 10000)

    log, lag = m(x[5000], y[5000], inverse=True)
    lop, lap = m(x0 + 0.5 * (x1 - x0), y0 + 0.5 * (y1 - y0), inverse=True)
    print lag, log, lap, lop
    return distance_on_earth(lag, log, lap, lop)
def ray_density(lat1, lon1, lat2, lon2,
                dt=1, gr_x=360, gr_y=180, 
                npts=180, projection='robin', 
                ray_coverage=False):
    '''
    Create the DATA array which contains the
    info for ray density
    '''
    global long_0

    mymap = Basemap(projection=projection, lon_0=long_0, lat_0=0)
    #npts=max(gr_x, gr_y)
    # grd[2]: longitude
    # grd[3]: latitude
    grd = mymap.makegrid(gr_x, gr_y, returnxy=True)

    lons, lats = mymap.gcpoints(lon1, lat1, lon2, lat2, npts)
    dist = locations2degrees(lat1, lon1, lat2, lon2)
    bap = int((dist - 97.0)*npts/dist)/2
    midlon = len(lons)/2
    midlat = len(lats)/2
    lons = lons[midlon-bap:midlon+1+bap]
    lats = lats[midlat-bap:midlat+1+bap]
    data = np.zeros([len(grd[2]), len(grd[3])])
    for i in range(len(lons)):
        xi, yi = point_finder(lons[i], lats[i], grd)
        # first one is latitude and second longitude
        try:
            #data[yi][xi] = dt/float(dist-97.0)
            data[yi][xi] += dt/len(lons)
        except Exception, e:
            print e
Example #4
0
File: z.py Project: leier/z_py
def sat_error():
  boxsize=6000
  lat,lon=52.52437,13.41053 # centre Berlin map
  m = Basemap(projection='ortho',lon_0=lon,lat_0=lat,resolution='l',area_thresh='l',llcrnrx=-boxsize,llcrnry=-boxsize,urcrnrx=+boxsize,urcrnry=+boxsize)
  
  x0,y0=m(lo_sat[0],la_sat[0])
  x1,y1=m(lo_sat[1],la_sat[1])
  dog=sqrt((x1-x0)**2.+(y1-y0)**2.)
  print x0+0.5*(x1-x0),y0+0.5*(y1-y0)
  print distance_on_earth(la_sat[0],lo_sat[0],la_sat[1],lo_sat[1])
  
  x,y=m.gcpoints(lo_sat[0],la_sat[0], lo_sat[1],la_sat[1], 10000)
  
  log,lag=m(x[5000],y[5000],inverse=True)
  lop,lap=m(x0+0.5*(x1-x0),y0+0.5*(y1-y0),inverse=True)
  print lag,log,lap,lop
  return distance_on_earth(lag,log,lap,lop)
Example #5
0
def ray_density(lat1, lon1, lat2, lon2, dt=1, gr_x=360, gr_y=180, npts=180, projection='robin', ray_coverage=False):
    """
    Create the DATA array which contains the info for ray density

    Procedure:
    1. make a grid based on the inputs (grd)
    grd: lon, lat, x, y
    2. find the great circle points:
    note that lon , lat are actually x and y!
    3. calculate the distance and find the middle point
    4. subtracting 97 degrees from the distance and find all the points on that section
    5. data ---> zero array with x*y elements

    """

    global long_0

    mymap = Basemap(projection=projection, lon_0=long_0, lat_0=0)
    #npts=max(gr_x, gr_y)
    # grd[2]: longitude
    # grd[3]: latitude
    grd = mymap.makegrid(gr_x, gr_y, returnxy=True)

    lons, lats = mymap.gcpoints(lon1, lat1, lon2, lat2, npts)
    dist = locations2degrees(lat1, lon1, lat2, lon2)

    # npts points on dist...how many on (dist-97)!: (dist-97)*npts/dist....but we also need to make it half!
    bap = int((dist - 97.0)*npts/dist)/2
    midlon = len(lons)/2
    midlat = len(lats)/2
    lons = lons[midlon-bap:midlon+1+bap]
    lats = lats[midlat-bap:midlat+1+bap]

    data = np.zeros([len(grd[2]), len(grd[3])])
    if not len(lons) == len(lats):
        sys.exit('ERROR: Lengths longitudes and latitudes are not the same! %s and %s' % (len(lons), len(lats)))

    for i in range(len(lons)):
        xi, yi = point_finder(lons[i], lats[i], grd)
        # first one is latitude and second longitude
        try:
            #data[yi][xi] = dt/float(dist-97.0)
            data[yi][xi] += dt/len(lons)
        except Exception, e:
            print '\nException: %s' % e
Example #6
0
class Mapa:
    def __init__(self):
        self.map = Basemap(projection='merc',
                           lat_0=0,
                           lon_0=0,
                           resolution='h',
                           area_thresh=0.1,
                           llcrnrlon=-42,
                           llcrnrlat=-7.9,
                           urcrnrlon=-37,
                           urcrnrlat=-2.7)
        self.map.drawcoastlines()
        self.map.drawcountries()
        self.map.drawstates()
        self.map.drawmapboundary(fill_color='aqua')
        self.map.drawstates(color='0.5')

    def inserir_cidade(self, cidade):
        x, y = self.map(cidade['longitude'], cidade['latitude'])
        self.map.plot(x, y, 'bo', markersize=5)
        dx = 5000
        dy = 2500
        plt.text(x + dx, y + dy, cidade['nome'])

    def liga_cidades(self, cidades):

        for i in range(len(cidades)):
            cidade1 = cidades[i]
            cidade2 = cidades[i + 1] if i + 1 < len(cidades) else cidades[0]
            self.inserir_cidade(cidade1)
            self.inserir_cidade(cidade2)
            x, y = self.map.gcpoints(cidade1['longitude'], cidade1['latitude'],
                                     cidade2['longitude'], cidade2['latitude'],
                                     300)

            self.map.plot(x, y)

    def exibir(self):
        plt.show()
Example #7
0
        cyclone_landfall_points = []

        while i < (len(Interested_point) - 1):
            initial_point = Interested_point[i]
            final_point = Interested_point[i + 1]

            init_point = LatLon(initial_point[index_latitude],
                                initial_point[index_longitude])
            fin_point = LatLon(final_point[index_latitude],
                               final_point[index_longitude])
            dis_between = init_point.distance(fin_point)

            if init_point != fin_point:
                intermediate_points = map.gcpoints(
                    initial_point[index_longitude],
                    initial_point[index_latitude],
                    final_point[index_longitude], final_point[index_latitude],
                    (round(dis_between / length_division) + 1))

                check = 0
                while check < len(intermediate_points[1]):

                    cyclone_position = LatLon((intermediate_points[1])[check],
                                              (intermediate_points[0])[check])

                    check2 = 0

                    while check2 < len(country_points):
                        check_point = LatLon((country_points[check2])[1],
                                             (country_points[check2])[0])
                        distance_calculated = cyclone_position.distance(
Example #8
0
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt

map = Basemap(projection='merc', 
              lat_0=0, lon_0=0,
              llcrnrlon=-20.,llcrnrlat=0.,urcrnrlon=180.,urcrnrlat=80.)

map.drawmapboundary(fill_color='aqua')
map.fillcontinents(color='coral',lake_color='aqua')
map.drawcoastlines()

x, y = map.gcpoints(2.3, 48.9, 139.7, 35.6, 300)

print x, y

map.plot(x, y)
plt.show()
Example #9
0
    end_latt=math.radians(end_latt)
    d_latt = end_latt - start_latt  
    d_long = end_long - start_long
    a = math.sin(d_latt/2)**2 + math.cos(start_latt) * math.cos(end_latt) * math.sin(d_long/2)**2  
    c = 2 * math.asin(math.sqrt(a))  
    return 6371 * c *1000

longslist=[0,90,180]
latslist=[65,65,65]
dpslist=[5,10,5]
dmslist=[5,5,10]
print m(0,60)
print m(0,70)
print m(-5,65)
print m(5,65)
print m.gcpoints(0,60,0,70,10)

m.drawgreatcircle(0,60,0,70,100)
m.drawgreatcircle(-5,65,5,65,100)

m.drawgreatcircle(0,60,-5,65,100)
m.drawgreatcircle(0,60,5,65,100)

m.drawgreatcircle(-5,65,0,70,100)
m.drawgreatcircle(0,70,5,65,100)
'''
# draw ellipses
for n in range(0,len(longslist)):
    xy= m(longslist[n],latslist[n])
    w = haversine(longslist[n]-dmslist[n],latslist[n],longslist[n]+dmslist[n],latslist[n])
    h = haversine(longslist[n],latslist[n]-dpslist[n],longslist[n],latslist[n]+dpslist[n])
    print Interested_latitude
    i = 0
    while i < (len(Interested_latitude) - 1):
        exit == False
        initial_point = [Interested_longitude[i], Interested_latitude[i]]
        final_point = [Interested_longitude[i + 1], Interested_latitude[i + 1]]

        # Check the distance between the points
        init_point = LatLon(initial_point[1], initial_point[0])
        fin_point = LatLon(final_point[1], final_point[0])
        dis_between = init_point.distance(fin_point)

        # Divide the track into sections of small divisions
        if initial_point != final_point:
            intermediate_points = map.gcpoints(initial_point[0],\
                initial_point[1],final_point[0],final_point[1], \
                (dis_between/length_division + 1))
            print intermediate_points
            check_point = 0
            while check_point < len(intermediate_points[0]):

                check_result = []
                c_pos = [(intermediate_points[0])[check_point],
                         (intermediate_points[1])[check_point]]
                if check_point == 0:
                    print 'check please'
                    time.sleep(10)
                else:
                    c2_pos = [(intermediate_points[0])[check_point - 1],
                              (intermediate_points[1])[check_point - 1]]
Example #11
0
File: z.py Project: leier/z_py
def main():
  """Finds location of maximum probability in a 2D space defined by three seperate PDFs."""
  
  # plotting
  fig=plt.figure(11,figsize=(6,6))
  plt.clf()
  plt.subplots_adjust(left=0.01, bottom=0.01, right=0.99, top=0.99, wspace=0., hspace=0.)
  ax = plt.subplot(1,1,1)
  xticklabels = getp(gca(), 'xticklabels')
  yticklabels = getp(gca(), 'yticklabels')
  
  # create map and set size
  boxsize=6000
  lat, lon=52.52437, 13.41053 # centre berlin map
  m = Basemap(projection='ortho',lon_0=lon,lat_0=lat,resolution='l',area_thresh='l',llcrnrx=-boxsize,llcrnry=-boxsize,urcrnrx=+boxsize,urcrnry=+boxsize)
  
  # read and plot street map / water areas from shapefile
  m.readshapefile('berlin_germany/berlin_germany_osm_roads_gen1', 'Streets',color='#DDDDDD')
  m.readshapefile('berlin_germany/berlin_germany_osm_waterareas', 'Water',color='#add8e6')
  
  # compute and plot points on great circle
  x,y=m.gcpoints(lo_sat[0],la_sat[0], lo_sat[1],la_sat[1], 100)
  m.plot(x,y,'r-',zorder=7)
  
  # plot spree list of coords
  x,y=m(lo_spree,la_spree)
  m.plot(x,y,'b.',markersize=2)
  
  # plot brandenburg gate
  gx,gy=m(lo_bgate,la_bgate) # coord transform
  m.plot(gx,gy,'bx')
  
  # create search grid
  bestY,bestX=m(13.4497839044, 52.5142566528 ) # grid centre
  minX=bestX-8000
  maxX=bestX+8000
  minY=bestY-8000
  maxY=bestY+8000
  
  rangeX=np.linspace(minX,maxX,nbins)
  rangeY=np.linspace(minY,maxY,nbins)
  npoints=None
  
  meshX, meshY = meshgrid(rangeX, rangeY)
  mzz=np.zeros(shape=(len(rangeY),len(rangeX)))
  maxmzz=0
  
  # compute probabilities for grid and location with max. prob.
  for ii in range(0, len(rangeY)):
    s = str(int(float(ii+1)/nbins*100.)) + '% computed'
    print s,
    sys.stdout.flush()
    backspace(len(s))
    for jj in range(0, len(rangeX)):
      mY,mX=m(rangeY[ii],rangeX[jj],inverse=True)
      prob_bgate,prob_spree,prob_sat,x_bgate,x_spree,x_sat=z_prob(m,mX,mY,npoints)
      mzz[ii][jj]=prob_bgate*prob_spree*prob_sat
      if mzz[ii][jj]>maxmzz:
        maxmzz=mzz[ii][jj]
        maxmX=mX
        maxmY=mY
        best_x_bgate=x_bgate
        best_x_spree=x_spree
        best_x_sat=x_sat
  
  # plot location with max. prob.
  loc_x,loc_y= m(maxmY,maxmX)
  m.plot(loc_x,loc_y,'r.',zorder=8)
  
  # output
  print "\nDone!"
  print "+++ search log +++"
  print "max prob.:", maxmzz, " found at: (lat,lon)=(",maxmX,",",maxmY,")"
  print "with dist. to spree: ", best_x_spree
  print "with dist. to bgate: ", best_x_bgate
  print "with dist. to sat: ", best_x_sat
  print "resolution in m: (dx,dy)=",(maxX-minX)/nbins,(maxY-minY)/nbins #
  
  # plotting: color map and contours
  logcrange=arange(-5,-2.1,0.1)
  crange=10**logcrange
  cs = m.contourf(meshY,meshX,mzz,levels=crange,cmap=cm.Blues,zorder=5, alpha=0.3)
  
  # plotting legend
  prop = matplotlib.font_manager.FontProperties(size=10)
  b, = plot([10000,20000],'bx', linewidth=1)
  c, = plot([10000,20000],'b.', linewidth=1)
  d, = plot([10000,20000],'r-', linewidth=1)
  e, = plot([10000,20000],'r.', linewidth=1)
  legend([b,c,d,e,], ['Brandenburg Gate','Spree (file)','projected satellite path','coordinates with max. probability'],loc='upper left', ncol=1, shadow=False, fancybox=True, numpoints=1, prop=prop,labelspacing=-0.0)
  
  # plotting scale
  shift=6700
  sx=6368777.0109+shift
  sy=6370097.04832+shift
  m.plot([sx,sx+1000],[sy,sy],'k-',linewidth=5)
  s1lo,s1la=m(sx+1000,sy,inverse=True)
  s2lo,s2la=m(sx,sy,inverse=True)
  text(sx,sy-400,r' $1$ $km$')
  
  #plotting colorbar
  cax = axes([0.05,0.05,0.9,0.04]) # cbar location and dimension
  cbar = plt.colorbar(cs,boundaries=logcrange,cax=cax,orientation="horizontal",norm=LogNorm(vmin=1E-6, vmax=7E-3),ticks=[5e-5,1e-4,5e-4,1e-3,5e-3])
  cbar.ax.tick_params(labelsize=9)
  cbar.set_label(r'$\Pi_i P_i$                                                                                           ',labelpad=-25)

  savefig('zmap.png')
  
  return
Example #12
0
    def plot_crosssection_any(self,
                              lon1,
                              lon2,
                              lat1,
                              lat2,
                              numpoints=400,
                              whattoplot='clust',
                              title='',
                              stretch=1,
                              greatcirclepath=True,
                              lon0=180,
                              spherical=False):
        """ plot horizontal slices through an ses3d model

    plot_slice(self,depth,colormap='tomo',res='i',verbose=False)

    depth=depth in km of the slice
    colormap='tomo','mono'
    res=resolution of the map, admissible values are: c, l, i, h f

    """
        model = getattr(self, whattoplot)
        #lon=(lon1+lon2)/2.
        #- set up a map and colourmap -----------------------------------------
        fig = plt.figure()
        plt.subplot(2, 1, 1)
        m = Basemap(projection='hammer', lon_0=lon0)
        #m.drawparallels(np.arange(self.lat_min,self.lat_max,45.),labels=[0,0,0,0])#[1,0,0,1])
        #m.drawmeridians(np.arange(self.lon_min,self.lon_max,60.),labels=[0,0,0,0])#[1,0,0,1])

        coasts = m.drawcoastlines(zorder=1, color='white', linewidth=0)
        coasts_paths = coasts.get_paths()
        ipolygons = range(40)  # want Baikal, but not Tanganyika
        # 80 = Superior+Michigan+Huron, 81 = Victoria, 82 = Aral, 83 = Tanganyika,
        # 84 = Baikal, 85 = Great Bear, 86 = Great Slave, 87 = Nyasa, 88 = Erie
        # 89 = Winnipeg, 90 = Ontario
        for ipoly in ipolygons:
            r = coasts_paths[ipoly]
            # Convert into lon/lat vertices
            polygon_vertices = [(vertex[0], vertex[1])
                                for (vertex,
                                     code) in r.iter_segments(simplify=False)]
            px = [polygon_vertices[i][0] for i in range(len(polygon_vertices))]
            py = [polygon_vertices[i][1] for i in range(len(polygon_vertices))]
            m.plot(px, py, linewidth=1., zorder=3, color=[0.2, 0.2, 0.2])
        #m.drawmapboundary(fill_color=[1.0,1.0,1.0])
        #m.drawmapboundary(fill_color=[1.0,1.0,1.0])
        if lon0 == 180:
            z = (model[:, :, 0])
            #z=z.transpose([1,0,2])
            #zt,lonstmp=shiftgrid(0,z.T,self.lon)
            #lonst,lonstmp=shiftgrid(0,lons.T,lons[:,0])
            x1, y1 = np.meshgrid(self.lon, self.lat)
            x, y = m(x1.T, y1.T)
        else:
            z = (model[:, :, 0])
            zt, lonstmp = shiftgrid(0, z.T, self.lon, start=False)
            x1, y1 = np.meshgrid(self.lon, self.lat)
            print(np.shape(x1), np.shape(y1))
            x, y = m(x1.T, y1.T)
        #x=m.shiftdata(x,lon_0=lon0)    rgb =np.array(np.transpose(clustmap,(1,2,0)),dtype='float32')
        #rgb =zt.transpose([1,2,0])
        #color_tuple=rgb.reshape((rgb.shape[1]*rgb.shape[0],rgb.shape[2]),order='C')
        #mapper=np.linspace(0.,1.,rgb.shape[1]*rgb.shape[0]).reshape(rgb.shape[0],rgb.shape[1])

        #rgb_map=LinearSegmentedColormap.from_list('rgbmap',color_tuple,N=rgb.shape[1]*rgb.shape[0])

        cs = m.pcolor(x, y, z, cmap=self.rgb_map, linewidth=0, rasterized=True)
        #plt.colorbar()

        inv = geo.WGS84.Inverse(lat1, lon1, lat2, lon2)
        points = np.linspace(0, inv['s12'], numpoints)
        line = geo.WGS84.Line(lat1, lon1, inv['azi1'])
        if greatcirclepath:
            [x1, y1] = m.gcpoints(lon1, lat1, lon2, lat2, numpoints)
            m.plot(x1, y1, 'k', linewidth=3)
            m.plot(x1[0], y1[0], '.c', markersize=15, markeredgecolor='k')
            m.plot(x1[-1], y1[-1], '.m', markersize=15, markeredgecolor='k')

            dist = []
            lonsline = []
            latsline = []
            for i in range(len(points)):
                loc = line.Position(points[i])
                # dist.append(haversine((loc['lat2'],loc['lon2']),([lat1],[lon1]))/111194.)
                dist.append(loc['s12'] / 111194.)
                lonsline.append(loc['lon2'])
                latsline.append(loc['lat2'])

            lonsline = np.array(lonsline)
            latsline = np.array(latsline)

        else:
            lonsline = np.linspace(lon1, lon2, numpoints)
            latsline = np.linspace(lat1, lat2, numpoints)
            dist = haversine((lat1, lon1), (latsline, lonsline)) / 111194.

            [x1, y1] = m(lonsline, latsline)
            m.plot(x1, y1, 'k', linewidth=3)
            m.plot(x1[0], y1[0], '.c', markersize=15, markeredgecolor='k')
            m.plot(x1[-1], y1[-1], '.m', markersize=15, markeredgecolor='k')

        modeltoplot = getattr(self, 'indg6')
        idxs = []
        for i in range(len(lonsline)):
            idxs.append(
                np.argmin(
                    haversine((latsline[i], lonsline[i]),
                              (self.latg6, self.long6))))
        idxs = np.array(idxs)

        toplot = np.empty((len(lonsline), len(self.depth)))

        for d in range(len(self.depth)):
            el = np.where(self.deps == self.depth[d])
            clusttmp = np.squeeze(modeltoplot[el])
            for i in range(len(lonsline)):
                toplot[i, d] = clusttmp[idxs[i]]

            #toplot.append(np.round(scipy.ndimage.map_coordinates(model[:,:,d], np.vstack((row,col)),order=0,mode='constant')))

        toplot = np.array(toplot).T

        xx, yy = np.meshgrid(dist, self.depth)

        if spherical == False:
            ax = plt.subplot(2, 1, 2)
            minval = np.min(np.min(toplot))
            maxval = np.max(np.max(toplot))

            contours = np.round(np.linspace(-1.1, 1.1, 12), 2)
            plt.title(title)

            cs = plt.pcolor(xx,
                            yy,
                            toplot,
                            cmap=self.rgb_map,
                            vmin=0.5,
                            vmax=21.5)
            plt.plot([dist[0], dist[-1]],
                     [min(self.depth), min(self.depth)],
                     'k',
                     linewidth=8)
            plt.plot(dist[0],
                     min(self.depth),
                     '.c',
                     markersize=40,
                     markeredgecolor='k')
            plt.plot(dist[-1],
                     min(self.depth),
                     '.m',
                     markersize=40,
                     markeredgecolor='k')

            #plt.pcolor(x,y,self.dvs[:,:,layer],vmin=-0.04, vmax=0.04,cmap=plt.cm.get_cmap('jet_r'))

            plt.ylim([min(self.depth), 2890])
            plt.gca().invert_yaxis()
            plt.xlim([min(dist), max(dist)])
            ax.set_aspect(.015 / stretch)
            #plt.xlabel(xlabel)
            plt.ylabel('depth (km)')
        if spherical == True:

            thetamin = 0
            thetamax = inv['a12'] * np.pi / 180.

            tr = PolarAxes.PolarTransform()

            pi = np.pi
            shift = pi / 2 - (thetamax + thetamin) / 2
            xx = xx + shift * 180. / pi
            angle_ticks = [(thetamin + shift, r""),
                           ((thetamax + thetamin) / 2 + shift, r""),
                           (thetamax + shift, r"")]
            grid_locator1 = FixedLocator([v for v, s in angle_ticks])
            tick_formatter1 = DictFormatter(dict(angle_ticks))

            grid_locator2 = MaxNLocator(6)

            grid_helper = floating_axes.GridHelperCurveLinear(
                tr,
                extremes=(thetamin + shift, thetamax + shift, 6371, 3480),
                grid_locator1=grid_locator1,
                grid_locator2=grid_locator2,
                tick_formatter1=tick_formatter1,
                tick_formatter2=None)

            ax1 = floating_axes.FloatingSubplot(fig,
                                                212,
                                                grid_helper=grid_helper)
            fig.add_subplot(ax1)

            # create a parasite axes whose transData in RA, cz
            aux_ax = ax1.get_aux_axes(tr)

            aux_ax.patch = ax1.patch  # for aux_ax to have a clip path as in ax
            ax1.patch.zorder = 0.9  # but this has a side effect that the patch is
            # drawn twice, and possibly over some other
            # artists. So, we decrease the zorder a bit to
            # prevent this.

            #ax=plt.subplot(212, polar = True)
            minval = np.min(np.min(toplot))
            maxval = np.max(np.max(toplot))

            contours = np.round(np.linspace(-1.1, 1.1, 12), 2)

            #plt.title(title)

            cs = aux_ax.pcolor((180. - xx) * np.pi / 180.,
                               6371. - yy,
                               toplot,
                               cmap=self.rgb_map,
                               vmin=0.5,
                               vmax=21.5)
            aux_ax.plot(np.pi - (thetamin + shift),
                        6371.,
                        '.c',
                        markersize=55,
                        markeredgecolor='k')
            aux_ax.plot(np.pi - (thetamax + shift),
                        6371.,
                        '.m',
                        markersize=55,
                        markeredgecolor='k')
            return aux_ax, shift
Example #13
0
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt

map = Basemap(projection='merc',
              lat_0=0,
              lon_0=0,
              llcrnrlon=-20.,
              llcrnrlat=0.,
              urcrnrlon=180.,
              urcrnrlat=80.)

map.drawmapboundary(fill_color='aqua')
map.fillcontinents(color='coral', lake_color='aqua')
map.drawcoastlines()

x, y = map.gcpoints(2.3, 48.9, 139.7, 35.6, 300)

print x, y

map.plot(x, y)
plt.show()
Example #14
0
    m.drawparallels(np.arange(-90.,120.,30.))
    m.drawmeridians(np.arange(0.,420.,60.))
    m.drawmapboundary()

    gc_xmid_points = []
    gc_ymid_points = []
    gc_dtmid_points = []
    for i in range(len(passed_staev)):
        sys.stdout.write('\r')
        sys.stdout.write("[%-100s] %d%%" % ('='*int(100.*(i+1)/len(passed_staev)),
                                                100.*(i+1)/len(passed_staev)))
        sys.stdout.flush()
        #m.drawgreatcircle(passed_staev[i][5],passed_staev[i][4],
        #            passed_staev[i][1],passed_staev[i][0], alpha = 0.1, 
        #            color=passed_staev[i][-1])
        gc_arc = m.gcpoints(passed_staev[i][5], passed_staev[i][4],
                    passed_staev[i][1], passed_staev[i][0], int(divisions))
        gc_xmid_points.append(gc_arc[0][int(divisions/2)])
        gc_ymid_points.append(gc_arc[1][int(divisions/2)])
        gc_dtmid_points.append(passed_staev[i][2])
        #m.scatter(gc_arc[0][50], gc_arc[1][50], color=passed_staev[i][-1])
        #m.scatter(gc_arc[0][50], gc_arc[1][50], color=passed_staev[i][2], vmin=-6, vmax=6.0)

    map_evlats = []
    map_evlons = []
    print '\nError:' 
    for i in range(len(proc_ev_ls)):
        try:
            evx, evy = m(evlons[i], evlats[i])
            map_evlons.append(evx)
            map_evlats.append(evy)
        except Exception, e:
Example #15
0
                        Interested_latitude.extend([latitude,next_latitude])

        point_number += 1

    i = 0

    while i < (len(Interested_latitude)-1):
        initial_point = [Interested_longitude[i],Interested_latitude[i]]
        final_point = [Interested_longitude[i+1],Interested_latitude[i+1]]
        init_point = LatLon(initial_point[1],initial_point[0])
        fin_point = LatLon(final_point[1],final_point[0])
        dis_between = init_point.distance(fin_point)

        if initial_point != final_point:
            intermediate_points = map.gcpoints(initial_point[0],
                initial_point[1],final_point[0],final_point[1],
                (dis_between/length_division + 1))
            check = 0
            while check < len(intermediate_points):
                cyclone_position = LatLon((intermediate_points[1])[check],(intermediate_points[0])[check])
                check2 = 0
                check_result = []
                while check2 < len(country_points):
                    check_point = LatLon((country_points[check2])[1],(country_points[check2])[0])
                    distance_calculated = cyclone_position.distance(check_point)
                    if distance_calculated <= distance_from_land:
                        check_result.append([True,distance_calculated,check2])
                    else:
                        check_result.append([False,distance_calculated,check2])
                    check2 += 1
                
Example #16
0
File: z.py Project: leier/z_py
def main():
    """Finds location of maximum probability in a 2D space defined by three seperate PDFs."""

    # plotting
    fig = plt.figure(11, figsize=(6, 6))
    plt.clf()
    plt.subplots_adjust(left=0.01,
                        bottom=0.01,
                        right=0.99,
                        top=0.99,
                        wspace=0.,
                        hspace=0.)
    ax = plt.subplot(1, 1, 1)
    xticklabels = getp(gca(), 'xticklabels')
    yticklabels = getp(gca(), 'yticklabels')

    # create map and set size
    boxsize = 6000
    lat, lon = 52.52437, 13.41053  # centre berlin map
    m = Basemap(projection='ortho',
                lon_0=lon,
                lat_0=lat,
                resolution='l',
                area_thresh='l',
                llcrnrx=-boxsize,
                llcrnry=-boxsize,
                urcrnrx=+boxsize,
                urcrnry=+boxsize)

    # read and plot street map / water areas from shapefile
    m.readshapefile('berlin_germany/berlin_germany_osm_roads_gen1',
                    'Streets',
                    color='#DDDDDD')
    m.readshapefile('berlin_germany/berlin_germany_osm_waterareas',
                    'Water',
                    color='#add8e6')

    # compute and plot points on great circle
    x, y = m.gcpoints(lo_sat[0], la_sat[0], lo_sat[1], la_sat[1], 100)
    m.plot(x, y, 'r-', zorder=7)

    # plot spree list of coords
    x, y = m(lo_spree, la_spree)
    m.plot(x, y, 'b.', markersize=2)

    # plot brandenburg gate
    gx, gy = m(lo_bgate, la_bgate)  # coord transform
    m.plot(gx, gy, 'bx')

    # create search grid
    bestY, bestX = m(13.4497839044, 52.5142566528)  # grid centre
    minX = bestX - 8000
    maxX = bestX + 8000
    minY = bestY - 8000
    maxY = bestY + 8000

    rangeX = np.linspace(minX, maxX, nbins)
    rangeY = np.linspace(minY, maxY, nbins)
    npoints = None

    meshX, meshY = meshgrid(rangeX, rangeY)
    mzz = np.zeros(shape=(len(rangeY), len(rangeX)))
    maxmzz = 0

    # compute probabilities for grid and location with max. prob.
    for ii in range(0, len(rangeY)):
        s = str(int(float(ii + 1) / nbins * 100.)) + '% computed'
        print s,
        sys.stdout.flush()
        backspace(len(s))
        for jj in range(0, len(rangeX)):
            mY, mX = m(rangeY[ii], rangeX[jj], inverse=True)
            prob_bgate, prob_spree, prob_sat, x_bgate, x_spree, x_sat = z_prob(
                m, mX, mY, npoints)
            mzz[ii][jj] = prob_bgate * prob_spree * prob_sat
            if mzz[ii][jj] > maxmzz:
                maxmzz = mzz[ii][jj]
                maxmX = mX
                maxmY = mY
                best_x_bgate = x_bgate
                best_x_spree = x_spree
                best_x_sat = x_sat

    # plot location with max. prob.
    loc_x, loc_y = m(maxmY, maxmX)
    m.plot(loc_x, loc_y, 'r.', zorder=8)

    # output
    print "\nDone!"
    print "+++ search log +++"
    print "max prob.:", maxmzz, " found at: (lat,lon)=(", maxmX, ",", maxmY, ")"
    print "with dist. to spree: ", best_x_spree
    print "with dist. to bgate: ", best_x_bgate
    print "with dist. to sat: ", best_x_sat
    print "resolution in m: (dx,dy)=", (maxX - minX) / nbins, (maxY -
                                                               minY) / nbins  #

    # plotting: color map and contours
    logcrange = arange(-5, -2.1, 0.1)
    crange = 10**logcrange
    cs = m.contourf(meshY,
                    meshX,
                    mzz,
                    levels=crange,
                    cmap=cm.Blues,
                    zorder=5,
                    alpha=0.3)

    # plotting legend
    prop = matplotlib.font_manager.FontProperties(size=10)
    b, = plot([10000, 20000], 'bx', linewidth=1)
    c, = plot([10000, 20000], 'b.', linewidth=1)
    d, = plot([10000, 20000], 'r-', linewidth=1)
    e, = plot([10000, 20000], 'r.', linewidth=1)
    legend([
        b,
        c,
        d,
        e,
    ], [
        'Brandenburg Gate', 'Spree (file)', 'projected satellite path',
        'coordinates with max. probability'
    ],
           loc='upper left',
           ncol=1,
           shadow=False,
           fancybox=True,
           numpoints=1,
           prop=prop,
           labelspacing=-0.0)

    # plotting scale
    shift = 6700
    sx = 6368777.0109 + shift
    sy = 6370097.04832 + shift
    m.plot([sx, sx + 1000], [sy, sy], 'k-', linewidth=5)
    s1lo, s1la = m(sx + 1000, sy, inverse=True)
    s2lo, s2la = m(sx, sy, inverse=True)
    text(sx, sy - 400, r' $1$ $km$')

    #plotting colorbar
    cax = axes([0.05, 0.05, 0.9, 0.04])  # cbar location and dimension
    cbar = plt.colorbar(cs,
                        boundaries=logcrange,
                        cax=cax,
                        orientation="horizontal",
                        norm=LogNorm(vmin=1E-6, vmax=7E-3),
                        ticks=[5e-5, 1e-4, 5e-4, 1e-3, 5e-3])
    cbar.ax.tick_params(labelsize=9)
    cbar.set_label(
        r'$\Pi_i P_i$                                                                                           ',
        labelpad=-25)

    savefig('zmap.png')

    return
Example #17
0
def plotFlights(trade_df, country2ll, item_name, count):
    from mpl_toolkits.basemap import Basemap
    # Add a connection between new york and London
    year_list = [x for x in range(1980, 2019)]
    trade_quantity = {}
    for year in year_list:
        trade_quantity[year] = {}

    for i, row in trade_df.iterrows():
        exporter = row['Exporter']
        importer = row['Importer']
        quantity = row['Quantity']
        year = row['Year']
        if type(exporter) is str and type(importer) is str:
            route_name = exporter + ' ' + importer
            if year in trade_quantity:
                if route_name in trade_quantity[year]:
                    trade_quantity[year][route_name] += 1
                else:
                    trade_quantity[year][route_name] = 1
            # else:
            #     trade_quantity[year] = {}
            #     trade_quantity[year][route_name] = quantity

    plt.tight_layout(pad=0)
    fig = plt.figure(figsize=(35, 14))
    for year in year_list:
        total_quantity = sum(trade_quantity[year].values())
        # A basic map
        ax = fig.add_axes([0, 0, 1, 1])
        ax.set_axis_off()
        _, raw_item_name = item_name.split('_')
        # ax.set_title('Year: {}, item name: {}, total count: {}'.format(year, raw_item_name, total_quantity))

        m = Basemap(llcrnrlon=-170,
                    llcrnrlat=-60,
                    urcrnrlon=180,
                    urcrnrlat=80,
                    lon_0=0,
                    lat_0=0)
        # m = Basemap(projection='eck4', lon_0=0, resolution='c') # llcrnrlon=-170, llcrnrlat=-70,urcrnrlon=170,urcrnrlat=70)
        m.fillcontinents()
        # m.drawcountries(linewidth=0.25)
        m.drawcoastlines()
        m.drawmapboundary()

        # m.drawmapboundary(fill_color='#A6CAE0', linewidth=0)
        # m.fillcontinents(color='grey', alpha=0.7, lake_color='grey')
        # m.drawcoastlines(linewidth=0.1, color="white")
        # m.drawcountries()

        for route_name in trade_quantity[year]:
            exporter, importer = route_name.split()
            if (exporter in country2ll) and (importer in country2ll) and (
                    exporter != importer):
                startlat = country2ll[exporter]['latitude']
                startlon = country2ll[exporter]['longitude']
                arrlat = country2ll[importer]['latitude']
                arrlon = country2ll[importer]['longitude']
                quantity = trade_quantity[year][route_name]

                linewidth = 0.2 + quantity / total_quantity * 15
                # gcline, = m.drawgreatcircle(startlon,startlat,arrlon,arrlat, linewidth=linewidth, color='orange')
                x_list, y_list = m.gcpoints(startlon, startlat, arrlon, arrlat,
                                            500)
                pre_i = 0
                endpoint_list = [0]
                start_plot = True
                for i in range(len(x_list) - 1):
                    if np.abs(x_list[i] - x_list[i + 1]) + np.abs(
                            y_list[i] - y_list[i + 1]) > 1:
                        m.plot(x_list[pre_i:i],
                               y_list[pre_i:i],
                               linewidth=linewidth,
                               color='orange')
                        pre_i = i + 1
                        endpoint_list.append(i)

                endpoint_list.append(499)

                m.plot(x_list[pre_i:i],
                       y_list[pre_i:i],
                       linewidth=linewidth,
                       color='orange')

                # ==================== adding red arrow to the tail ===================
                last_endpoint = int((endpoint_list[-1]) -
                                    (endpoint_list[-1] - endpoint_list[-2]) //
                                    6)
                head = m(arrlon, arrlat)  # get location of arrow's head
                tail = m(x_list[last_endpoint],
                         y_list[last_endpoint])  # get location of arrow's tail

                # draw annotation with arrow in 'red' color
                # blank text is specified, because we need the arrow only
                # adjust facecolor and other arrow properties as needed
                ax.annotate('',
                            xy=(head[0], head[1]),
                            xycoords='data',
                            xytext=(tail[0], tail[1]),
                            textcoords='data',
                            size=1,
                            arrowprops=dict(width=linewidth, \
                                            headwidth=linewidth*3, \
                                            headlength=linewidth*3, \
                                            facecolor="red", \
                                            edgecolor="none", \
                                            connectionstyle="arc3, rad=0.001") )

                head = m(x_list[endpoint_list[1] // 6],
                         y_list[endpoint_list[1] //
                                6])  # get location of arrow's tail
                tail = m(startlon, startlat)  # get location of arrow's head
                ax.annotate('',
                            xy=(head[0], head[1]),
                            xycoords='data',
                            xytext=(tail[0], tail[1]),
                            textcoords='data',
                            size=1,
                            arrowprops=dict(width=linewidth, \
                                            headwidth=linewidth*3, \
                                            headlength=linewidth*3, \
                                            facecolor="green", \
                                            edgecolor="none", \
                                            connectionstyle="arc3, rad=0.001") )

        try:
            imagefolder = 'visualization/maps/{}'.format(item_name)
            if not os.path.exists(imagefolder):
                os.makedirs(imagefolder)
            plt.savefig('visualization/maps/{}/{}.pdf'.format(item_name, year))
        except:
            print(item_name, 'failed...')
        plt.clf()
Example #18
0
def select_sta():
    
    """
    Select required stations
    """
    
    global input
    
    map_proj = Basemap(projection='cyl', llcrnrlat=-90,urcrnrlat=90,\
                llcrnrlon=-180,urcrnrlon=180, resolution='c')
    ev_file = open(os.path.join(os.getcwd(), 'quake_req.txt'), 'r')
    ev_add = ev_file.read().split('\n')[:-1]
    select = open(os.path.join(os.getcwd(), input['file'] + '.dat'), 'w')
    select.close()
    
    for k in range(0, len(ev_add)):
        
        '''
        select = open(os.path.join(os.getcwd(), \
                input['file'] + '-' + ev_add[k].split('/')[-1] + \
                '.dat'), 'w')
        '''
        
        (quake_d, quake_t) = read_quake(ev_add[k])
        
        list_sta = glob.glob(os.path.join(ev_add[k], 'BH', \
                                input['identity']))
        
        for i in range(0, len(list_sta)):
            
            try:
                
                st = read(list_sta[i])
                print '***************************************'
                print str(i) + '/' + str(len(list_sta)) + ' -- ' + \
                        str(k) + '/' + str(len(ev_add))
                print list_sta[i].split('/')[-1]
                
                info_sac = st[0].stats['sac']
                
                if input['all_sta'] == None:
                    
                    dist = locations2degrees(lat1 = quake_d['lat'], \
                            long1 = quake_d['lon'], lat2 = info_sac['stla'], \
                            long2 = info_sac['stlo'])
                    tt = getTravelTimes(delta=dist, depth=quake_d['dp'], \
                                            model=input['model'])
                    
                    for m in range(0, len(tt)):
                        
                        if tt[m]['phase_name'] in input['phase']:

                            try:
                                print '--------------------'
                                print list_sta[i].split('/')[-1] + ' has ' + \
                                        tt[m]['phase_name'] + ' phase'
                                
                                if input['freq'] != None:
                                    st[0].decimate(int(round(\
                                        st[0].stats['sampling_rate'])/input['freq']), \
                                        no_filter=False)
                                    
                                    if st[0].stats['sampling_rate'] != input['freq']:
                                        print list_sta[i].split('/')[-1]
                                        print st[0].stats['sampling_rate']
                                        print '------------------------------------------'
                                '''
                                np_evt = round((events[0]['datetime'] - st[0].stats['starttime'])*st[0].stats['sampling_rate'])
                                np_pha = np_evt + round(tt[m]['time']*st[0].stats['sampling_rate'])
                                
                                select = open(Address_events + '/' + events[l]['event_id'] + '/IRIS/info/' + name_select, 'a')
                                '''
                                if tt[m]['phase_name'] != 'Pdiff':
                                    lat_1 = str(quake_d['lat'])
                                    lon_1 = str(quake_d['lon'])
                                    lat_2 = str(info_sac['stla'])
                                    lon_2 = str(info_sac['stlo'])
                                elif tt[m]['phase_name'] == 'Pdiff':
                                    dist_limit = 97.0
                                    num_gcp = 1000
                                    gcp = map_proj.gcpoints(quake_d['lon'], \
                                            quake_d['lat'], info_sac['stlo'], \
                                            info_sac['stla'], num_gcp)

                                    if dist >= dist_limit:
                                        diff_dist = dist - dist_limit
                                                        
                                        req_gcp = diff_dist*(float(num_gcp)/dist)
                                        req_gcp = round(req_gcp)/2

                                        mid_p = len(gcp[0])/2
                                        #before = int(mid_p - req_gcp)
                                        #after = int(mid_p + req_gcp)
                                        before = mid_p - int(2.0 * len(gcp[0])/dist)
                                        after = mid_p + int(2.0 * len(gcp[0])/dist)
                                        
                                        x_p, y_p = gcp
                                        lat_1 = y_p[before]
                                        lat_2 = y_p[after]
                                        lon_1 = x_p[before]
                                        lon_2 = x_p[after]
                                        
                                ph_info = tt[m]['phase_name'] + ',' + \
                                    str(dist) + ',' + \
                                    str(tt[m]['time']) + ',' + \
                                    str(st[0].stats['sampling_rate']) + ',' + \
                                    st[0].stats['network'] + ',' + \
                                    st[0].stats['station'] + \
                                    ',' + st[0].stats['location'] + ',' + \
                                    st[0].stats['channel'] + ',' + \
                                    str(info_sac['stla']) + ',' + \
                                    str(info_sac['stlo']) + ',' + \
                                    str(info_sac['stdp']) + ',' + \
                                    str(info_sac['stel']) + ',' + \
                                    str(quake_d['lat']) + ',' + \
                                    str(quake_d['lon']) + ',' + \
                                    str(quake_d['dp']) + ',' + \
                                    '-----' + ',' + \
                                    str(lat_1) + ',' + \
                                    str(lon_1) + ',' + \
                                    str(lat_2) + ',' + \
                                    str(lon_2) + ',' + \
                                    '-----' + ',' + \
                                    ev_add[k].split('/')[-1] + ',' + \
                                    list_sta[i] + '\n'
                                    
                                #select = open(os.path.join(os.getcwd(), \
                                #    input['file'] + '-' + \
                                #    ev_add[k].split('/')[-1] + '.dat'), 'a')
                                select = open(os.path.join(os.getcwd(), \
                                    input['file'] + '.dat'), 'a')
                                select.writelines(ph_info)
                                select.close()
                            
                            except Exception, e:
                                print e
                
                elif input['all_sta'] != None:
                    
                    ph_info = 'NA' + ',' + 'NA' + ',' + \
                    'NA' + ',' + \
                    str(st[0].stats['sampling_rate']) + ',' + \
                    st[0].stats['network'] + ',' + st[0].stats['station'] + \
                    ',' + st[0].stats['location'] + ',' + \
                    st[0].stats['channel'] + ',' + \
                    str(info_sac['stla']) + ',' + \
                    str(info_sac['stlo']) + ',' + \
                    str(info_sac['stdp']) + ',' + \
                    str(info_sac['stel']) + ',' + \
                    str(quake_d['lat']) + ',' + str(quake_d['lon']) + ',' + \
                    str(quake_d['dp']) + ',' + \
                    ev_add[k].split('/')[-1] + ',' + \
                    list_sta[i] + '\n'
                    
                    '''
                    select = open(os.path.join(os.getcwd(), \
                        input['file'] + '-' + \
                        ev_add[k].split('/')[-1] + '.dat'), 'a')
                    '''
                    select = open(os.path.join(os.getcwd(), \
                        input['file'] + '.dat'), 'a')
                    select.writelines(ph_info)
                    select.close()
            
            except Exception, e:
                print e
                pass
Example #19
0
              color=_c,
              zorder=2,
              sizes=[0] * coords.shape[0])
lwidths = list(np.logspace(np.log(1), np.log(5), 300, base=np.e))

beziers = []
rounded_edges_coords = []
_colors = []
for i in ll.Objects:
    if i == ll.root or isinstance(i, bt.leaf):
        continue
    for j in i.children:
        if j.traits["Location"] != i.traits["Location"]:
            _from = coords[coords["Country"] == i.traits["Location"]]
            _to = coords[coords["Country"] == j.traits["Location"]]
            x, y = m.gcpoints(_from["lng"], _from["lat"], _from["lng"],
                              _from["lat"], 300)
            points = np.array([x, y]).T.reshape(-1, 1, 2)
            segments = np.concatenate([points[:-1], points[1:]], axis=1)
            _c.extend(["#000000"] * 300)
            lc = LineCollection(segments, linewidths=[0] * 300, colors=_c)
            lc = ax.add_collection(lc)
            beziers.append(lc)
            rounded_edges_coords.append([x[0], y[0]])
            _colors.append(
                "#FFFFFF"
            )  # Lines drawn in individual frames. Color set in animate()
rounded_edges = m.scatter([i[0] for i in rounded_edges_coords],
                          [i[1] for i in rounded_edges_coords],
                          sizes=[0] * len(rounded_edges_coords),
                          zorder=1,
                          color="#FFFFFF",
Example #20
0
with open("test_sms.xml", "r") as filetoberead:
    body = filetoberead.readlines()[3:-1] #Read in all the texts
    
freq = {} #Create a database and associate each text with a frequency
for text in body:
    num = sms.get_area(text)
    if num in freq:
        freq[num] += 1
    else:
        freq[num] = 1

codes = sorted(freq, key=freq.get)
results = []
for each in codes:
    results.append(freq[each])
    
print codes[1], results[1]
#results.reverse() #Reversed the values so the color would end up darker for more usage; lighter for lighter usage
    
for i, num in enumerate(codes):
    scale = (ceil(np.log(results[i])))/10 #Creates a log scale for the relative frequencies
    rgb = colorswap(0.3,0.3,scale) #alter the HSV scale to RGB to keep a single color and adjust the tone
    try:
        long2,lat2 = area_codes[int(num)][1:]
        z = n.gcpoints(lat2,long2, lat1,long1,10)
        n.plot(z[0],z[1],color=rgb,linewidth = 1.3)
    except: pass #I have tried to code for many of the exceptions, but i was getting strange area codes which do not exist. Not sure what to do with them....

plt.show()
Example #21
0
 
     # Setup azimuthal equidistant projection basemap for calculating distance 
     # between 2 points
     map = Basemap(width=width,height=width,projection='aeqd',resolution='i',
                 lat_0=lat_0,lon_0=lon_0)
     
     # Calculate the distance between 2 points
     point_0 = map(lon_0, lat_0)
     point_1 = map(lon_1, lat_1)
     distance = np.sqrt((point_1[0] - point_0[0])**2 + (point_1[1] - point_0[1])**2)
     
     # Set the number of points such that the interval between points is 10 km
     number_points = int(distance / 1.e4) + 1.
     
     # Dissect the line connecting the 2 points
     Points = map.gcpoints(lon_0,lat_0,lon_1,lat_1,number_points)
     
     # Check whether the points are on land
     i = 0
     Land = []
     while i < number_points:
         a = (Points[0])[i]
         b = (Points[1])[i]
         Land.append(map.is_land(a,b))
         i += 1
     
     print Land
     
     # List to record landfall raw data
     landfall_raw = []
     
Example #22
0
                    29.56667,
                    linewidth=2,
                    color='g')
#乌鲁木齐
map.drawgreatcircle(116.41667,
                    39.91667,
                    87.68333,
                    43.76667,
                    linewidth=2,
                    color='b')
#拉萨
map.drawgreatcircle(116.41667,
                    39.91667,
                    91.00000,
                    29.60000,
                    linewidth=2,
                    color='g')
#哈尔滨
map.drawgreatcircle(116.41667,
                    39.91667,
                    126.63333,
                    45.75000,
                    linewidth=2,
                    color='b')

x, y = map.gcpoints(116.41667, 39.91667, 40, 20, 50)
map.plot(x, y, linewidth=2, color='b')

#显示结果
plt.show()
Example #23
0
def flat_mutipath_globe(df_travel, path_route, colors, all_starting_countries):
    """
        This is flat structure for multistop 
    """

    plt.figure(figsize=(30, 30))
    m = Basemap(projection='gall')
    m.fillcontinents(color="#61993b", lake_color="#008ECC")
    m.drawmapboundary(fill_color="#5D9BFF")
    m.drawcountries(color='#585858', linewidth=1)
    m.drawstates(linewidth=0.2)
    m.drawcoastlines(linewidth=1)
    for path_rout in path_route:
        if path_rout[0][0] == 'USA;Mexico':
            point_a = df_travel[df_travel.country_or_province_travelled ==
                                path_rout[0][0].split(';')[0]]
            point_b = df_travel[df_travel.country_or_province_travelled ==
                                path_rout[0][0].split(';')[1]]
            point_c = df_travel[df_travel.country_or_province_travelled ==
                                path_rout[0][1]]
            point_d = df_travel[df_travel.country_or_province_travelled ==
                                path_rout[1]]

            x2, y2 = m.gcpoints(point_a["latitude"], point_a["longitude"],
                                point_b["latitude"], point_b["longitude"], 20)
            plt.plot(x2,
                     y2,
                     color=colors[all_starting_countries.index(
                         path_rout[0][0].split(';')[0])],
                     linewidth=3)
            #         m.scatter(point_a["latitude"],point_a["longitude"], marker='^',color="#EC7063", s=500,zorder=5)
            #         plt.text(point_a["latitude"],point_a["longitude"]+10000,path_rout[0][0].split(';')[0].replace('the ', ''),fontsize=20,fontweight='bold',ha='center',va='bottom',color="black")
            x2, y2 = m.gcpoints(point_b["latitude"], point_b["longitude"],
                                point_c["latitude"], point_c["longitude"], 20)
            plt.plot(x2,
                     y2,
                     color=colors[all_starting_countries.index(
                         path_rout[0][0].split(';')[0])],
                     linewidth=3)
            x2, y2 = m.gcpoints(point_c["latitude"], point_c["longitude"],
                                point_d["latitude"], point_d["longitude"], 20)
            plt.plot(x2,
                     y2,
                     color=colors[all_starting_countries.index(
                         path_rout[0][0].split(';')[0])],
                     linewidth=3)
        elif len(path_rout[0]) == 2:
            point_a = df_travel[df_travel.country_or_province_travelled ==
                                path_rout[0][0].replace('the ', '')]
            point_b = df_travel[df_travel.country_or_province_travelled ==
                                path_rout[0][1].replace('the ', '')]
            point_c = df_travel[df_travel.country_or_province_travelled ==
                                path_rout[1].replace('LP', 'LIM')]

            x2, y2 = m.gcpoints(point_a["latitude"], point_a["longitude"],
                                point_b["latitude"], point_b["longitude"], 20)
            plt.plot(x2,
                     y2,
                     color=colors[all_starting_countries.index(
                         path_rout[0][0].replace('the ', ''))],
                     linewidth=3)
            #         m.scatter(x2, y2, marker='^',color="#EC7063", s=500,zorder=5)
            #         plt.text(x2,y2,path_rout[0][0].replace('the ', ''),fontsize=20,fontweight='bold',ha='center',va='bottom',color="black")
            x2, y2 = m.gcpoints(point_b["latitude"], point_b["longitude"],
                                point_c["latitude"], point_c["longitude"], 20)
            plt.plot(x2,
                     y2,
                     color=colors[all_starting_countries.index(
                         path_rout[0][0].replace('the ', ''))],
                     linewidth=3)
        elif len(path_rout[0]) == 3:
            point_a = df_travel[df_travel.country_or_province_travelled ==
                                path_rout[0][0]]
            point_b = df_travel[df_travel.country_or_province_travelled ==
                                path_rout[0][1]]
            point_c = df_travel[df_travel.country_or_province_travelled ==
                                path_rout[0][2]]
            point_d = df_travel[df_travel.country_or_province_travelled ==
                                path_rout[1]]

            x2, y2 = m.gcpoints(point_a["latitude"], point_a["longitude"],
                                point_b["latitude"], point_b["longitude"], 20)
            plt.plot(x2,
                     y2,
                     color=colors[all_starting_countries.index(
                         path_rout[0][0])],
                     linewidth=0.8)
            #         m.scatter(x2, y2, marker='^',color="#EC7063", s=500,zorder=5)
            #         plt.text(x2,y2,path_rout[0][0],fontsize=20,fontweight='bold',ha='center',va='bottom',color="black")
            x2, y2 = m.gcpoints(point_b["latitude"], point_b["longitude"],
                                point_c["latitude"], point_c["longitude"], 20)
            plt.plot(x2,
                     y2,
                     color=colors[all_starting_countries.index(
                         path_rout[0][0])],
                     linewidth=0.8)
            x2, y2 = m.gcpoints(point_c["latitude"], point_c["longitude"],
                                point_d["latitude"], point_d["longitude"], 20)
            plt.plot(x2,
                     y2,
                     color=colors[all_starting_countries.index(
                         path_rout[0][0])],
                     linewidth=3)
        elif len(path_rout[0]) == 4:
            point_a = df_travel[df_travel.country_or_province_travelled ==
                                path_rout[0][0]]
            point_b = df_travel[df_travel.country_or_province_travelled ==
                                path_rout[0][1]]
            point_c = df_travel[df_travel.country_or_province_travelled ==
                                path_rout[0][2]]
            point_d = df_travel[df_travel.country_or_province_travelled ==
                                path_rout[0][3]]
            point_e = df_travel[df_travel.country_or_province_travelled ==
                                path_rout[1]]
            x2, y2 = m.gcpoints(point_a["latitude"], point_a["longitude"],
                                point_b["latitude"], point_b["longitude"], 20)
            plt.plot(x2,
                     y2,
                     color=colors[all_starting_countries.index(
                         path_rout[0][0])],
                     linewidth=3)
            #         m.scatter(x2, y2, marker='^',color="#EC7063", s=500,zorder=5)
            #         plt.text(x2,y2,path_rout[0][0],fontsize=20,fontweight='bold',ha='center',va='bottom',color="black")
            x2, y2 = m.gcpoints(point_b["latitude"], point_b["longitude"],
                                point_c["latitude"], point_c["longitude"], 20)
            plt.plot(x2,
                     y2,
                     color=colors[all_starting_countries.index(
                         path_rout[0][0])],
                     linewidth=3)
            x2, y2 = m.gcpoints(point_c["latitude"], point_c["longitude"],
                                point_d["latitude"], point_d["longitude"], 20)
            plt.plot(x2,
                     y2,
                     color=colors[all_starting_countries.index(
                         path_rout[0][0])],
                     linewidth=3)
            x2, y2 = m.gcpoints(point_d["latitude"], point_d["longitude"],
                                point_e["latitude"], point_e["longitude"], 20)
            plt.plot(x2,
                     y2,
                     color=colors[all_starting_countries.index(
                         path_rout[0][0])],
                     linewidth=3)
    plt.show()
Example #24
0
def select_sta():
    """
    Select required stations
    """

    global input

    map_proj = Basemap(projection='cyl', llcrnrlat=-90,urcrnrlat=90,\
                llcrnrlon=-180,urcrnrlon=180, resolution='c')
    ev_file = open(os.path.join(os.getcwd(), 'quake_req.txt'), 'r')
    ev_add = ev_file.read().split('\n')[:-1]
    select = open(os.path.join(os.getcwd(), input['file'] + '.dat'), 'w')
    select.close()

    for k in range(0, len(ev_add)):
        '''
        select = open(os.path.join(os.getcwd(), \
                input['file'] + '-' + ev_add[k].split('/')[-1] + \
                '.dat'), 'w')
        '''

        (quake_d, quake_t) = read_quake(ev_add[k])

        list_sta = glob.glob(os.path.join(ev_add[k], 'BH', \
                                input['identity']))

        for i in range(0, len(list_sta)):

            try:

                st = read(list_sta[i])
                print '***************************************'
                print str(i) + '/' + str(len(list_sta)) + ' -- ' + \
                        str(k) + '/' + str(len(ev_add))
                print list_sta[i].split('/')[-1]

                info_sac = st[0].stats['sac']

                if input['all_sta'] == None:

                    dist = locations2degrees(lat1 = quake_d['lat'], \
                            long1 = quake_d['lon'], lat2 = info_sac['stla'], \
                            long2 = info_sac['stlo'])
                    tt = getTravelTimes(delta=dist, depth=quake_d['dp'], \
                                            model=input['model'])

                    for m in range(0, len(tt)):

                        if tt[m]['phase_name'] in input['phase']:

                            try:
                                print '--------------------'
                                print list_sta[i].split('/')[-1] + ' has ' + \
                                        tt[m]['phase_name'] + ' phase'

                                if input['freq'] != None:
                                    st[0].decimate(int(round(\
                                        st[0].stats['sampling_rate'])/input['freq']), \
                                        no_filter=False)

                                    if st[0].stats['sampling_rate'] != input[
                                            'freq']:
                                        print list_sta[i].split('/')[-1]
                                        print st[0].stats['sampling_rate']
                                        print '------------------------------------------'
                                '''
                                np_evt = round((events[0]['datetime'] - st[0].stats['starttime'])*st[0].stats['sampling_rate'])
                                np_pha = np_evt + round(tt[m]['time']*st[0].stats['sampling_rate'])
                                
                                select = open(Address_events + '/' + events[l]['event_id'] + '/IRIS/info/' + name_select, 'a')
                                '''
                                if tt[m]['phase_name'] != 'Pdiff':
                                    lat_1 = str(quake_d['lat'])
                                    lon_1 = str(quake_d['lon'])
                                    lat_2 = str(info_sac['stla'])
                                    lon_2 = str(info_sac['stlo'])
                                elif tt[m]['phase_name'] == 'Pdiff':
                                    dist_limit = 97.0
                                    num_gcp = 1000
                                    gcp = map_proj.gcpoints(quake_d['lon'], \
                                            quake_d['lat'], info_sac['stlo'], \
                                            info_sac['stla'], num_gcp)

                                    if dist >= dist_limit:
                                        diff_dist = dist - dist_limit

                                        req_gcp = diff_dist * (float(num_gcp) /
                                                               dist)
                                        req_gcp = round(req_gcp) / 2

                                        mid_p = len(gcp[0]) / 2
                                        #before = int(mid_p - req_gcp)
                                        #after = int(mid_p + req_gcp)
                                        before = mid_p - int(
                                            2.0 * len(gcp[0]) / dist)
                                        after = mid_p + int(
                                            2.0 * len(gcp[0]) / dist)

                                        x_p, y_p = gcp
                                        lat_1 = y_p[before]
                                        lat_2 = y_p[after]
                                        lon_1 = x_p[before]
                                        lon_2 = x_p[after]

                                ph_info = tt[m]['phase_name'] + ',' + \
                                    str(dist) + ',' + \
                                    str(tt[m]['time']) + ',' + \
                                    str(st[0].stats['sampling_rate']) + ',' + \
                                    st[0].stats['network'] + ',' + \
                                    st[0].stats['station'] + \
                                    ',' + st[0].stats['location'] + ',' + \
                                    st[0].stats['channel'] + ',' + \
                                    str(info_sac['stla']) + ',' + \
                                    str(info_sac['stlo']) + ',' + \
                                    str(info_sac['stdp']) + ',' + \
                                    str(info_sac['stel']) + ',' + \
                                    str(quake_d['lat']) + ',' + \
                                    str(quake_d['lon']) + ',' + \
                                    str(quake_d['dp']) + ',' + \
                                    '-----' + ',' + \
                                    str(lat_1) + ',' + \
                                    str(lon_1) + ',' + \
                                    str(lat_2) + ',' + \
                                    str(lon_2) + ',' + \
                                    '-----' + ',' + \
                                    ev_add[k].split('/')[-1] + ',' + \
                                    list_sta[i] + '\n'

                                #select = open(os.path.join(os.getcwd(), \
                                #    input['file'] + '-' + \
                                #    ev_add[k].split('/')[-1] + '.dat'), 'a')
                                select = open(os.path.join(os.getcwd(), \
                                    input['file'] + '.dat'), 'a')
                                select.writelines(ph_info)
                                select.close()

                            except Exception, e:
                                print e

                elif input['all_sta'] != None:

                    ph_info = 'NA' + ',' + 'NA' + ',' + \
                    'NA' + ',' + \
                    str(st[0].stats['sampling_rate']) + ',' + \
                    st[0].stats['network'] + ',' + st[0].stats['station'] + \
                    ',' + st[0].stats['location'] + ',' + \
                    st[0].stats['channel'] + ',' + \
                    str(info_sac['stla']) + ',' + \
                    str(info_sac['stlo']) + ',' + \
                    str(info_sac['stdp']) + ',' + \
                    str(info_sac['stel']) + ',' + \
                    str(quake_d['lat']) + ',' + str(quake_d['lon']) + ',' + \
                    str(quake_d['dp']) + ',' + \
                    ev_add[k].split('/')[-1] + ',' + \
                    list_sta[i] + '\n'
                    '''
                    select = open(os.path.join(os.getcwd(), \
                        input['file'] + '-' + \
                        ev_add[k].split('/')[-1] + '.dat'), 'a')
                    '''
                    select = open(os.path.join(os.getcwd(), \
                        input['file'] + '.dat'), 'a')
                    select.writelines(ph_info)
                    select.close()

            except Exception, e:
                print e
                pass