示例#1
0
    def collection_aspect(self, axis, filename_width, filename_width_height):
        """
        Common part of the test_collection_aspect_[xy] tests.
        """
        mt = [0.91, -0.89, -0.02, 1.78, -1.55, 0.47]

        # Test passing only a width
        # Initialize figure
        fig = plt.figure()
        ax = fig.add_subplot(111)
        # add the beachball (a collection of two patches) to the axis
        # give it an axes to keep make the beachballs circular
        # even though axes are not scaled
        ax.add_collection(
            Beach(mt, width=400, xy=(0, 0), linewidth=.6, axes=ax))
        # set the x and y limits
        ax.axis(axis)
        # create and compare image
        with ImageComparison(self.path, filename_width) as ic:
            fig.savefig(ic.name)

        # Test passing a width and a height
        # Initialize figure
        fig = plt.figure()
        ax = fig.add_subplot(111)
        # add the beachball (a collection of two patches) to the axis
        # give it an axes to keep make the beachballs circular
        # even though axes are not scaled
        ax.add_collection(
            Beach(mt, width=(400, 200), xy=(0, 0), linewidth=.6, axes=ax))
        # set the x and y limits and save the output
        ax.axis(axis)
        # create and compare image
        with ImageComparison(self.path, filename_width_height) as ic:
            fig.savefig(ic.name)
示例#2
0
    def plot_global_map(self):
        """
        Plot global map of event and stations
        """
        # ax = plt.subplot(211)
        plt.title(self.cmtsource.eventname)
        m = Basemap(projection='cyl', lon_0=0.0, lat_0=0.0,
                    resolution='c')
        m.drawcoastlines()
        m.fillcontinents()
        m.drawparallels(np.arange(-90., 120., 30.))
        m.drawmeridians(np.arange(0., 420., 60.))
        m.drawmapboundary()

        x, y = m(self.sta_lon, self.sta_lat)
        m.scatter(x, y, 30, color="r", marker="^", edgecolor="k",
                  linewidth='0.3', zorder=3)

        cmt_lat = self.cmtsource.latitude
        cmt_lon = self.cmtsource.longitude
        focmecs = self.moment_tensor
        ax = plt.gca()
        bb = Beach(focmecs, xy=(cmt_lon, cmt_lat), width=20, linewidth=1,
                   alpha=1.0)
        bb.set_zorder(10)
        ax.add_collection(bb)
示例#3
0
def source_reciever_plot(st, **kwargs):
    """
   Plot source and reciever on map
   """
    save = kwargs.get('save', False)
    topo = kwargs.get('topo', False)
    mt = kwargs.get('moment_tensor', False)
    w = kwargs.get('width', (900000, 900000))
    title = kwargs.get('title', True)
    proj = kwargs.get('proj', 'aeqd')

    m = mapplot(proj,
                lat_0=st[0].stats.sac['evla'],
                lon_0=st[0].stats.sac['evlo'])
    m.drawparallels(np.arange(-80., 81., 20.), labels=[True])
    m.drawmeridians(np.arange(-180., 181., 20.))
    source_coord = add_source(st, m)
    coord_list = stat_coord(st)
    add_station(coord_list, m)
    for ii in range(0, len(coord_list[0]), 2):
        m.drawgreatcircle(source_coord[1],
                          source_coord[0],
                          coord_list[1][ii],
                          coord_list[0][ii],
                          c='k',
                          lw=0.3,
                          alpha=0.3)
    title = os.getcwd().split('/')
    ax = plt.gca()
    x, y = m(st[0].stats.sac['evlo'], st[0].stats.sac['evla'])

    if mt == False:
        try:
            b = beachball(st[0], xy=(x, y), plot='map')
            b.set_zorder(2)
            ax.add_collection(b)
        except KeyError:
            print('No focal mechanism found')
    else:
        b = Beach(mt, width=w, xy=(x, y))
        b.set_zorder(2)
        ax.add_collection(b)

    if title == True:
        ax.set_title('{} \n Depth (km): {} '.format(
            title[5], round(st[0].stats.sac['evdp'], 3)))
    if topo != False:
        myplot.basemap.drawtopography(m, alpha=0.5, cmap=matplotlib.cm.gray)

    if save != False:
        plt.savefig(save + '/map.pdf', format='pdf')
    if save == False:
        plt.show()
示例#4
0
def plot_si_bb_comp(ax, cmt, cmt_init, tag, runfile):
    # get moment tensor
    mt = [cmt.m_rr, cmt.m_tt, cmt.m_pp, cmt.m_rt, cmt.m_rp, cmt.m_tp]
    # plot beach ball
    b = Beach(mt, linewidth=1, xy=(0, 0.6), width=1.5, size=2, facecolor='r')
    ax.add_collection(b)
    # set axis
    ax.set_xlim([-1, 1])
    ax.set_ylim([-1, 1.5])
    ax.set_aspect('equal')
    # magnitude energy change
    dmag = cmt.moment_magnitude - cmt_init.moment_magnitude
    deltam = (cmt.M0 - cmt_init.M0) / cmt_init.M0
    print "delta energy:", deltam, dmag
    text = r"$\Delta$M=%4.3f(%4.3f%%)" % (dmag, deltam * 100.0)
    plt.text(-0.9, -0.3, text, fontsize=7)
    # lat and lon
    text = r"$\Delta$lat=%6.3f$^\circ$; $\Delta$lon=%6.3f$^\circ$" % (
        cmt.latitude - cmt_init.latitude, cmt.longitude - cmt_init.longitude)
    plt.text(-0.9, -0.5, text, fontsize=7)
    # depth
    text = r"$\Delta$dep=%6.3f km;" % (
        (cmt.depth_in_m - cmt_init.depth_in_m) / 1000.0)
    plt.text(-0.9, -0.7, text, fontsize=7)
    ax.set_xticks([])
    ax.set_yticks([])
    # variance reduction
    if os.path.exists(runfile):
        red_val = get_variance_reduction(runfile)
        text = r"$\Delta$Var=%4.3f%%" % (red_val)
        plt.text(-0.9, -0.9, text, fontsize=7)

    text = tag
    plt.text(-0.9, 1.3, text, fontsize=7)
示例#5
0
def plot_si_bb(ax, cmt):
    # get moment tensor
    mt = [float(cmt.m_rr), cmt.m_tt, cmt.m_pp, cmt.m_rt, cmt.m_rp, cmt.m_tp]
    print "inside:", mt
    print mt[0]
    print type(mt[0])
    # plot beach ball
    b = Beach(mt, linewidth=1, xy=(0, 0.6), width=1.5, size=2, facecolor='r')
    ax.add_collection(b)
    # set axis
    ax.set_xlim([-1, 1])
    ax.set_ylim([-1, 1.5])
    ax.set_aspect('equal')
    # magnitude
    text = "Mw=%4.3f" % cmt.moment_magnitude
    plt.text(-0.9, -0.3, text, fontsize=7)
    # lat and lon
    text = "lat=%6.3f$^\circ$; lon=%6.3f$^\circ$" % (cmt.latitude,
                                                     cmt.longitude)
    plt.text(-0.9, -0.5, text, fontsize=7)
    #depth
    text = "dep=%6.3f km;" % (cmt.depth_in_m / 1000.0)
    plt.text(-0.9, -0.7, text, fontsize=7)
    ax.set_xticks([])
    ax.set_yticks([])
    # title
    text = "Init CMT"
    plt.text(-0.9, 1.3, text, fontsize=7)
示例#6
0
def source_reciever_plot(st, **kwargs):
   """
   Plot source and reciever on map
   """
   save = kwargs.get('save',False)
   topo = kwargs.get('topo',False)
   mt = kwargs.get('moment_tensor',False)
   w = kwargs.get('width',(900000,900000))
   title = kwargs.get('title',True)
   proj = kwargs.get('proj','eck4')

   m = mapplot(proj,lat_0=st[0].stats.sac['evla'],lon_0=st[0].stats.sac['evlo'])
   m.drawparallels(np.arange(-80.,81.,20.),labels=[True])
   m.drawmeridians(np.arange(-180.,181.,20.))
   source_coord = add_source(st,m)
   coord_list = stat_coord(st)
   add_station(coord_list,m)
   for ii in range(0,len(coord_list[0]),2):
       m.drawgreatcircle(source_coord[1],source_coord[0],
       coord_list[1][ii],coord_list[0][ii],c='k',lw=0.3,alpha=0.3)
   title = os.getcwd().split('/')
   ax = plt.gca()
   x,y = m(st[0].stats.sac['evlo'],st[0].stats.sac['evla'])

   if mt == False:
       try:
           b = beachball(st[0],xy=(x,y),plot='map')
           b.set_zorder(2)
           ax.add_collection(b)
       except KeyError:
           print('No focal mechanism found')
   else:
       b = Beach(mt,width=w,xy=(x,y))
       b.set_zorder(2)
       ax.add_collection(b)


   if title == True:
       ax.set_title('{} \n Depth (km): {} '.format(
               title[5],round(st[0].stats.sac['evdp'],3)))
   if topo != False:
       myplot.basemap.drawtopography(m,alpha=0.5,cmap=matplotlib.cm.gray)

   if save != False:
       plt.savefig(save+'/map.pdf',format='pdf')
   if save == False:
       plt.show()
示例#7
0
def plot_events(events, map_object):
    """
    """
    for event in events:
        org = event.preferred_origin() or event.origins[0]
        fm = event.preferred_focal_mechanism() or event.focal_mechanisms[0]
        mt = fm.moment_tensor.tensor

        # Add beachball plot.
        x, y = map_object(org.longitude, org.latitude)

        focmec = [mt.m_rr, mt.m_tt, mt.m_pp, mt.m_rt, mt.m_rp, mt.m_tp]
        # Attempt to calculate the best beachball size.
        width = max((map_object.xmax - map_object.xmin,
            map_object.ymax - map_object.ymin)) * 0.020
        b = Beach(focmec, xy=(x, y), width=width, linewidth=1, facecolor="red")
        b.set_zorder(200000000)
        plt.gca().add_collection(b)
示例#8
0
def plot_events(events, map_object):
    """
    """
    for event in events:
        org = event.preferred_origin() or event.origins[0]
        fm = event.preferred_focal_mechanism() or event.focal_mechanisms[0]
        mt = fm.moment_tensor.tensor

        # Add beachball plot.
        x, y = map_object(org.longitude, org.latitude)

        focmec = [mt.m_rr, mt.m_tt, mt.m_pp, mt.m_rt, mt.m_rp, mt.m_tp]
        # Attempt to calculate the best beachball size.
        width = max((map_object.xmax - map_object.xmin,
                     map_object.ymax - map_object.ymin)) * 0.020
        b = Beach(focmec, xy=(x, y), width=width, linewidth=1, facecolor="red")
        b.set_zorder(200000000)
        plt.gca().add_collection(b)
示例#9
0
    def test_collection(self):
        """
        Tests to plot beachballs as collection into an existing axis
        object. The moment tensor values are taken form the
        test_Beachball unit test. See that test for more information about
        the parameters.
        """
        reltol = 1
        if MATPLOTLIB_VERSION < [1, 2, 0]:
            reltol = 20
        mt = [[0.91, -0.89, -0.02, 1.78, -1.55, 0.47],
              [274, 13, 55],
              [130, 79, 98],
              [264.98, 45.00, -159.99],
              [160.55, 76.00, -46.78],
              [1.45, -6.60, 5.14, -2.67, -3.16, 1.36],
              [235, 80, 35],
              [138, 56, 168],
              [1, 1, 1, 0, 0, 0],
              [-1, -1, -1, 0, 0, 0],
              [1, -2, 1, 0, 0, 0],
              [1, -1, 0, 0, 0, 0],
              [1, -1, 0, 0, 0, -1],
              [179, 55, -78],
              [10, 42.5, 90],
              [10, 42.5, 92],
              [150, 87, 1],
              [0.99, -2.00, 1.01, 0.92, 0.48, 0.15],
              [5.24, -6.77, 1.53, 0.81, 1.49, -0.05],
              [16.578, -7.987, -8.592, -5.515, -29.732, 7.517],
              [-2.39, 1.04, 1.35, 0.57, -2.94, -0.94],
              [150, 87, 1]]

        # Initialize figure
        fig = plt.figure(figsize=(6, 6), dpi=300)
        ax = fig.add_subplot(111, aspect='equal')

        # Plot the stations or borders
        ax.plot([-100, -100, 100, 100], [-100, 100, -100, 100], 'rv')

        x = -100
        y = -100
        for i, t in enumerate(mt):
            # add the beachball (a collection of two patches) to the axis
            ax.add_collection(Beach(t, width=30, xy=(x, y), linewidth=.6))
            x += 50
            if (i + 1) % 5 == 0:
                x = -100
                y += 50

        # set the x and y limits and save the output
        ax.axis([-120, 120, -120, 120])
        # create and compare image
        with ImageComparison(self.path, 'bb_collection.png',
                             reltol=reltol) as ic:
            fig.savefig(ic.name)
示例#10
0
def beachball(tr, **kwargs):
    plot = kwargs.get('plot', True)
    coord = kwargs.get('xy', (0, 0))
    w = kwargs.get('width', (900000, 900000))

    ymd = str(tr.stats.starttime + tr.stats.sac['o']).split('-')
    hm = str(tr.stats.starttime + tr.stats.sac['o']).split(':')

    lat = str(round(tr.stats.sac['evla']))
    lon = str(round(tr.stats.sac['evlo']))

    year = str(ymd[0])
    month = str(ymd[1])
    day = str(ymd[2][0:2])

    hour = str(hm[0][-2:])
    min = str(hm[1])

    key = '{}_{}_{}_{}_{}_{}_{}'.format(year, month, day, hour, min, lat, lon)

    if plot == 'map':
        return Beach(list(cmt[key][...]), width=w, xy=coord)
示例#11
0
文件: map.py 项目: wangwu1991/sito
def createMap(ll=None,
              ur=None,
              figsize=None,
              margin=None,
              ax=None,
              dict_basemap=None,
              countries=True,
              lw=1,
              coastlines=True,
              mapboundary=True,
              grid=False,
              grid_labels=True,
              watercolor='#ADD8E6',
              fillcontinents='coral',
              use_lsmask=False,
              stations=None,
              cities=None,
              trench=None,
              earthquake=None,
              slip=None,
              elevation=None,
              elevation_args=(7000, 500, True),
              elevation_offset=None,
              shaded=True,
              shaded_args=(315, 45, 0.2),
              colormap=None,
              title=None,
              show=True,
              save=None,
              station_markersize=4,
              elev_oceans=True,
              grid_lw=None,
              spines_lw=None,
              dpi=None,
              station_labelsize='small',
              loffset=None):
    if figsize:
        fig = plt.figure(figsize=figsize)
        if margin:
            ax = fig.add_axes(margin)
    else:
        fig = None
    if dict_basemap is None:
        dict_basemap = dict(llcrnrlon=-180,
                            llcrnrlat=-60,
                            urcrnrlon=180,
                            urcrnrlat=60,
                            lat_0=0,
                            lon_0=0,
                            projection='hammer',
                            resolution='l')
    elif ll is not None:
        print dict_basemap
        up_dict = dict(llcrnrlon=ll[1],
                       llcrnrlat=ll[0],
                       urcrnrlon=ur[1],
                       urcrnrlat=ur[0])
        dict_basemap.update(up_dict)
    m = Basemap(ax=ax, **dict_basemap)
    if fillcontinents and use_lsmask:
        m.drawlsmask(land_color=fillcontinents, ocean_color='white')
    elif fillcontinents:
        m.fillcontinents(color=fillcontinents, lake_color=watercolor, zorder=0)
    if countries:
        m.drawcountries(linewidth=lw)
    if coastlines:
        m.drawcoastlines(linewidth=lw)
    if mapboundary:
        m.drawmapboundary(fill_color=watercolor, zorder=-10)
    print 1
    if grid or grid_labels:
        if not grid_lw:
            grid_lw = lw
        if grid is True:
            grid = 1.
        #JGR
        if grid and grid_labels:
            m.drawparallels(np.arange(-90., 90., grid),
                            labels=[True, True, False, False],
                            linewidth=grid_lw,
                            xoffset=loffset,
                            yoffset=loffset,
                            size='small')
            m.drawmeridians(np.arange(0., 390., grid),
                            labels=[False, False, True, True],
                            linewidth=grid_lw,
                            xoffset=loffset,
                            yoffset=loffset,
                            size='small')
        elif grid:
            m.drawparallels(np.arange(-90., 90., grid),
                            labels=[False, False, False, False],
                            linewidth=grid_lw)
            m.drawmeridians(np.arange(0., 390., grid),
                            labels=[False, False, False, False],
                            linewidth=grid_lw)
    if stations:
        stations.plot(m,
                      mfc='b',
                      ms=station_markersize,
                      zorder=10,
                      lsize=station_labelsize)
    if slip:
        if len(slip) == 4:
            x, y, z, levels = slip
            colors_slip = None
        else:
            x, y, z, levels, colors_slip = slip
        x, y = zip(*[m(lon, lat) for lon, lat in zip(x, y)])
        if len(np.shape(z)) == 2:
            grid_x = x
            grid_y = y
        else:
            grid_x = np.arange(
                min(x),
                max(x) - 0.15 * (max(x) - min(x)),
                100)  #VERY dirty hack to cut of parts of the slip model
            grid_y = np.arange(min(y), max(y), 100)
            #grid_x, grid_y = np.mgrid[min(x):max(x):100j, min(y):max(y):100j]
            z = scipy.interpolate.griddata((x, y),
                                           z,
                                           (grid_x[None, :], grid_y[:, None]),
                                           method='cubic')

        plt.gca().contour(grid_x, grid_y, z, levels, colors=colors_slip, lw=lw)
    if earthquake == 'Tocopilla':
        x, y = m(-70.06, -22.34)
        x2, y2 = m(-69.5, -24.2)  #x2, y2 = m(-70.4, -21.5)
        m.plot((x, x2), (y, y2), 'k-', lw=lw)  #line
        m.plot((x), (y), 'r*', ms=2 * station_markersize,
               zorder=10)  #epicenter
        b = Beach([358, 26, 109], xy=(x2, y2), width=50000, linewidth=lw)
        b.set_zorder(10)
        plt.gca().add_collection(b)
        plt.annotate(
            '14 Nov. 2007\n M 7.7',
            (x2, y2),
            xytext=(15, 0),  # 22
            textcoords='offset points',
            va='center',
            size=station_labelsize)
    elif earthquake == 'Tocopilla_beachball':
        #x, y = m(-70.06, -22.34)
        x2, y2 = m(-69.5, -24.2)  #x2, y2 = m(-70.4, -21.5)
        b = Beach([358, 26, 109], xy=(x2, y2), width=50000, linewidth=lw)
        b.set_zorder(10)
        plt.gca().add_collection(b)
        plt.annotate('14 Nov. 2007\n M 7.6', (x2, y2),
                     xytext=(22, 0),
                     textcoords='offset points',
                     va='center')

    elif earthquake == 'Tocopilla_position':
        x, y = m(-70.06, -22.34)
        m.plot((x), (y), 'r*', ms=15, zorder=10)  #epicenter
    elif earthquake:
        xs, ys = zip(*[m(lon, lat) for lon, lat in zip(*earthquake[:2])])
        m.plot(xs, ys, 'r*', ms=15, zorder=10)  #epicenters
        if len(earthquake) == 3:
            for i in range(len(xs)):
                x, y, mag = xs[i], ys[i], earthquake[2][i]
                plt.annotate('M%.1f' % mag,
                             xy=(x, y),
                             xytext=(-5, -15),
                             textcoords='offset points',
                             va='center')
        elif len(earthquake) > 3:
            for i in range(len(xs)):
                x, y, mag, date = xs[i], ys[i], earthquake[2][i], earthquake[
                    3][i]
                plt.annotate('M%.1f\n%s' % (mag, date.date),
                             xy=(x, y),
                             xytext=(10, 0),
                             textcoords='offset points',
                             va='center')
    print 2
    if elevation:
        vmax, resol, bar = elevation_args
        geo = gdal.Open(elevation)
        topoin = geo.ReadAsArray()
        if elevation_offset:
            topoin[topoin > 0] += elevation_offset
        coords = geo.GetGeoTransform()
        nlons = topoin.shape[1]
        nlats = topoin.shape[0]
        delon = coords[1]
        delat = coords[5]
        lons = coords[0] + delon * np.arange(nlons)
        lats = coords[3] + delat * np.arange(nlats)[::-1]  # reverse lats
        # create masked array, reversing data in latitude direction
        # (so that data is oriented in increasing latitude,
        # as transform_scalar requires).
        topoin = np.ma.masked_less(topoin[::-1, :], -11000)
        #topoin = gaussian_filter(topoin, 1)
        #topoin = array[::-1, :]
        # transform DEM data to a 250m native projection grid

        #            if True:
        #                x, y = m(*np.meshgrid(lons, lats))
        #                m.contourf(x, y, topoin, 100, cm=colormap)
        #                if save:
        #                    plt.savefig(save)
        #                return
        if resol:
            if resol < 25:
                nx = resol * len(lons)
                ny = resol * len(lats)
            else:
                nx = int((m.xmax - m.xmin) / resol) + 1
                ny = int((m.ymax - m.ymin) / resol) + 1
        else:
            nx = len(lons)
            ny = len(lats)
        topodat = m.transform_scalar(topoin, lons, lats, nx, ny, masked=True)
        if elevation == 'CleanTopo2_nchile.tif':
            # -10,701m(0) to 8,248m(18948)
            topodat = topodat - 10701
        if (isinstance(colormap, basestring) and os.path.isfile(colormap)
                and colormap.endswith('.gpf')):
            colormap = createColormapFromGPF(colormap)
        if shaded:
            azdeg, altdeg, fraction = shaded_args
            ls = colors.LightSource(azdeg=azdeg, altdeg=altdeg)
            # convert data to rgb array including shading from light source.
            if elev_oceans:
                rgb = colormap(0.5 * topodat / vmax + 0.5)
            else:
                rgb = colormap(topodat / vmax)
            rgb1 = ls.shade_rgb(rgb, elevation=topodat, fraction=fraction)
            rgb[:, :, 0:3] = rgb1
            m.imshow(rgb, zorder=1)
        else:
            if elev_oceans:
                m.imshow(topodat,
                         interpolation='bilinear',
                         cmap=colormap,
                         zorder=1,
                         vmin=-vmax,
                         vmax=vmax)
            else:
                m.imshow(topodat,
                         interpolation='bilinear',
                         cmap=colormap,
                         zorder=1,
                         vmin=0,
                         vmax=vmax)

        if bar:
            ax = plt.gca()
            fig = plt.gcf()
            #cb_ax = fig.add_axes([0.8, 0.3, 0.02, 0.4])
            cb_ax = fig.add_axes([0.82, 0.3, 0.02, 0.4])
            cb = colorbar.ColorbarBase(cb_ax,
                                       cmap=colormap,
                                       norm=colors.Normalize(vmin=-vmax,
                                                             vmax=vmax))
            #cb.set_label('elevation and bathymetry')
            ticks = (np.arange(20) - 10) * 1000
            ticks = ticks[np.abs(ticks) <= vmax]
            cb.set_ticks(ticks)
            tls = ['%dm' % i if i % 2000 == 0 else '' for i in ticks]
            cb.set_ticklabels(tls)
            plt.axes(ax)  # make the original axes current again
    if cities == 'ipoc':
        cities = 'Antofagasta Tocopilla Iquique Calama Pisagua Arica'.split()
        lons = [-70.4, -70.2, -70.1525, -68.933333, -70.216667, -70.333333]
        lats = [-23.65, -22.096389, -20.213889, -22.466667, -19.6, -18.483333]
        x, y = m(lons[:len(cities)], lats[:len(cities)])
        m.plot(x, y, 'o', ms=station_markersize, mfc='w', mec='k', zorder=10)
        for i in range(len(cities)):
            if 'Anto' in cities[i]:
                plt.annotate(cities[i], (x[i], y[i]),
                             xytext=(5, 0),
                             textcoords='offset points',
                             va='top',
                             size=station_labelsize)
            else:
                plt.annotate(cities[i], (x[i], y[i]),
                             xytext=(-5, 0),
                             textcoords='offset points',
                             ha='right',
                             size=station_labelsize)
    elif cities == 'Tocopilla':
        lons = [-70.2]
        lats = [-22.096389]
        x, y = m(lons, lats)
        m.plot(x, y, 'o', ms=station_markersize, mfc='w', mec='k', zorder=10)
        plt.annotate('Tocopilla', (x[0], y[0]),
                     xytext=(5, 0),
                     textcoords='offset points',
                     size=station_labelsize)

    if trench == 'ipoc':
        coords = np.transpose(
            np.loadtxt('/home/richter/Data/map/'
                       'nchile_trench.txt'))
        import matplotlib as mpl  # hack JGR
        mpl.rcParams.update({'lines.linewidth': 1})
        plotTrench(m,
                   coords[0, :],
                   coords[1, :],
                   facecolors='k',
                   edgecolors='k')
    if spines_lw:
        for l in plt.gca().spines.values():
            l.set_linewidth(spines_lw)
    if title:
        plt.title(title, y=1.05)
    if save:
        plt.savefig(save, dpi=dpi)
    if show:
        plt.show()
    return m
示例#12
0
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.basemap import Basemap
from obspy.imaging.beachball import Beach

m = Basemap(projection='cyl', lon_0=142.36929, lat_0=38.3215, resolution='c')

m.drawcoastlines()
m.fillcontinents()
m.drawparallels(np.arange(-90., 120., 30.))
m.drawmeridians(np.arange(0., 420., 60.))
m.drawmapboundary()

x, y = m(142.36929, 38.3215)
focmecs = [0.136, -0.591, 0.455, -0.396, 0.046, -0.615]

ax = plt.gca()
b = Beach(focmecs, xy=(x, y), width=10, linewidth=1, alpha=0.85)
b.set_zorder(10)
ax.add_collection(b)
plt.show()
示例#13
0
  def plot_misfit(self, event_id, window_id, out_file=None):
    """Plot misfit for a certain event and window_id  
    """
    # CC0 map  | CC0 v.s. SNR (size ~ weight)
    #------------|-----------------
    # DTcc map   | avg. CC0      

    # check inputs
    events = self.data['events']
    if event_id not in events:
      raise Exception("[ERROR] %s does NOT exist. Exit" % (event_id))
      sys.exit()
    event = events[event_id]
    stations = event['stations']

    # get list of station,window id
    #sta_win_id_list = []
    stla_list = []
    stlo_list = []
    cc_dt_list = []
    CC0_list = []
    CCmax_list = []
    snr_list = []
    weight_list = []
    for station_id in stations:
      station = stations[station_id]
      windows = station['windows']

      # skip bad station 
      if station['stat']['code'] < 0:
        continue

      if window_id not in windows:
        continue

      window = windows[window_id]
      if window['stat']['code'] != 1:
        continue

      meta = station['meta']
      misfit = window['misfit']
      quality = window['quality']

      #sta_win_id = (station_id, window_id)
      #sta_win_id_list.append(sta_win_id)
      stla_list.append(meta['latitude'])
      stlo_list.append(meta['longitude'])
      cc_dt_list.append(misfit['CC_time_shift'])
      CC0_list.append(misfit['CC0'])
      CCmax_list.append(misfit['CCmax'])
      snr_list.append(quality['SNR'])
      weight_list.append(window['weight'])

    # get event data
    gcmt = event['gcmt']
    evla = gcmt['latitude']
    evlo = gcmt['longitude']
    M = gcmt['moment_tensor']
    Mrr = M[0][0]
    Mtt = M[1][1]
    Mpp = M[2][2]
    Mrt = M[0][1]
    Mrp = M[0][2]
    Mtp = M[1][2]
    focmec = [ Mrr, Mtt, Mpp, Mrt, Mrp, Mtp ]

    # map range
    min_lat = min(min(stla_list), evla)
    max_lat = max(max(stla_list), evla)
    lat_range = max_lat - min_lat
    min_lat -= 0.1*lat_range
    max_lat += 0.1*lat_range
    min_lon = min(min(stlo_list), evlo)
    max_lon = max(max(stlo_list), evlo)
    lon_range = max_lon - min_lon
    min_lon -= 0.1*lon_range
    max_lon += 0.1*lon_range
    #lat_true_scale = np.mean(stla_list)
    lat_0 = np.mean(stla_list)
    lon_0 = np.mean(stlo_list)
    # 
    parallels = np.arange(0.,81,10.)
    meridians = np.arange(0.,351,10.)

    # figure size
    fig = plt.figure(figsize=(11, 8.5))
    str_title = '%s %s' % (event_id, window_id)
    fig.text(0.5, 0.95, str_title, size='x-large', 
        horizontalalignment='center')

    #------ color map CC_time_shift, symbol size ~ SNR 
    ax = fig.add_axes([0.05, 0.5, 0.4, 0.35])
    ax.set_title("DT_cc (symbol_size ~ SNR)")

    m = Basemap(projection='merc', resolution='l',
        llcrnrlat=min_lat, llcrnrlon=min_lon, 
        urcrnrlat=max_lat, urcrnrlon=max_lon,
        lat_0=lat_0, lon_0=lon_0 )
    m.drawcoastlines(linewidth=0.1)
    m.drawcountries(linewidth=0.1)
    m.drawparallels(parallels, linewidth=0.1, labels=[1,0,0,1])
    m.drawmeridians(meridians, linewidth=0.1, labels=[1,0,0,1])
    
    # CC_time_shift, SNR
    sx, sy = m(stlo_list, stla_list)
    size_list = [ 0.1 if x<0.1 else x for x in snr_list ]
    im = m.scatter(sx, sy, s=size_list, marker='o',
        c=cc_dt_list, cmap='seismic', 
        edgecolor='grey', linewidth=0.05)
    mean_amp = np.mean(cc_dt_list)
    std_amp = np.std(cc_dt_list)
    #plot_amp = abs(mean_amp)+std_amp
    plot_amp = 5.0 
    im.set_clim(-plot_amp, plot_amp)
    
    # focal mechanism
    sx, sy = m(evlo, evla)
    b = Beach(focmec, xy=(sx, sy), width=200000, linewidth=0.2, 
        facecolor='k')
    ax.add_collection(b)
    
    # colorbar
    cbar_ax = fig.add_axes([0.46, 0.575, 0.005, 0.2])
    fig.colorbar(im, cax=cbar_ax, orientation="vertical")
    cbar_ax.tick_params(labelsize=9)
    cbar_ax.set_xlabel('DT_cc(s)', fontsize=9)
    cbar_ax.xaxis.set_label_position('top')
   
    #------ color map CC0, symbol size ~ SNR
    ax = fig.add_axes([0.05, 0.05, 0.4, 0.35])
    ax.set_title("CC0 (symbol_size ~ SNR)")

    m = Basemap(projection='merc', resolution='l',
        llcrnrlat=min_lat, llcrnrlon=min_lon, 
        urcrnrlat=max_lat, urcrnrlon=max_lon,
        lat_0=lat_0, lon_0=lon_0 )
    m.drawcoastlines(linewidth=0.1)
    m.drawcountries(linewidth=0.1)
    m.drawparallels(parallels, linewidth=0.1, labels=[1,0,0,1])
    m.drawmeridians(meridians, linewidth=0.1, labels=[1,0,0,1])
    
    # CC0, SNR 
    sx, sy = m(stlo_list, stla_list)
    #size_list = [ 20**x for x in CCmax_list ]
    size_list = [ 0.1 if x<0.1 else x for x in snr_list ]
    im = m.scatter(sx, sy, s=size_list, marker='o',
        c=CC0_list, cmap='jet', 
        edgecolor='grey', linewidth=0.05)
    im.set_clim(0.5, 1.0)
    
    # focal mechanism
    sx, sy = m(evlo, evla)
    b = Beach(focmec, xy=(sx, sy), width=200000, linewidth=0.2, 
        facecolor='k')
    ax.add_collection(b)
 
    #add colorbar
    cbar_ax = fig.add_axes([0.46, 0.125, 0.005, 0.2])
    fig.colorbar(im, cax=cbar_ax, orientation="vertical")
    cbar_ax.tick_params(labelsize=9) 
    cbar_ax.set_xlabel('CC0', fontsize=9)
    cbar_ax.xaxis.set_label_position('top')

    #------ SNR v.s. CC0, colored by cc_dt, size ~ weight
    ax = fig.add_axes([0.58, 0.65, 0.35, 0.2])
    im = ax.scatter(snr_list, CC0_list, marker='o', 
        s=10.*np.array(weight_list), 
        c=cc_dt_list, cmap='seismic',
        edgecolor='grey', linewidth=0.05)
    mean_amp = np.mean(cc_dt_list)
    std_amp = np.std(cc_dt_list)
    #plot_amp = abs(mean_amp)+std_amp
    plot_amp = 5.0
    im.set_clim(-plot_amp, plot_amp)
    #ax.set_xlim([min(snr_list), max(snr_list)])
    #ax.set_ylim([min(CCmax_list), max(CCmax_list)])
    ax.set_xlim([0, max(snr_list)])
    ax.set_ylim([0.3, 1.0])
    ax.set_xlabel("SNR")
    ax.set_ylabel("CC0")
    #add colorbar
    cbar_ax = fig.add_axes([0.95, 0.65, 0.005, 0.2])
    fig.colorbar(im, cax=cbar_ax, orientation="vertical")
    cbar_ax.tick_params(labelsize=9)
    cbar_ax.set_xlabel('DT_cc(s)', fontsize=9)
    cbar_ax.xaxis.set_label_position('top')

    ##------ CC0 v.s. CCmax, colored by cc_dt
    #ax = fig.add_axes([0.58, 0.375, 0.35, 0.2])
    #im = ax.scatter(CC0_list, CCmax_list, marker='o', s=10,
    #    c=cc_dt_list, cmap='seismic',
    #    edgecolor='grey', linewidth=0.05)
    #mean_amp = np.mean(cc_dt_list)
    #std_amp = np.std(cc_dt_list)
    #plot_amp = abs(mean_amp)+std_amp
    #im.set_clim(-plot_amp, plot_amp)
    #ax.set_xlim([min(CC0_list), max(CC0_list)])
    #ax.set_ylim([min(CCmax_list), max(CCmax_list)])
    #ax.set_xlabel("CC0")
    #ax.set_ylabel("CCmax")
    ##add colorbar
    #cbar_ax = fig.add_axes([0.95, 0.375, 0.005, 0.2])
    #fig.colorbar(im, cax=cbar_ax, orientation="vertical")
    #cbar_ax.tick_params(labelsize=9)
    #cbar_ax.set_xlabel('cc_dt(s)', fontsize=9)
    #cbar_ax.xaxis.set_label_position('top')

    ##------ cc_dt v.s. CCmax, colored by SNR
    #ax = fig.add_axes([0.58, 0.1, 0.35, 0.2])
    #im = ax.scatter(cc_dt_list, CCmax_list, marker='o', s=10, 
    #    c=snr_list, cmap='seismic',
    #    edgecolor='grey', linewidth=0.05)
    #im.set_clim(min(snr_list), max(snr_list))
    #ax.set_xlim([min(cc_dt_list), max(cc_dt_list)])
    #ax.set_ylim([min(CCmax_list), max(CCmax_list)])
    #ax.set_xlabel("cc_dt")
    #ax.set_ylabel("CCmax")
    ##add colorbar
    #cbar_ax = fig.add_axes([0.95, 0.1, 0.005, 0.2])
    #fig.colorbar(im, cax=cbar_ax, orientation="vertical")
    #cbar_ax.tick_params(labelsize=9)
    #cbar_ax.set_xlabel('SNR(dB)', fontsize=9)
    #cbar_ax.xaxis.set_label_position('top')

    ##------ histogram of dt_cc and dt_res
    #ax1 = fig.add_axes([0.5,0.28,0.4,0.15])
    #n, bins, patches = ax1.hist(dt_cc, 50, facecolor='green', alpha=0.75)
    #amp = max(abs(dt_cc))
    #ax1.set_xlim([-amp, amp])
    #ax1.set_title('dt_cc: mean=%.2f std=%.2f' % (np.mean(dt_cc), np.std(dt_cc)))
    #ax1.tick_params(labelsize=10) 
    #
    #ax2 = fig.add_axes([0.5,0.07,0.4,0.15])
    #n, bins, patches = ax2.hist(dt_res, 50, facecolor='green', alpha=0.75)
    #amp = max(abs(dt_cc))
    #ax2.set_xlim([-amp, amp])
    #ax2.set_title('dt_res: mean=%.2f std=%.2f' % (np.mean(dt_res), np.std(dt_res)))
    #ax2.set_xlabel('dt (sec)')
    #ax2.tick_params(labelsize=10)

    #------ save figure
    if not out_file:
      out_file = '%s_%s.pdf' % (event_id, window_id)
    fig.savefig(out_file, format='pdf')
示例#14
0
from matplotlib import rc as matplotlibrc
matplotlibrc('figure.subplot', right=1.00, bottom=0.00, left=0.00, top=1.00)
import matplotlib.pylab as plt
from obspy.imaging.beachball import Beach
import os

# Moment tensors.
mt = [[264.98, 45.00, -159.99], [130, 79, 98],
      [0.99, -2.00, 1.01, 0.92, 0.48, 0.15],
      [-2.39, 1.04, 1.35, 0.57, -2.94, -0.94]]

# Initialize figure
fig = plt.figure(1, figsize=(4, 1), dpi=100)
ax = fig.add_subplot(111, aspect='equal')

x = -100
y = -100
for i, t in enumerate(mt):
    ax.add_collection(Beach(t, size=100, width=35, xy=(x, y), linewidth=.6))
    x += 50
    if (i + 1) % 5 == 0:
        x = -100
        y += 50
# Set the x and y limits, disable the ticks and save the output
ax.axis([-125, 75, -125, -75])
ax.set_xticks([])
ax.set_yticks([])
for _i in ax.spines.values():
    _i.set_linewidth(0)
fig.savefig('beachball-collection.pdf')
示例#15
0
x, y = m(lons, lats)
m.scatter(x,
          y,
          30,
          color="r",
          marker="^",
          edgecolor="k",
          linewidth='0.3',
          zorder=3)

focmecs = [
    moment_tensor,
]
ax = plt.gca()
for i in range(len(focmecs)):
    b = Beach(focmecs[i], xy=(cmt_lon, cmt_lat), width=10, linewidth=1)
    b.set_zorder(10)
    ax.add_collection(b)

earth_hc, _, _ = gps2DistAzimuth(0, 0, 0, 180)
##plot azimuth and distance distribution
theta = []
radius = []
for i in range(len(lons)):
    geo_info = gps2DistAzimuth(cmt_lat, cmt_lon, lats[i], lons[i])
    #geo_info = gps2DistAzimuth(lats[i], lons[i], cmt_loc[0], cmt_loc[1])
    #print geo_info
    theta.append(geo_info[1] / 180.0 * np.pi)
    radius.append(geo_info[0] / earth_hc)

ax = plt.subplot(223, polar=True)
示例#16
0
文件: mapa.py 项目: ndperezg/mapa_foc
from obspy.imaging.beachball import Beach

focmec, lat, lon = [], [], []
datos = open('datos.txt')

counter = 0
for line in datos:
    if counter > 0:
        focmec.append([float(line.split('\t')[7]),float(line.split('\t')[9]),float(line.split('\t')[9])])
        lat.append(float(line.split('\t')[1]))
        lon.append(float(line.split('\t')[2]))
    counter+= 1



map = Basemap(llcrnrlon=-83.5,llcrnrlat=-4.5,urcrnrlon=-76,urcrnrlat=6, projection='cyl', resolution=None)
#map.drawcoastlines()



x, y = map(lon, lat)
#map.scatter(x, y, 200, color="r", marker="v", edgecolor="k", zorder=3)

ax = plt.gca()
for i in range(len(focmec)):
    b = Beach(focmec[i], xy=(x[i], y[i]), width=0.35, linewidth=1)
    b.set_zorder(1)
    ax.add_collection(b)

map.arcgisimage(service='NatGeo_World_Map', xpixels = 1500, verbose= True)
plt.show()
示例#17
0
def plot_seismicity(input_dics, events):
    """
    create a seismicity map with some basic statistical analysis on the results
    :param input_dics:
    :param events:
    :return:
    """
    print('\n==============')
    print('Seismicity map')
    print('==============\n')

    # plt.rc('font', family='serif')
    if not len(events) > 0:
        print("[WARNING] no event passed the given criteria!")
        print("[WARNING] can not create any seismicity map.")
        return

    if input_dics['evlatmin'] is None:
        input_dics['evlatmin'] = -90
        input_dics['evlatmax'] = +90
        input_dics['evlonmin'] = -180
        input_dics['evlonmax'] = +180
        map_proj = 'cyl'
    else:
        map_proj = 'cyl'

    # set-up the map
    m = Basemap(projection=map_proj,
                llcrnrlat=input_dics['evlatmin'],
                urcrnrlat=input_dics['evlatmax'],
                llcrnrlon=input_dics['evlonmin'],
                urcrnrlon=input_dics['evlonmax'],
                lon_0=input_dics['plot_lon0'],
                resolution='l')

    parallels = np.arange(-90, 90, 30.)
    m.drawparallels(parallels, fontsize=24)
    meridians = np.arange(-180., 180., 60.)
    m.drawmeridians(meridians, fontsize=24)

    raw_input_resp = raw_input_built('choose the map style:\n'
                                     '1. bluemarble (PIL should be installed)\n'
                                     '2. etopo (PIL should be installed)\n'
                                     '3. shadedrelief (PIL should be installed)\n'
                                     '4. simple\n')
    if int(raw_input_resp) == 1:
        m.bluemarble(scale=0.5)
    elif int(raw_input_resp) == 2:
        m.etopo(scale=0.5)
    elif int(raw_input_resp) == 3:
        m.shadedrelief(scale=0.1)
    else:
        m.fillcontinents()

    # defining labels
    x_ev, y_ev = m(-360, 0)
    m.scatter(x_ev, y_ev, 20, color='red', marker="o",
              edgecolor="black", zorder=10, label='0-70km')
    m.scatter(x_ev, y_ev, 20, color='green', marker="o",
              edgecolor="black", zorder=10, label='70-300km')
    m.scatter(x_ev, y_ev, 20, color='blue', marker="o",
              edgecolor="black", zorder=10, label='300< km')

    m.scatter(x_ev, y_ev, 10, color='white', marker="o",
              edgecolor="black", zorder=10, label='< 4.0')
    m.scatter(x_ev, y_ev, 40, color='white', marker="o",
              edgecolor="black", zorder=10, label='4.0-5.0')
    m.scatter(x_ev, y_ev, 70, color='white', marker="o",
              edgecolor="black", zorder=10, label='5.0-6.0')
    m.scatter(x_ev, y_ev, 100, color='white', marker="o",
              edgecolor="black", zorder=10, label='6.0<=')

    ev_dp_all = []
    ev_mag_all = []
    ev_info_ar = np.array([])
    plot_focal_mechanism = False
    for ev in events:
        x_ev, y_ev = m(float(ev['longitude']), float(ev['latitude']))
        ev_dp_all.append(abs(float(ev['depth'])))
        ev_mag_all.append(abs(float(ev['magnitude'])))

        if abs(float(ev['depth'])) < 70.0:
            color = 'red'
        elif 70.0 <= abs(float(ev['depth'])) < 300.0:
            color = 'green'
        elif 300.0 <= abs(float(ev['depth'])):
            color = 'blue'

        if float(ev['magnitude']) < 4.0:
            size = 10
        elif 4.0 <= float(ev['magnitude']) < 5.0:
            size = 40
        elif 5.0 <= float(ev['magnitude']) < 6.0:
            size = 70
        elif 6.0 <= float(ev['magnitude']):
            size = 100

        if ev['focal_mechanism']:
            plot_focal_mechanism = True
            f1 = ev['focal_mechanism'][0]
            f2 = ev['focal_mechanism'][1]
            f3 = ev['focal_mechanism'][2]
            f4 = ev['focal_mechanism'][3]
            f5 = ev['focal_mechanism'][4]
            f6 = ev['focal_mechanism'][5]
        else:
            f1 = False
            f2 = False
            f3 = False
            f4 = False
            f5 = False
            f6 = False
        if np.size(ev_info_ar) < 1:
            ev_info_ar = np.append(ev_info_ar,
                                   [float(ev['depth']), float(x_ev),
                                    float(y_ev), size, color,
                                    f1, f2, f3, f4, f5, f6])
        else:
            ev_info_ar = np.vstack((ev_info_ar,
                                    [float(ev['depth']), float(x_ev),
                                     float(y_ev), size, color,
                                     f1, f2, f3, f4, f5, f6]))

    if np.shape(ev_info_ar)[0] == np.size(ev_info_ar):
        ev_info_ar = np.reshape(ev_info_ar, (1, 11))
    else:
        ev_info_ar = sorted(ev_info_ar,
                            key=lambda ev_info_iter: float(ev_info_iter[0]))

    for ev in ev_info_ar:
        m.scatter(float(ev[1]), float(ev[2]), float(ev[3]),
                  color=ev[4], marker="o", edgecolor='k', zorder=10)

    plt.legend(bbox_to_anchor=(1.01, 1), loc=2, borderaxespad=0.)

    if plot_focal_mechanism:
        plt.figure()

        m = Basemap(projection=map_proj,
                    llcrnrlat=input_dics['evlatmin'],
                    urcrnrlat=input_dics['evlatmax'],
                    llcrnrlon=input_dics['evlonmin'],
                    urcrnrlon=input_dics['evlonmax'],
                    lon_0=input_dics['plot_lon0'],
                    resolution='l')

        parallels = np.arange(-90, 90, 30.)
        m.drawparallels(parallels, fontsize=24)
        meridians = np.arange(-180., 180., 60.)
        m.drawmeridians(meridians, fontsize=24)

        if int(raw_input_resp) == 1:
            m.bluemarble(scale=0.5)
        elif int(raw_input_resp) == 2:
            m.etopo(scale=0.5)
        elif int(raw_input_resp) == 3:
            m.shadedrelief(scale=0.1)
        else:
            m.fillcontinents()

        for evfoc in ev_info_ar:
            focmec = False
            try:
                ax = plt.gca()
                focmec = (float(evfoc[5]), float(evfoc[6]), float(evfoc[7]),
                          float(evfoc[8]), float(evfoc[9]), float(evfoc[10]))
                b = Beach(focmec, xy=(float(evfoc[1]), float(evfoc[2])),
                          facecolor=evfoc[4], width=float(evfoc[3])/100.,
                          linewidth=1, alpha=0.85)
                b.set_zorder(10)
                ax.add_collection(b)
            except Exception as error:
                print('[EXCEPTION] focal mechanism:')
                print(focmec)
                print('[EXCEPTION] error: %s' % error)

    if len(events) > 0:
        plt.figure()
        hn, hbins, hpatches = \
            plt.hist(ev_dp_all, input_dics['depth_bins_seismicity'],
                     facecolor='g', edgecolor='k', lw=3, alpha=0.5, log=True)

        plt.xlabel('Depth', size=32, weight='bold')
        plt.ylabel('#Events (log)', size=32, weight='bold')
        plt.yscale('log')
        plt.ylim(ymin=0.2)
        plt.xticks(size=24, weight='bold')
        plt.yticks(size=24, weight='bold')
        plt.tight_layout()
        plt.grid(True)

        plt.figure()
        hn, hbins, hpatches = \
            plt.hist(ev_mag_all,
                     bins=np.linspace(int(float(input_dics['min_mag'])),
                                      int(float(input_dics['max_mag'])),
                                      (int(float(input_dics['max_mag'])) -
                                       int(float(input_dics['min_mag'])))*2+1),
                     facecolor='g', edgecolor='k', lw=3, alpha=0.5, log=True)

        plt.xlabel('Magnitude', size=32, weight='bold')
        plt.ylabel('#Events (log)', size=32, weight='bold')
        plt.yscale('log')
        plt.ylim(ymin=0.2)
        plt.xticks(size=24, weight='bold')
        plt.yticks(size=24, weight='bold')
        plt.tight_layout()
        plt.grid(True)

    plt.show()
示例#18
0
def plot_hist_mt(psmeca_dict,
                 figsize=(16, 24),
                 mt_size=10,
                 pretty=False,
                 resolution='l'):
    if psmeca_dict['psmeca'] != []:
        psmeca = psmeca_dict['psmeca']
        #get the latitudes, longitudes, and the 6 independent component
        lats = psmeca[:, 1]
        lons = psmeca[:, 0]
        focmecs = psmeca[:, 3:9]
        depths = psmeca[:, 2]
        (llat, ulat, llon, ulon) = psmeca_dict['range']
        evla = psmeca_dict['evloc'][0]
        evlo = psmeca_dict['evloc'][1]

        plt.figure(figsize=figsize)
        m = Basemap(projection='cyl',
                    lon_0=142.36929,
                    lat_0=38.3215,
                    llcrnrlon=llon,
                    llcrnrlat=llat,
                    urcrnrlon=ulon,
                    urcrnrlat=ulat,
                    resolution=resolution)

        m.drawcoastlines()
        m.drawmapboundary()

        if pretty:
            m.etopo()
        else:
            m.fillcontinents()

        llat = float(llat)
        ulat = float(ulat)
        llon = float(llon)
        ulon = float(ulon)

        m.drawparallels(np.arange(llat, ulat, (ulat - llat) / 4.0),
                        labels=[1, 0, 0, 0])
        m.drawmeridians(np.arange(llon, ulon, (ulon - llon) / 4.0),
                        labels=[0, 0, 0, 1])

        ax = plt.gca()

        x, y = m(lons, lats)

        for i in range(len(focmecs)):
            '''
            if x[i] < 0:
                x[i] = 360 + x[i]
            '''

            if depths[i] <= 50:
                color = '#FFA500'
                #label_
            elif depths[i] > 50 and depths[i] <= 100:
                color = 'g'
            elif depths[i] > 100 and depths[i] <= 200:
                color = 'b'
            else:
                color = 'r'

            index = np.where(focmecs[i] == 0)[0]

            #note here, if the mrr is zero, then you will have an error
            #so, change this to a very small number
            if focmecs[i][0] == 0:
                focmecs[i][0] = 0.001

            try:
                b = Beach(focmecs[i],
                          xy=(x[i], y[i]),
                          width=mt_size,
                          linewidth=1,
                          facecolor=color)
            except:
                pass

            b.set_zorder(10)
            ax.add_collection(b)

        x_0, y_0 = m(evlo, evla)
        m.plot(x_0, y_0, 'r*', markersize=25)

        circ1 = Line2D([0], [0],
                       linestyle="none",
                       marker="o",
                       alpha=0.6,
                       markersize=10,
                       markerfacecolor="#FFA500")
        circ2 = Line2D([0], [0],
                       linestyle="none",
                       marker="o",
                       alpha=0.6,
                       markersize=10,
                       markerfacecolor="g")
        circ3 = Line2D([0], [0],
                       linestyle="none",
                       marker="o",
                       alpha=0.6,
                       markersize=10,
                       markerfacecolor="b")
        circ4 = Line2D([0], [0],
                       linestyle="none",
                       marker="o",
                       alpha=0.6,
                       markersize=10,
                       markerfacecolor="r")
        plt.legend((circ1, circ2, circ3, circ4),
                   ("depth $\leq$ 50 km", "50 km $<$ depth $\leq$ 100 km",
                    "100 km $<$ depth $\leq$ 200 km", "200 km $<$ depth"),
                   numpoints=1,
                   loc=3)
        plt.show()
    else:
        print 'No historical MT found!'
示例#19
0
def plotMTfit(st, gr, mt, Tb, Te, args):

    # length
    tim = int(float(args.len) / float(args.DeltaInv))

    # set axis length
    tBegin = 0
    tEnd   = st[0].stats.endtime.timestamp \
                - st[0].stats.starttime.timestamp
    t = np.arange(Tb, Te, st[0].stats.delta)
    nt = len(t)
    ntr = len(st[0].data)

    # define number of stations:
    StazOb = getSTationslist(st)

    # subplot positions
    Xsize = 8.27  # default A4 size in inc.
    Ysize = 11.69

    # set np1 and title and catalog and get Stress regime
    title, np1, mkl = setNP1Title(StazOb, mt, '1e20', args)
    mtCatalog = makeCatalog(StazOb, mt, '1e20', args)

    # number of figures
    F = int(len(StazOb) / 10) + 1
    i = 0

    # loop over figures F
    for f in range(F):

        p = 3
        u = 12
        nrPage = 'Page ' + str(f + 1) + '/' + str(F)
        page = str(f + 1) + '-' + str(F)
        name = args.pltname + page

        # number of stations for each plot
        if ((f + 1) < F):
            nr = 10
        else:
            nr = len(StazOb) - (F - 1) * 10
        nr *= 3

        #       #  Initialize figure
        fig = plt.figure(f, figsize=(Xsize, Ysize), facecolor='w')

        #       # write info
        plt.figtext(0.45, 0.98, nrPage, fontsize=8)
        plt.figtext(0.20, 0.96, 'Tan', fontsize=12)
        plt.figtext(0.50, 0.96, 'Rad', fontsize=12)
        plt.figtext(0.80, 0.96, 'Ver', fontsize=12)
        plt.figtext(0.05, 0.06, title, fontsize=10)

        p = 3

        for k in range(0, nr):
            p = p + 1
            d = "%s,%s,%s" % (u, 3, p)
            Mmo = max(abs(st[i].data))
            Mmg = max(abs(gr[i].data))

            tt = gr[i].data[0:tim]
            ss = st[i].data[0:tim]
            ax1 = fig.add_subplot(u, 3, p)
            ax1 = plt.plot(t, tt, color='r', linestyle='--')
            ax1 = plt.plot(t, ss, color='k')
            if (args.zcor == 'uniso'):
                info = gr[i].stats.station + '  ' + \
                 '$\Delta$ = ' + str(int(gr[i].stats.dist)) + ' [km]   ' + \
                 '$\phi$ = '+ str(int(gr[i].stats.az)) + '$^\circ$   ' + \
                 'Tcor = ' + str(int(st[i].stats.Tcor)) + '   ' + \
                 'Rcor = ' + str(int(st[i].stats.Rcor)) + '   ' + \
                 'Vcor = ' + str(int(st[i].stats.Vcor)) + '   ' + \
                 'VR = ' + str(int(st[i].stats.VR))
            else:
                info = gr[i].stats.station + '  ' + \
                 '$\Delta$ = ' + str(int(gr[i].stats.dist)) + ' [km]   ' + \
                 '$\phi$ = '+ str(int(gr[i].stats.az)) + '$^\circ$   ' + \
                 'Zcor = ' + str(int(st[i].stats.Zcor)) + '   ' + \
                 'VR = ' + str(int(st[i].stats.VR))
            if (gr[i].stats.channel == 'TAN'):
                ax1 = plt.title(info, fontsize=8, position=(0.82, 0.95))
            ax1 = plt.axis('off')
            i = i + 1

        # plot focal mechanism
        u = 10
        np11 = [float(np1[0]), float(np1[1]), float(np1[2])]
        ax0 = plt.subplots_adjust(top=1.0)
        ax0 = fig.add_subplot(u, 3, 0)
        ax0 = pylab.axis('off')
        if (args.pltndc == 'Y'):
            try:
                beach = Beach(mkl, xy=(0.5, 0.5), width=0.97)
            except:
                beach = Beach(np11, xy=(0.5, 0.5), width=0.97)
        else:
            beach = Beach(np11, xy=(0.5, 0.5), width=0.97)
        ax0 = plt.gca()
        ax0.add_collection(beach, autolim=True)
        ax0.set_aspect("equal")

        # save fig
        fig.savefig(args.outdir + os.sep + name + '.pdf')

    # output result
    print "\n\nMT SOLUTION:\n"
    print title, "\n"

    # output mt_inv.out, mt_inv.log and mt_inv.xml
    namelast = 'mt_inv.out'
    namehist = 'mt_inv.log'
    nameqxml = 'mt_inv.xml'

    # out
    outMTlast = open(args.outdir + os.sep + namelast, 'w')
    outMTlast.write(title + "\n")
    outMTlast.close()
    # log
    outMThist = open(args.outdir + os.sep + namehist, 'a+')
    outMThist.write(title + "\n\n ------ \n")
    outMThist.close()
    # xml
    mtCatalog.write(args.outdir + os.sep + "mt_inv.xml", format="QUAKEML")

    if (args.plt == 'Y'):
        plt.show()

    return title
示例#20
0
def plot_hist_mt(psmeca_dict, figsize = (16,24), mt_size = 10, pretty = False, resolution='l'):
    if psmeca_dict['psmeca'] != []:
        psmeca = psmeca_dict['psmeca']
        #get the latitudes, longitudes, and the 6 independent component
        lats = psmeca[:,1]
        lons = psmeca[:,0]
        focmecs = psmeca[:,3:9]
        depths =  psmeca[:,2]    
        (llat, ulat, llon, ulon) = psmeca_dict['range'] 
        evla = psmeca_dict['evloc'][0]
        evlo = psmeca_dict['evloc'][1]

        plt.figure(figsize=figsize)
        m = Basemap(projection='cyl', lon_0=142.36929, lat_0=38.3215, 
                    llcrnrlon=llon,llcrnrlat=llat,urcrnrlon=ulon,urcrnrlat=ulat,resolution=resolution)
    
        m.drawcoastlines()
        m.drawmapboundary()
    
        if pretty:    
            m.etopo()
        else:
            m.fillcontinents()
    
        llat = float(llat)
        ulat = float(ulat)
        llon = float(llon)
        ulon = float(ulon)
    
        m.drawparallels(np.arange(llat, ulat, (ulat - llat) / 4.0), labels=[1,0,0,0])
        m.drawmeridians(np.arange(llon, ulon, (ulon - llon) / 4.0), labels=[0,0,0,1])   
    
        ax = plt.gca()
    
        x, y = m(lons, lats)
    
        for i in range(len(focmecs)):
            '''
            if x[i] < 0:
                x[i] = 360 + x[i]
            '''
        
            if depths[i] <= 50:
                color = '#FFA500'
                #label_
            elif depths[i] > 50 and depths [i] <= 100:
                color = 'g'
            elif depths[i] > 100 and depths [i] <= 200:
                color = 'b'
            else:
                color = 'r'
        
            index = np.where(focmecs[i] == 0)[0]
        
            #note here, if the mrr is zero, then you will have an error
            #so, change this to a very small number 
            if focmecs[i][0] == 0:
                focmecs[i][0] = 0.001
        
            try:
                b = Beach(focmecs[i], xy=(x[i], y[i]),width=mt_size, linewidth=1, facecolor=color)
            except:
                pass
            
            b.set_zorder(10)
            ax.add_collection(b)
        
        x_0, y_0 = m(evlo, evla)
        m.plot(x_0, y_0, 'r*', markersize=25) 
    
        circ1 = Line2D([0], [0], linestyle="none", marker="o", alpha=0.6, markersize=10, markerfacecolor="#FFA500")
        circ2 = Line2D([0], [0], linestyle="none", marker="o", alpha=0.6, markersize=10, markerfacecolor="g")
        circ3 = Line2D([0], [0], linestyle="none", marker="o", alpha=0.6, markersize=10, markerfacecolor="b")
        circ4 = Line2D([0], [0], linestyle="none", marker="o", alpha=0.6, markersize=10, markerfacecolor="r")
        plt.legend((circ1, circ2, circ3, circ4), ("depth $\leq$ 50 km", "50 km $<$ depth $\leq$ 100 km", 
                        "100 km $<$ depth $\leq$ 200 km", "200 km $<$ depth"), numpoints=1, loc=3)
        plt.show()
    else:
        print 'No historical MT found!'
示例#21
0
  def plot_seismogram(self,
      savefig=False, out_dir='plot',
      plot_param={
        'time':[0,100], 'rayp':10., 'azbin':10, 'window_id':'F.p,P',
        'SNR':None, 'CC0':None, 'CCmax':None, 'dist':None }
      ):
    """ Plot seismograms for one event
      azbin: azimuthal bin size
      win: 
    """
    comp_name = ['R', 'T', 'Z']
    sampling_rate = self.data['sampling_rate']
    data_delta = 1.0/sampling_rate
    data_nyq = 0.5*sampling_rate

    #------ selection parameters
    plot_time = plot_param['time']
    plot_azbin = plot_param['azbin']
    plot_rayp = plot_param['rayp']
    plot_window_id = plot_param['window_id']

    plot_SNR = plot_param['SNR']
    plot_CC0 = plot_param['CC0']
    plot_CCmax = plot_param['CCmax']
    plot_dist = plot_param['dist']

    #------ event info
    event = self.data['event']
    t0 = event['t0']
    tau = event['tau']
    evla = event['latitude']
    evlo = event['longitude']
    evdp = event['depth']
    mt = event['mt_rtp']
    Mrr = mt[0][0]
    Mtt = mt[1][1]
    Mpp = mt[2][2]
    Mrt = mt[0][1]
    Mrp = mt[0][2]
    Mtp = mt[1][2]
    focmec = [Mrr, Mtt, Mpp, Mrt, Mrp, Mtp]

    #------ station info
    station_dict = self.data['station']
    stla_all = []
    stlo_all = []
    dist_all = []
    for station_id in station_dict:
      station = station_dict[station_id]
      meta = station['meta']
      window_dict = station['window']
      # select data 
      if station['stat']['code'] < 0:
        continue
      if plot_window_id not in window_dict:
        continue
      stla_all.append(meta['latitude'])
      stlo_all.append(meta['longitude'])
      dist_all.append(meta['dist_degree'])

    #------ traveltime curve
    model = TauPyModel(model="ak135")
    dist_ttcurve = np.arange(0.0,max(dist_all),0.5)
    ttcurve_p = []
    ttcurve_P = []
    ttcurve_s = []
    ttcurve_S = []
    for dist in dist_ttcurve:
      arrivals = model.get_travel_times(
          source_depth_in_km=evdp, 
          distance_in_degree=dist, 
          phase_list=['p','P','s','S'])
      for arr in arrivals:
        if arr.name == 'p':
          ttcurve_p.append((arr.distance, arr.time, arr.ray_param))
        elif arr.name == 'P':
          ttcurve_P.append((arr.distance, arr.time, arr.ray_param))
        elif arr.name == 's':
          ttcurve_s.append((arr.distance, arr.time, arr.ray_param))
        elif arr.name == 'S':
          ttcurve_S.append((arr.distance, arr.time, arr.ray_param))
    # sort phases
    ttcurve_p = sorted(ttcurve_p, key=lambda x: x[2])
    ttcurve_P = sorted(ttcurve_P, key=lambda x: x[2])
    ttcurve_s = sorted(ttcurve_s, key=lambda x: x[2])
    ttcurve_S = sorted(ttcurve_S, key=lambda x: x[2])

    #------ map configuration 
    min_lat = min(min(stla_all), evla)
    max_lat = max(max(stla_all), evla)
    lat_range = max_lat - min_lat
    min_lat -= 0.1*lat_range
    max_lat += 0.1*lat_range
    min_lon = min(min(stlo_all), evlo)
    max_lon = max(max(stlo_all), evlo)
    lon_range = max_lon - min_lon
    min_lon -= 0.1*lon_range
    max_lon += 0.1*lon_range
    lat_0 = np.mean(stla_all)
    lon_0 = np.mean(stlo_all)
    # 
    parallels = np.arange(0.,81,10.)
    meridians = np.arange(0.,351,10.)

    #------ plot azimuthal bins (one figure per azbin)
    if plot_azbin <= 0.0:
      raise Exception("plot_param['azbin']=%f must > 0.0" % plot_azbin)

    for az in np.arange(0, 360, plot_azbin):
      azmin = az
      azmax = az + plot_azbin

      #print(azmin, azmax

      #---- gather data for the current azbin 
      data_azbin = {}
      for station_id in station_dict:
        # skip bad station
        station = station_dict[station_id]
        if station['stat']['code'] < 0:
          continue

        # skip un-selected station 
        meta = station['meta']
        azimuth = meta['azimuth']
        dist_degree = meta['dist_degree']
        if plot_dist:
          if dist_degree < min(plot_dist) or dist_degree > max(plot_dist):
            continue
        if azimuth < azmin or azimuth >= azmax:
          continue
        if plot_window_id not in window_dict:
          continue

        # skip bad window
        window_dict = station['window']
        window = window_dict[plot_window_id]
        quality = window['quality']
        cc = window['cc']
        if window['stat']['code'] <= 0:
          continue
        if plot_SNR and quality['SNR']<min(plot_SNR):
          continue
        if plot_CC0 and cc['CC0']<min(plot_CC0):
          continue
        if plot_CCmax and cc['CCmax']<min(plot_CCmax):
          continue

        # get seismograms: syn/obs
        waveform = station['waveform']
        data_starttime = waveform['starttime']
        data_npts = waveform['npts']
        obs = waveform['obs']
        grf = waveform['grf']
        # filter parameter
        filter_param = window['filter']
        filter_a = filter_param['a']
        filter_b = filter_param['b']
        # filter seismograms 
        obs = signal.lfilter(filter_b, filter_a, obs)
        grf = signal.lfilter(filter_b, filter_a, grf)
        # convolve stf on grf
        freq = np.fft.rfftfreq(data_npts, d=data_delta)
        src_spectrum = stf_gauss_spectrum(freq, event['tau'])
        syn = np.fft.irfft(src_spectrum*np.fft.rfft(grf), data_npts)
        # project to polarity defined by the window
        proj_matrix = window['polarity']['proj_matrix']
        obs = np.dot(proj_matrix, obs)
        syn = np.dot(proj_matrix, syn)
        # rotate EN(0:2) -> RT(0:2) (T-R-Z: right-hand convention)
        Raz = (meta['back_azimuth'] + 180.0) % 360.0
        sin_Raz = np.sin(np.deg2rad(Raz))
        cos_Raz = np.cos(np.deg2rad(Raz))
        proj_matrix = [ 
            [sin_Raz,  cos_Raz], 
            [cos_Raz, -sin_Raz] ]
        obs[0:2,:] = np.dot(proj_matrix, obs[0:2,:])
        syn[0:2,:] = np.dot(proj_matrix, syn[0:2,:])
        # append to data
        data_dict = {
            'meta': meta,
            'window': window,
            'syn': syn,
            'obs': obs
            }
        data_azbin[station_id] = data_dict
      #endfor station_id in station_dict:
  
      #---- skip empty azbin
      if not data_azbin:
        warn_str = "No station in the azbin [%f %f]." %(azmin, azmax)
        warnings.warn(warn_str)
        continue

      #---- create figure
      fig = plt.figure(figsize=(8.5, 11)) # US letter
      str_title = '{:s} (win: {:s}, az: {:04.1f}~{:04.1f})'.format(
          event['id'], plot_window_id, azmin, azmax)
      fig.text(0.5, 0.95, str_title, size='x-large', horizontalalignment='center')
      #---- plot station/event map
      ax_origin = [0.3, 0.74]
      ax_size = [0.4, 0.2]
      ax_map = fig.add_axes(ax_origin + ax_size)
      ax_bm = Basemap(projection='merc', resolution='l',
          llcrnrlat=min_lat, llcrnrlon=min_lon, 
          urcrnrlat=max_lat, urcrnrlon=max_lon,
          lat_0=lat_0, lon_0=lon_0 )
      ax_bm.drawcoastlines(linewidth=0.1)
      ax_bm.drawcountries(linewidth=0.1)
      ax_bm.drawparallels(parallels, linewidth=0.1, labels=[1,0,0,1], 
          fontsize=10, fmt='%3.0f')
      ax_bm.drawmeridians(meridians, linewidth=0.1, labels=[1,0,0,1], 
          fontsize=10, fmt='%3.0f')
      sx, sy = ax_bm(stlo_all, stla_all)
      ax_bm.scatter(sx, sy, s=10, marker='^', facecolor='blue', edgecolor='')
      # plot focal mechanism
      sx, sy = ax_bm(evlo, evla)
      bb_width = 110000.0 * np.abs(max(stlo_all)-min(stlo_all)) * 0.1
      b = Beach(focmec, xy=(sx, sy), width=bb_width, linewidth=0.2, facecolor='r')
      ax_map.add_collection(b)
      #-- plot the station location
      stla = [ x['meta']['latitude'] for x in data_azbin.itervalues() ]
      stlo = [ x['meta']['longitude'] for x in data_azbin.itervalues() ]
      sx, sy = ax_bm(stlo, stla)
      ax_bm.scatter(sx, sy, s=10, marker='^', facecolor='red', edgecolor='')

      #-- create axis for seismograms
      ax_RTZ = []
      for i in range(3):
        ax_origin = [0.07+0.3*i, 0.05]
        ax_size = [0.25, 0.65]
        ax_RTZ.append(fig.add_axes(ax_origin + ax_size))

      #-- plot traveltime curves
      for i in range(3):
        ax = ax_RTZ[i]
        ax.plot([x[1]-plot_rayp*x[0] for x in ttcurve_p], \
            [x[0] for x in ttcurve_p], 'b-', linewidth=0.2)
        ax.plot([x[1]-plot_rayp*x[0] for x in ttcurve_P], \
            [x[0] for x in ttcurve_P], 'b-', linewidth=0.2)
        ax.plot([x[1]-plot_rayp*x[0] for x in ttcurve_s], \
            [x[0] for x in ttcurve_s], 'c-', linewidth=0.2)
        ax.plot([x[1]-plot_rayp*x[0] for x in ttcurve_S], \
            [x[0] for x in ttcurve_S], 'c-', linewidth=0.2)

      #-- ylim setting
      y = [ x['meta']['dist_degree'] for x in data_azbin.itervalues() ]
      ny = len(y)
      plot_dy = 0.5*(max(y)-min(y)+1)/ny
      if plot_dist:
        plot_ymax = max(plot_dist) + 2*plot_dy
        plot_ymin = min(plot_dist) - 2*plot_dy
      else:
        plot_ymax = max(y) + 2*plot_dy
        plot_ymin = min(y) - 2*plot_dy

      #-- plot each station
      for station_id in data_azbin:
        station = data_azbin[station_id]
        meta = station['meta']
        window = station['window']
        syn = station['syn']
        obs = station['obs']

        # get plot time 
        dist_degree = meta['dist_degree']
        reduced_time = dist_degree * plot_rayp
        # time of first sample referred to centroid time 
        t0 = data_starttime - event['t0']
        # time of samples referred to centroid time
        syn_times = data_delta*np.arange(data_npts) + t0
        # plot time window
        plot_t0 = min(plot_time) + reduced_time
        plot_t1 = max(plot_time) + reduced_time
        plot_idx = (syn_times > plot_t0) & (syn_times < plot_t1)
        # plot time
        t_plot = syn_times[plot_idx] - reduced_time

        #  window begin/end
        taper = window['taper']
        win_starttime = taper['starttime']
        win_endtime = taper['endtime']
        win_t0 = (win_starttime - event['t0']) - reduced_time
        win_t1 = (win_endtime - event['t0']) - reduced_time

        # plot seismograms
        Amax_obs = np.sqrt(np.max(np.sum(obs[:,plot_idx]**2, axis=0)))
        Amax_syn = np.sqrt(np.max(np.sum(syn[:,plot_idx]**2, axis=0)))
        for i in range(3):
          ax = ax_RTZ[i]
          ax.plot(t_plot, plot_dy*obs[i,plot_idx]/Amax_obs+dist_degree, \
              'k-', linewidth=0.5)
          ax.plot(t_plot, plot_dy*syn[i,plot_idx]/Amax_syn+dist_degree, \
              'r-', linewidth=0.5)
          # mark measure window range
          ax.plot(win_t0, dist_degree, 'k|', markersize=8)
          ax.plot(win_t1, dist_degree, 'k|', markersize=8)
          # annotate amplitude
          if i == 0:
            ax.text(max(plot_time), dist_degree, '%.1e ' % (Amax_obs), 
                verticalalignment='bottom', 
                horizontalalignment='right', 
                fontsize=7, color='black')
            ax.text(max(plot_time), dist_degree, '%.1e ' % (Amax_syn), 
                verticalalignment='top', 
                horizontalalignment='right', 
                fontsize=7, color='red')
          # annotate CC0
          if i == 0:
            ax.text(max(plot_time), dist_degree, ' %.3f'%(window['cc']['CC0']),
                verticalalignment='center', fontsize=7)
          # annotate window weight
          if i == 1:
            ax.text(max(plot_time), dist_degree, ' %.1f' % (window['weight']),
                verticalalignment='center', fontsize=7)
          #annotate station names 
          if i == 2:
            #str_annot = '%.3f,%.1f,%s' % (
            #    misfit['CC0'], window['weight'], station_id)
            ax.text(max(plot_time), dist_degree, ' '+station_id, \
                verticalalignment='center', fontsize=7)
      #endfor data in data_azbin:

      #-- set axes limits and lables, annotation
      for i in range(3):
        ax = ax_RTZ[i]
        ax.set_xlim(min(plot_time), max(plot_time))
        ax.set_ylim(plot_ymin, plot_ymax)
        ax.set_title(comp_name[i])
        ax.set_xlabel('t - {:.1f}*dist (s)'.format(plot_rayp))
        ax.tick_params(axis='both',labelsize=10)
        # ylabel 
        if i == 0:
          ax.set_ylabel('dist (deg)')
        else:
          ax.set_yticklabels([])

      #-- save figures
      if savefig: 
        out_file = '%s/%s_az_%03d_%03d_%s.pdf' \
            % (out_dir, event['id'], azmin, azmax, plot_window_id)
        plt.savefig(out_file, format='pdf')
      else:
        plt.show()
      plt.close(fig)
    
#END class misfit
示例#22
0
文件: map.py 项目: iceseismic/sito
def createMap(
    ll=None,
    ur=None,
    figsize=None,
    margin=None,
    ax=None,
    dict_basemap=None,
    countries=True,
    lw=1,
    coastlines=True,
    mapboundary=True,
    grid=False,
    grid_labels=True,
    watercolor="#ADD8E6",
    fillcontinents="coral",
    use_lsmask=False,
    stations=None,
    cities=None,
    trench=None,
    earthquake=None,
    slip=None,
    elevation=None,
    elevation_args=(7000, 500, True),
    elevation_offset=None,
    shaded=True,
    shaded_args=(315, 45, 0.2),
    colormap=None,
    title=None,
    show=True,
    save=None,
    station_markersize=4,
    elev_oceans=True,
    grid_lw=None,
    spines_lw=None,
    dpi=None,
    station_labelsize="small",
    loffset=None,
):
    if figsize:
        fig = plt.figure(figsize=figsize)
        if margin:
            ax = fig.add_axes(margin)
    else:
        fig = None
    if dict_basemap is None:
        dict_basemap = dict(
            llcrnrlon=-180,
            llcrnrlat=-60,
            urcrnrlon=180,
            urcrnrlat=60,
            lat_0=0,
            lon_0=0,
            projection="hammer",
            resolution="l",
        )
    elif ll is not None:
        print dict_basemap
        up_dict = dict(llcrnrlon=ll[1], llcrnrlat=ll[0], urcrnrlon=ur[1], urcrnrlat=ur[0])
        dict_basemap.update(up_dict)
    m = Basemap(ax=ax, **dict_basemap)
    if fillcontinents and use_lsmask:
        m.drawlsmask(land_color=fillcontinents, ocean_color="white")
    elif fillcontinents:
        m.fillcontinents(color=fillcontinents, lake_color=watercolor, zorder=0)
    if countries:
        m.drawcountries(linewidth=lw)
    if coastlines:
        m.drawcoastlines(linewidth=lw)
    if mapboundary:
        m.drawmapboundary(fill_color=watercolor, zorder=-10)
    print 1
    if grid or grid_labels:
        if not grid_lw:
            grid_lw = lw
        if grid is True:
            grid = 1.0
        # JGR
        if grid and grid_labels:
            m.drawparallels(
                np.arange(-90.0, 90.0, grid),
                labels=[True, True, False, False],
                linewidth=grid_lw,
                xoffset=loffset,
                yoffset=loffset,
                size="small",
            )
            m.drawmeridians(
                np.arange(0.0, 390.0, grid),
                labels=[False, False, True, True],
                linewidth=grid_lw,
                xoffset=loffset,
                yoffset=loffset,
                size="small",
            )
        elif grid:
            m.drawparallels(np.arange(-90.0, 90.0, grid), labels=[False, False, False, False], linewidth=grid_lw)
            m.drawmeridians(np.arange(0.0, 390.0, grid), labels=[False, False, False, False], linewidth=grid_lw)
    if stations:
        stations.plot(m, mfc="b", ms=station_markersize, zorder=10, lsize=station_labelsize)
    if slip:
        if len(slip) == 4:
            x, y, z, levels = slip
            colors_slip = None
        else:
            x, y, z, levels, colors_slip = slip
        x, y = zip(*[m(lon, lat) for lon, lat in zip(x, y)])
        if len(np.shape(z)) == 2:
            grid_x = x
            grid_y = y
        else:
            grid_x = np.arange(
                min(x), max(x) - 0.15 * (max(x) - min(x)), 100
            )  # VERY dirty hack to cut of parts of the slip model
            grid_y = np.arange(min(y), max(y), 100)
            # grid_x, grid_y = np.mgrid[min(x):max(x):100j, min(y):max(y):100j]
            z = scipy.interpolate.griddata((x, y), z, (grid_x[None, :], grid_y[:, None]), method="cubic")

        plt.gca().contour(grid_x, grid_y, z, levels, colors=colors_slip, lw=lw)
    if earthquake == "Tocopilla":
        x, y = m(-70.06, -22.34)
        x2, y2 = m(-69.5, -24.2)  # x2, y2 = m(-70.4, -21.5)
        m.plot((x, x2), (y, y2), "k-", lw=lw)  # line
        m.plot((x), (y), "r*", ms=2 * station_markersize, zorder=10)  # epicenter
        b = Beach([358, 26, 109], xy=(x2, y2), width=50000, linewidth=lw)
        b.set_zorder(10)
        plt.gca().add_collection(b)
        plt.annotate(
            "14 Nov. 2007\n M 7.7",
            (x2, y2),
            xytext=(15, 0),  # 22
            textcoords="offset points",
            va="center",
            size=station_labelsize,
        )
    elif earthquake == "Tocopilla_beachball":
        # x, y = m(-70.06, -22.34)
        x2, y2 = m(-69.5, -24.2)  # x2, y2 = m(-70.4, -21.5)
        b = Beach([358, 26, 109], xy=(x2, y2), width=50000, linewidth=lw)
        b.set_zorder(10)
        plt.gca().add_collection(b)
        plt.annotate("14 Nov. 2007\n M 7.6", (x2, y2), xytext=(22, 0), textcoords="offset points", va="center")

    elif earthquake == "Tocopilla_position":
        x, y = m(-70.06, -22.34)
        m.plot((x), (y), "r*", ms=15, zorder=10)  # epicenter
    elif earthquake:
        xs, ys = zip(*[m(lon, lat) for lon, lat in zip(*earthquake[:2])])
        m.plot(xs, ys, "r*", ms=15, zorder=10)  # epicenters
        if len(earthquake) == 3:
            for i in range(len(xs)):
                x, y, mag = xs[i], ys[i], earthquake[2][i]
                plt.annotate("M%.1f" % mag, xy=(x, y), xytext=(-5, -15), textcoords="offset points", va="center")
        elif len(earthquake) > 3:
            for i in range(len(xs)):
                x, y, mag, date = xs[i], ys[i], earthquake[2][i], earthquake[3][i]
                plt.annotate(
                    "M%.1f\n%s" % (mag, date.date), xy=(x, y), xytext=(10, 0), textcoords="offset points", va="center"
                )
    print 2
    if elevation:
        vmax, resol, bar = elevation_args
        geo = gdal.Open(elevation)
        topoin = geo.ReadAsArray()
        if elevation_offset:
            topoin[topoin > 0] += elevation_offset
        coords = geo.GetGeoTransform()
        nlons = topoin.shape[1]
        nlats = topoin.shape[0]
        delon = coords[1]
        delat = coords[5]
        lons = coords[0] + delon * np.arange(nlons)
        lats = coords[3] + delat * np.arange(nlats)[::-1]  # reverse lats
        # create masked array, reversing data in latitude direction
        # (so that data is oriented in increasing latitude,
        # as transform_scalar requires).
        topoin = np.ma.masked_less(topoin[::-1, :], -11000)
        # topoin = gaussian_filter(topoin, 1)
        # topoin = array[::-1, :]
        # transform DEM data to a 250m native projection grid

        #            if True:
        #                x, y = m(*np.meshgrid(lons, lats))
        #                m.contourf(x, y, topoin, 100, cm=colormap)
        #                if save:
        #                    plt.savefig(save)
        #                return
        if resol:
            if resol < 25:
                nx = resol * len(lons)
                ny = resol * len(lats)
            else:
                nx = int((m.xmax - m.xmin) / resol) + 1
                ny = int((m.ymax - m.ymin) / resol) + 1
        else:
            nx = len(lons)
            ny = len(lats)
        topodat = m.transform_scalar(topoin, lons, lats, nx, ny, masked=True)
        if elevation == "CleanTopo2_nchile.tif":
            # -10,701m(0) to 8,248m(18948)
            topodat = topodat - 10701
        if isinstance(colormap, basestring) and os.path.isfile(colormap) and colormap.endswith(".gpf"):
            colormap = createColormapFromGPF(colormap)
        if shaded:
            azdeg, altdeg, fraction = shaded_args
            ls = colors.LightSource(azdeg=azdeg, altdeg=altdeg)
            # convert data to rgb array including shading from light source.
            if elev_oceans:
                rgb = colormap(0.5 * topodat / vmax + 0.5)
            else:
                rgb = colormap(topodat / vmax)
            rgb1 = ls.shade_rgb(rgb, elevation=topodat, fraction=fraction)
            rgb[:, :, 0:3] = rgb1
            m.imshow(rgb, zorder=1)
        else:
            if elev_oceans:
                m.imshow(topodat, interpolation="bilinear", cmap=colormap, zorder=1, vmin=-vmax, vmax=vmax)
            else:
                m.imshow(topodat, interpolation="bilinear", cmap=colormap, zorder=1, vmin=0, vmax=vmax)

        if bar:
            ax = plt.gca()
            fig = plt.gcf()
            # cb_ax = fig.add_axes([0.8, 0.3, 0.02, 0.4])
            cb_ax = fig.add_axes([0.82, 0.3, 0.02, 0.4])
            cb = colorbar.ColorbarBase(cb_ax, cmap=colormap, norm=colors.Normalize(vmin=-vmax, vmax=vmax))
            # cb.set_label('elevation and bathymetry')
            ticks = (np.arange(20) - 10) * 1000
            ticks = ticks[np.abs(ticks) <= vmax]
            cb.set_ticks(ticks)
            tls = ["%dm" % i if i % 2000 == 0 else "" for i in ticks]
            cb.set_ticklabels(tls)
            plt.axes(ax)  # make the original axes current again
    if cities == "ipoc":
        cities = "Antofagasta Tocopilla Iquique Calama Pisagua Arica".split()
        lons = [-70.4, -70.2, -70.1525, -68.933333, -70.216667, -70.333333]
        lats = [-23.65, -22.096389, -20.213889, -22.466667, -19.6, -18.483333]
        x, y = m(lons[: len(cities)], lats[: len(cities)])
        m.plot(x, y, "o", ms=station_markersize, mfc="w", mec="k", zorder=10)
        for i in range(len(cities)):
            if "Anto" in cities[i]:
                plt.annotate(
                    cities[i], (x[i], y[i]), xytext=(5, 0), textcoords="offset points", va="top", size=station_labelsize
                )
            else:
                plt.annotate(
                    cities[i],
                    (x[i], y[i]),
                    xytext=(-5, 0),
                    textcoords="offset points",
                    ha="right",
                    size=station_labelsize,
                )
    elif cities == "Tocopilla":
        lons = [-70.2]
        lats = [-22.096389]
        x, y = m(lons, lats)
        m.plot(x, y, "o", ms=station_markersize, mfc="w", mec="k", zorder=10)
        plt.annotate("Tocopilla", (x[0], y[0]), xytext=(5, 0), textcoords="offset points", size=station_labelsize)

    if trench == "ipoc":
        coords = np.transpose(np.loadtxt("/home/richter/Data/map/" "nchile_trench.txt"))
        import matplotlib as mpl  # hack JGR

        mpl.rcParams.update({"lines.linewidth": 1})
        plotTrench(m, coords[0, :], coords[1, :], facecolors="k", edgecolors="k")
    if spines_lw:
        for l in plt.gca().spines.values():
            l.set_linewidth(spines_lw)
    if title:
        plt.title(title, y=1.05)
    if save:
        plt.savefig(save, dpi=dpi)
    if show:
        plt.show()
    return m
示例#23
0
def plot_mt(earthquakes, mt, event_id, location = None, M_above = 5.0, show_above_M = True, 
            llat = '-90', ulat = '90', llon = '-170', ulon = '190', figsize = (12,8),
            radius = 25, dist_bt = 600, mt_width = 2, angle_step = 20, show_eq = True, 
            par_range = (-90., 120., 30.), mer_range = (0, 360, 60),
            pretty = False,  legend_loc = 4, title = '', resolution = 'l'):
    '''
    Function to plot moment tensors on the map
    Input:
        earthquakes - list of earthquake information
        mt - list of focal/moment_tensor information
        event_id - event ID corresponding to the earthquakes 
        location - predefined region, choose from 'US' or 'CA', 
            default is 'None' which will plot the whole world
        M_above - Only show the events with magnitude larger than this number
            default is 5.0, use with show_above_M 
        show_above_M - Flag to turn on the M_above option, default is True, 
        llat - bottom left corner latitude, default is -90
        ulat - upper right corner latitude, default is 90
        llon - bottom left corner longitude, default is -170 
        ulon - upper right corner longitude, default is 190
        figsize - figure size, default is (12,8)
        radius - used in checking collisions (MT), put the MT on a circle with this 
            radius, default is 25
        dist_bt - used in checking collisions (MT), if two events within dist_bt km, 
            then we say it is a collision, default is 600
        angle_step - used in checking collisions (MT), this is to decide the angle 
            step on the circle, default is 20 degree 
        mt_width - size of the MT on the map. Different scale of the map may need 
            different size, play with it.
        show_eq -  flag to show the seismicity as well, default is True
        par_range - range of latitudes you want to label on the map, start lat, end lat
            and step size, default is (-90., 120., 30.),
        mer_range - range of longitudes you want to label on the map, start lon, end lon
            and step size, default is (0, 360, 60),
        pretty - draw a pretty map, default is False to make faster plot
        legend_loc - location of the legend, default is 4
        title - title of the plot
        resolution - resolution of the map,  Possible values are
            * ``"c"`` (crude)
            * ``"l"`` (low)
            * ``"i"`` (intermediate)
            * ``"h"`` (high)
            * ``"f"`` (full)
            Defaults to ``"l"``
    '''
    
    if location == 'US':
        llon=-125
        llat=20
        ulon=-70
        ulat=60
        M_above = 4.0
        radius = 5
        dist_bt = 200 
        par_range = (20, 60, 15)
        mer_range = (-120, -60, 15)
        mt_width = 0.8        
        drawCountries = True
        
    elif location == 'CAL':
        llat = '30'
        ulat = '45'
        llon = '-130'
        ulon = '-110'
        M_above = 3.0
        radius = 1.5
        dist_bt = 50
        mt_width = 0.3
        drawStates = True
    else:
        location = None

    print earthquakes,mt,event_id
        
        
    times = [event[6] for event in earthquakes]  
    
    if show_above_M:
        mags = [row[3] for row in mt]
        index = np.array(mags) >= M_above
        mt_select = np.array(mt)[index]
        evid = np.array(event_id)[index]
        times_select = np.array(times)[index]
    else:
        evid = [row[0] for row in event_id]
        times_select = times
        mt_select = mt
    
    lats = [row[0] for row in mt_select]
    lons = [row[1] for row in mt_select]
    depths = [row[2] for row in mt_select]
    mags =  [row[3] for row in mt_select]
    focmecs = [row[4:] for row in mt_select]
    
    lats_m, lons_m, indicator = check_collision(lats, lons, radius, dist_bt, angle_step)  
    
    count = 0
    
    colors=[]
    
    min_color = min(times_select)
    max_color = max(times_select)
    colormap = plt.get_cmap()
    
    for i in times_select:
        colors.append(i)
    
    scal_map = ScalarMappable(norm=cc.Normalize(min_color, max_color),cmap=colormap)
    scal_map.set_array(np.linspace(0, 1, 1))
    
    colors_plot = [scal_map.to_rgba(c) for c in colors]
     
    ys = np.array(lats_m)
    xs = np.array(lons_m)
    url = ['http://earthquake.usgs.gov/earthquakes/eventpage/' + tmp + '#summary' for tmp in evid]
    
    stnm = np.array(evid)    
    
    fig, ax1 = plt.subplots(1,1, figsize = figsize)
    #map_ax = fig.add_axes([0.03, 0.13, 0.94, 0.82])
    
    if show_eq:
        cm_ax = fig.add_axes([0.98, 0.39, 0.04, 0.3])   
        plt.sca(ax1)
        cb = mpl.colorbar.ColorbarBase(ax=cm_ax, cmap=colormap, orientation='vertical')
        cb.set_ticks([0, 0.25, 0.5, 0.75, 1.0])
        color_range = max_color - min_color
        cb.set_ticklabels([_i.strftime('%Y-%b-%d, %H:%M:%S %p')
        for _i in [min_color, min_color + color_range * 0.25,
           min_color + color_range * 0.50,
           min_color + color_range * 0.75, max_color]])
           
    
    m = Basemap(projection='cyl', lon_0=142.36929, lat_0=38.3215, 
                llcrnrlon=llon,llcrnrlat=llat,urcrnrlon=ulon,urcrnrlat=ulat,resolution=resolution)
    
    m.drawcoastlines()
    m.drawmapboundary()
    m.drawcountries()
    m.drawparallels(np.arange(par_range[0], par_range[1], par_range[2]), labels=[1,0,0,0], linewidth=0)
    m.drawmeridians(np.arange(mer_range[0],mer_range[1], mer_range[2]), labels=[0,0,0,1], linewidth=0)
    
    
    if pretty:    
        m.etopo()
    else:
        m.fillcontinents()
        
    x, y = m(lons_m, lats_m)
    
    for i in range(len(focmecs)):
            
        index = np.where(focmecs[i] == 0)[0]
        
        #note here, if the mrr is zero, then you will have an error
        #so, change this to a very small number 
        if focmecs[i][0] == 0:
            focmecs[i][0] = 0.001
            
        
        width = mags[i] * mt_width
        
        if depths[i] <= 50:
            color = '#FFA500'
            #label_
        elif depths[i] > 50 and depths [i] <= 100:
            color = '#FFFF00'
        elif depths[i] > 100 and depths [i] <= 150:
            color = '#00FF00'
        elif depths[i] > 150 and depths [i] <= 200:
            color = 'b'
        else:
            color = 'r'
                  
        if indicator[i] == 1:
            m.plot([lons[i],lons_m[i]],[lats[i], lats_m[i]], 'k')   
            #m.plot([10,20],[0,0])  
        try:
            
            b = Beach(focmecs[i], xy=(x[i], y[i]),width=width, linewidth=1, facecolor= color, alpha=1)
            count += 1
            line, = ax1.plot(x[i],y[i], 'o', picker=5, markersize=30, alpha =0) 
    
        except:
            pass
        b.set_zorder(3)
        ax1.add_collection(b)
        
        
    d=5
    circ1 = Line2D([0], [0], linestyle="none", marker="o", alpha=0.6, markersize=10, markerfacecolor="#FFA500")
    circ2 = Line2D([0], [0], linestyle="none", marker="o", alpha=0.6, markersize=10, markerfacecolor="#FFFF00")
    circ3 = Line2D([0], [0], linestyle="none", marker="o", alpha=0.6, markersize=10, markerfacecolor="#00FF00")
    circ4 = Line2D([0], [0], linestyle="none", marker="o", alpha=0.6, markersize=10, markerfacecolor="b")
    circ5 = Line2D([0], [0], linestyle="none", marker="o", alpha=0.6, markersize=10, markerfacecolor="r")
    
    M4 = Line2D([0], [0], linestyle="none", marker="o", alpha=0.4, markersize= 4*d, markerfacecolor="k")
    M5 = Line2D([0], [0], linestyle="none", marker="o", alpha=0.4, markersize= 5*d, markerfacecolor="k")
    M6 = Line2D([0], [0], linestyle="none", marker="o", alpha=0.4, markersize= 6*d, markerfacecolor="k")
    M7 = Line2D([0], [0], linestyle="none", marker="o", alpha=0.4, markersize= 7*d, markerfacecolor="k")
    
    if location == 'World':
    
        title = str(count) + ' events with focal mechanism - color codes depth, size the magnitude'
        
    elif location == 'US':
    
        title = 'US events with focal mechanism - color codes depth, size the magnitude'
        
    elif location == 'CAL':
        title = 'California events with focal mechanism - color codes depth, size the magnitude'
    elif location is None:
        pass
        
    legend1 = plt.legend((circ1, circ2, circ3, circ4, circ5), ("depth $\leq$ 50 km", "50 km $<$ depth $\leq$ 100 km", 
                                       "100 km $<$ depth $\leq$ 150 km", "150 km $<$ depth $\leq$ 200 km","200 km $<$ depth"), numpoints=1, loc=legend_loc)
    
    plt.title(title)
    plt.gca().add_artist(legend1)
    
    if location == 'World':
        plt.legend((M4,M5,M6,M7), ("M 4.0", "M 5.0", "M 6.0", "M 7.0"), numpoints=1, loc=legend_loc)
        
    x, y = m(lons, lats)
    min_size = 6
    max_size = 30
    min_mag = min(mags)
    max_mag = max(mags)
    
    if show_eq:
        if len(lats) > 1:
            frac = [(_i - min_mag) / (max_mag - min_mag) for _i in mags]
            magnitude_size = [(_i * (max_size - min_size)) ** 2 for _i in frac]
            magnitude_size = [(_i * min_size/2)**2 for _i in mags]
        else:
            magnitude_size = 15.0 ** 2
            colors_plot = "red"
        m.scatter(x, y, marker='o', s=magnitude_size, c=colors_plot,
                zorder=10)
    
    plt.show()
    
    print 'Max magnitude ' + str(np.max(mags)), 'Min magnitude ' + str(np.min(mags))
示例#24
0
文件: ffiplot.py 项目: junxie01/ffipy
def stacov(bx1,elon,elat,edep):
    lines = open('fort.1','r').readlines()
    sites = {}
    for line in open('iris.site','r'):
        sta = line.split()[0]
        lat,lon = [float(x) for x in line.split()[3:5]]
        sites[sta] = (lat,lon)
    stas = []
    lats = []
    lons = []
    azs  = {}
    ps   = []
    clrs = []
    for i in range(0,len(lines)):
        line = lines[i]
        sta = line.split()[0]
        if sta in stas or not 'ref' in line:
            continue
        ib = int(lines[i+2].split()[1])
        if ib < 5:
            az,baz,gcarc,p = [float(x) for x in lines[i+1].split()[0:4]]
            azs[sta] = az
            ps.append(p)
        if not sites.has_key(sta):
            print 'Station %s not found in site table' % sta
            continue
        if not plrs.has_key(sta):
            clrs.append('gray')
        elif plrs[sta] == 'c':
            clrs.append('yellow')
        else:
            clrs.append('cyan')            
        stas.append(sta)
        lat,lon = sites[sta]
        #print sta,lat,lon,az,baz,gcarc
        lats.append(lat)
        lons.append(lon)
    map = Basemap(projection='ortho',lat_0=elat,lon_0=elon,
              resolution='l',area_thresh=10000.)
    x,y = map(lons,lats)
    map.scatter(x,y,s=25,c=clrs,marker='o',edgecolors='black',zorder=10)
    for i in range(0,len(stas)):
        sx=x[i]
        sy=y[i]
        if stas[i] == 'MOO':
            plt.text(sx,sy-800000,stas[i],fontsize=12,color='black')
        else:
            plt.text(sx,sy,stas[i],fontsize=12,color='black')
    map.fillcontinents(color='coral')
    map.drawmapboundary()
    map.drawmeridians(np.arange(0,360,30))
    map.drawparallels(np.arange(-90,90,30))
    x1,y1 = map(elon,elat)
    rad = 3000000
    fm = [194., 18., 90.]
    bx1.add_collection(Beach(fm, size=100, width=2.*rad, xy=(x1, y1), facecolor='red', linewidth=.6,zorder=45))
    fm = [359.,80,90.]
    bx1.add_collection(Beach(fm, size=100, width=2.*rad, xy=(x1, y1), facecolor='blue', linewidth=.6,alpha=0.5,zorder=47))
    r_src = 6371.-edep
    x2 = []
    y2 = []
    for i in range(0,len(stas)):
        xi = mt.asin(min(1.,7.95*ps[i]))
        xi = mt.sin(0.5*xi)
        x2.append(x1+rad*xi*mt.sin(azs[stas[i]]*mt.pi/180.))
        y2.append(y1+rad*xi*mt.cos(azs[stas[i]]*mt.pi/180.))
    map.scatter(x2,y2,s=25,c=clrs,marker='o',edgecolors='black',zorder=50)
    bx1.annotate("IFP",xy=(0.50,0.275), xycoords='axes fraction',fontsize=16,
            xytext=(0.55,0.15), textcoords='axes fraction',arrowprops=dict(arrowstyle="->",
                            connectionstyle="arc3",zorder=1)
            )
    bx1.annotate("MFP",xy=(0.565,0.735), xycoords='axes fraction',fontsize=16,
            xytext=(0.70,0.75), textcoords='axes fraction',arrowprops=dict(arrowstyle="->",
                            connectionstyle="arc3",zorder=2)
            )
    return azs
示例#25
0
# Make gradient plot.
#ps = m.pcolor(x, y, srtm3)
# Make contour plot.
cs = m.contour(x, y, srtm3, 40, colors=".4", lw=0.5, alpha=0.3)
m.drawcountries(color="red", linewidth=1)

# Draw a lon/lat grid (20 lines for an interval of one degree).
m.drawparallels(np.linspace(47, 48, 21), labels=[1,1,0,0], fmt="%.2f",
                dashes=[2,2])
m.drawmeridians(np.linspace(12, 13, 21), labels=[0,0,1,1], fmt="%.2f",
                dashes=[2,2])

# Calculate map projection for the coordinates.
x, y = m(stations_long, stations_lat)
m.scatter(x, y, 200, color="r", marker="v", edgecolor="k", zorder=3)
for i in range(len(stations_id)):
    plt.text(x[i], y[i], " " + stations_id[i], color='k', va="top", 
             family="monospace", weight="bold")

# Calculate map projectoins for the beachballs.
x, y = m(events_long, events_lat)
# Plot the beachballs.
ax = plt.gca()
for i in range(len(events_focmec)):
    b = Beach(events_focmec[i], xy=(x[i], y[i]), width=1000, linewidth=1)
    b.set_zorder(10)
    ax.add_collection(b)

# Save the figure.
plt.savefig("basemap_beachball_example.pdf")
示例#26
0
x, y = m(lons, lats)
m.scatter(x, y, 200, color="r", marker="v", edgecolor="k", zorder=3)
for i in range(len(names)):
    plt.text(x[i],
             y[i],
             " " + names[i],
             color='k',
             va="top",
             family="monospace",
             weight="bold")

# add beachballs for three events
lats = [47.74750100000, 47.74878700000, 47.76233333330]
longs = [12.88500000000, 12.82278700000, 12.83816666670]
# three focal mechanisms for the beachball routine, specified as [strike, dip, rake]
focmecs = [[60.00000000000, 65.00000000000, -60.00000000000],
           [80.00000000000, 60.00000000000, 80.00000000000],
           [40.00000000000, 80.00000000000, 90.00000000000]]
x, y = m(longs, lats)

ax = plt.gca()
print focmecs
print x, y
for i in range(len(focmecs)):
    b = Beach(focmecs[i], xy=(x[i], y[i]), width=1000, linewidth=1)
    b.set_zorder(10)
    ax.add_collection(b)

plt.savefig("basemap_beachball_demo2.pdf")
示例#27
0
def plot_mt(mapobj,
            axisobj,
            figobj,
            earthquakes,
            mt,
            event_id,
            location=None,
            M_above=3.0,
            show_above_M=True,
            llat='-90',
            ulat='90',
            llon='-170',
            ulon='190',
            figsize=(12, 8),
            radius=25,
            dist_bt=600,
            mt_width=2,
            angle_step=20,
            show_eq=True,
            par_range=(-90., 120., 30.),
            mer_range=(0, 360, 60),
            pretty=False,
            legend_loc=4,
            title='',
            resolution='l'):
    '''
    Function to plot moment tensors on the map
    Input:
        mapobj - already existing Basemap object onwhich to plot the quakes
        earthquakes - list of earthquake information
        mt - list of focal/moment_tensor information
        event_id - event ID corresponding to the earthquakes 
        location - predefined region, choose from 'US' or 'CA', 
            default is 'None' which will plot the whole world
        M_above - Only show the events with magnitude larger than this number
            default is 5.0, use with show_above_M 
        show_above_M - Flag to turn on the M_above option, default is True, 
        llat - bottom left corner latitude, default is -90
        ulat - upper right corner latitude, default is 90
        llon - bottom left corner longitude, default is -170 
        ulon - upper right corner longitude, default is 190
        figsize - figure size, default is (12,8)
        radius - used in checking collisions (MT), put the MT on a circle with this 
            radius, default is 25
        dist_bt - used in checking collisions (MT), if two events within dist_bt km, 
            then we say it is a collision, default is 600
        angle_step - used in checking collisions (MT), this is to decide the angle 
            step on the circle, default is 20 degree 
        mt_width - size of the MT on the map. Different scale of the map may need 
            different size, play with it.
        show_eq -  flag to show the seismicity as well, default is True
        par_range - range of latitudes you want to label on the map, start lat, end lat
            and step size, default is (-90., 120., 30.),
        mer_range - range of longitudes you want to label on the map, start lon, end lon
            and step size, default is (0, 360, 60),
        pretty - draw a pretty map, default is False to make faster plot
        legend_loc - location of the legend, default is 4
        title - title of the plot
        resolution - resolution of the map,  Possible values are
            * ``"c"`` (crude)
            * ``"l"`` (low)
            * ``"i"`` (intermediate)
            * ``"h"`` (high)
            * ``"f"`` (full)
            Defaults to ``"l"``
    '''

    quakedots = None

    if location == 'US':
        llon = -125
        llat = 20
        ulon = -70
        ulat = 60
        M_above = 4.0
        radius = 5
        dist_bt = 200
        par_range = (20, 60, 15)
        mer_range = (-120, -60, 15)
        mt_width = 0.8
        drawCountries = True

    elif location == 'CAL':
        llat = '30'
        ulat = '45'
        llon = '-130'
        ulon = '-110'
        M_above = 3.0
        radius = 1.5
        dist_bt = 50
        mt_width = 0.3
        drawStates = True
    else:
        location = None

    times = [event[6] for event in earthquakes]

    if show_above_M:
        mags = [row[3] for row in mt]
        index = np.array(mags) >= M_above
        mt_select = np.array(mt)[index]
        evid = np.array(event_id)[index]
        #times_select = np.array(times)[index]
    else:
        evid = [row for row in event_id]
        times_select = times
        mt_select = mt

    lats = [row[0] for row in mt_select]
    lons = [row[1] for row in mt_select]
    depths = [row[2] for row in mt_select]
    mags = [row[3] for row in mt_select]
    focmecs = [row[4:] for row in mt_select]

    lats_m, lons_m, indicator = check_collision(lats, lons, radius, dist_bt,
                                                angle_step)

    #sys.exit(1)

    count = 0

    colors = []

    min_color = 1  #min(times_select) 1
    max_color = 10  #max(times_select) 10
    colormap = plt.get_cmap()

    for i in range(min_color, max_color):
        colors.append(i)

    scal_map = ScalarMappable(norm=cc.Normalize(min_color, max_color),
                              cmap=colormap)
    scal_map.set_array(np.linspace(0, 1, 1))

    colors_plot = [scal_map.to_rgba(c) for c in colors]

    ys = np.array(lats_m)
    xs = np.array(lons_m)
    url = [
        'http://earthquake.usgs.gov/earthquakes/eventpage/' + tmp + '#summary'
        for tmp in evid
    ]

    stnm = np.array(evid)

    #fig, ax1 = plt.subplots(1,1, figsize = figsize)
    #map_ax = fig.add_axes([0.03, 0.13, 0.94, 0.82])

    # if show_eq:
    #     cm_ax = fig.add_axes([0.98, 0.39, 0.04, 0.3])
    #     plt.sca(ax1)
    #     cb = mpl.colorbar.ColorbarBase(ax=cm_ax, cmap=colormap, orientation='vertical')
    #     cb.set_ticks([0, 0.25, 0.5, 0.75, 1.0])
    #     color_range = max_color - min_color
    #     cb.set_ticklabels([_i.strftime('%Y-%b-%d, %H:%M:%S %p')
    #     for _i in [min_color, min_color + color_range * 0.25,
    #        min_color + color_range * 0.50,
    #        min_color + color_range * 0.75, max_color]])

    #m = Basemap(projection='cyl', lon_0=142.36929, lat_0=38.3215, llcrnrlon=llon,llcrnrlat=llat,urcrnrlon=ulon,urcrnrlat=ulat,resolution=resolution)

    #mapobj.drawmapboundary()
    #mapobj.drawcountries()
    #mapobj.drawparallels(np.arange(par_range[0], par_range[1], par_range[2]), labels=[1,0,0,0], linewidth=0)
    #mapobj.drawmeridians(np.arange(mer_range[0],mer_range[1], mer_range[2]), labels=[0,0,0,1], linewidth=0)

    # Plot the earthquake epicenters as points

    x, y = mapobj(lons, lats)
    min_size = 1
    max_size = 8
    min_mag = min(mags)
    max_mag = max(mags)

    if show_eq:
        if len(lats) > 1:
            frac = [(_i - min_mag) / (max_mag - min_mag) for _i in mags]
            magnitude_size = [(_i * (max_size - min_size))**2 for _i in frac]
            magnitude_size = [(_i * min_size / 2)**2 for _i in mags]
        else:
            magnitude_size = 15.0**2
            colors_plot = "red"

        quakedots = mapobj.scatter(x,
                                   y,
                                   marker='o',
                                   s=magnitude_size,
                                   c=colors_plot,
                                   zorder=10)

    print 'Max magnitude ' + str(np.max(mags)), 'Min magnitude ' + str(
        np.min(mags))

    #plot the moment tensor beachballs if available
    x, y = mapobj(lons_m, lats_m)

    mtlineobjs = []
    mtobjs = []

    for i in range(len(focmecs)):

        index = np.where(focmecs[i] == 0)[0]

        #note here, if the mrr is zero, then you will have an error
        #so, change this to a very small number
        if focmecs[i][0] == 0:
            focmecs[i][0] = 0.001

        width = mags[i] * mt_width

        if depths[i] <= 50:
            color = '#FFA500'
            #label_
        elif depths[i] > 50 and depths[i] <= 100:
            color = '#FFFF00'
        elif depths[i] > 100 and depths[i] <= 150:
            color = '#00FF00'
        elif depths[i] > 150 and depths[i] <= 200:
            color = 'b'
        else:
            color = 'r'

        if indicator[i] == 1:
            lineobj = mapobj.plot([lons[i], lons_m[i]], [lats[i], lats_m[i]],
                                  'k')
            #mtlineobjs.append(lineobj)
            #m.plot([10,20],[0,0])
        else:

            lineobj = None

        try:

            b = Beach(focmecs[i],
                      xy=(x[i], y[i]),
                      width=width,
                      linewidth=1,
                      facecolor=color,
                      alpha=1)
            count += 1
            #line = axisobj.plot(x[i],y[i], 'o', picker=5, markersize=30, alpha =0)
            #mtlineobjs.append(line)

        except:
            pass

        #ensure that the MTs are always plotted on top of the earthquakes associated with them
        b.set_zorder(100)
        axisobj.add_collection(b)
        mtobjs.append(b)
        mtlineobjs.append(lineobj)

    d = 2
    circ1 = Line2D([0], [0],
                   linestyle="none",
                   marker="o",
                   alpha=0.6,
                   markersize=10,
                   markerfacecolor="#FFA500")
    circ2 = Line2D([0], [0],
                   linestyle="none",
                   marker="o",
                   alpha=0.6,
                   markersize=10,
                   markerfacecolor="#FFFF00")
    circ3 = Line2D([0], [0],
                   linestyle="none",
                   marker="o",
                   alpha=0.6,
                   markersize=10,
                   markerfacecolor="#00FF00")
    circ4 = Line2D([0], [0],
                   linestyle="none",
                   marker="o",
                   alpha=0.6,
                   markersize=10,
                   markerfacecolor="b")
    circ5 = Line2D([0], [0],
                   linestyle="none",
                   marker="o",
                   alpha=0.6,
                   markersize=10,
                   markerfacecolor="r")

    M4 = Line2D([0], [0],
                linestyle="none",
                marker="o",
                alpha=0.4,
                markersize=4 * d,
                markerfacecolor="k")
    M5 = Line2D([0], [0],
                linestyle="none",
                marker="o",
                alpha=0.4,
                markersize=5 * d,
                markerfacecolor="k")
    M6 = Line2D([0], [0],
                linestyle="none",
                marker="o",
                alpha=0.4,
                markersize=6 * d,
                markerfacecolor="k")
    M7 = Line2D([0], [0],
                linestyle="none",
                marker="o",
                alpha=0.4,
                markersize=7 * d,
                markerfacecolor="k")

    if location == 'World':

        title = str(
            count
        ) + ' events with focal mechanism - color codes depth, size the magnitude'

    elif location == 'US':

        title = 'US events with focal mechanism - color codes depth, size the magnitude'

    elif location == 'CAL':
        title = 'California events with focal mechanism - color codes depth, size the magnitude'
    elif location is None:
        pass

    #handles, labels = axisobj.get_legend_handles_labels()

    #axisobj.legend(handles,labels,(circ1, circ2, circ3, circ4, circ5), ("depth $\leq$ 50 km", "50 km $<$ depth $\leq$ 100 km",
    #                                   "100 km $<$ depth $\leq$ 150 km", "150 km $<$ depth $\leq$ 200 km","200 km $<$ depth"), numpoints=1, loc=legend_loc)

    #plt.title(title)
    #plt.gca().add_artist(legend1)

    #if location == 'World':
    #    axisobj.legend(han,dles,labels(M4,M5,M6,M7), ("M 4.0", "M 5.0", "M 6.0", "M 7.0"), numpoints=1, loc=legend_loc)

    if not quakedots:
        quakedots = False

    return mtlineobjs, mtobjs, quakedots, xs, ys, url
示例#28
0
def plot_sta_ev_ray(input_dics, events):
    """
    plot stations, events and ray paths on a map using basemap.
    :param input_dics:
    :param events:
    :return:
    """
    plt.figure(figsize=(20., 10.))
    plt_stations = input_dics['plot_sta']
    plt_availability = input_dics['plot_availability']
    plt_events = input_dics['plot_ev']
    plt_ray_path = input_dics['plot_ray']

    if input_dics['evlatmin'] is None:
        evlatmin = -90
        evlatmax = +90
        evlonmin = -180
        evlonmax = +180
        glob_map = True
    else:
        evlatmin = input_dics['evlatmin']
        evlatmax = input_dics['evlatmax']
        evlonmin = input_dics['evlonmin']
        evlonmax = input_dics['evlonmax']
        glob_map = False

    if plt_ray_path:
        # # hammer, kav7, cyl, mbtfpq, moll
        m = Basemap(projection='moll', lon_0=input_dics['plot_lon0'])
        parallels = np.arange(-90, 90, 30.)
        m.drawparallels(parallels, fontsize=24)
        meridians = np.arange(-180., 180., 60.)
        m.drawmeridians(meridians, fontsize=24)
        width_beach = 10e5
        width_station = 50
    elif not glob_map:
        m = Basemap(projection='cyl', llcrnrlat=evlatmin, urcrnrlat=evlatmax,
                    llcrnrlon=evlonmin, urcrnrlon=evlonmax)
        parallels = np.arange(-90, 90, 5.)
        m.drawparallels(parallels, fontsize=12)
        meridians = np.arange(-180., 180., 5.)
        m.drawmeridians(meridians, fontsize=12)
        width_beach = 5
        width_station = 10
    elif glob_map:
        m = Basemap(projection='moll', lon_0=input_dics['plot_lon0'])
        parallels = np.arange(-90, 90, 30.)
        m.drawparallels(parallels, fontsize=24)
        meridians = np.arange(-180., 180., 60.)
        m.drawmeridians(meridians, fontsize=24)
        width_beach = 5e5
        width_station = 50
    else:
        sys.exit('[ERROR] can not continue, error:\n%s' % input_dics)

    raw_input_resp = raw_input_built('choose the map style:\n'
                                     '1. bluemarble (PIL should be installed)\n'
                                     '2. etopo (PIL should be installed)\n'
                                     '3. shadedrelief (PIL should be installed)\n'
                                     '4. simple\n')
    if int(raw_input_resp) == 1:
        m.bluemarble(scale=0.5)
    elif int(raw_input_resp) == 2:
        m.etopo(scale=0.5)
    elif int(raw_input_resp) == 3:
        m.shadedrelief(scale=0.1)
    else:
        m.fillcontinents()

    for ei in range(len(events)):
        if plt_events:
            if input_dics['plot_focal']:
                if not events[ei]['focal_mechanism']:
                    print('[ERROR] moment tensor does not exist!')
                    continue
                x, y = m(events[ei]['longitude'],
                         events[ei]['latitude'])
                focmecs = [float(events[ei]['focal_mechanism'][0]),
                           float(events[ei]['focal_mechanism'][1]),
                           float(events[ei]['focal_mechanism'][2]),
                           float(events[ei]['focal_mechanism'][3]),
                           float(events[ei]['focal_mechanism'][4]),
                           float(events[ei]['focal_mechanism'][5])]
                try:
                    ax = plt.gca()
                    b = Beach(focmecs, xy=(x, y), facecolor='blue',
                              width=width_beach, linewidth=1, alpha=0.85)
                    b.set_zorder(10)
                    ax.add_collection(b)
                except Exception as error:
                    print("[WARNING: %s -- %s]" % (error, focmecs))
                    continue
            else:
                x, y = m(events[ei]['longitude'],
                         events[ei]['latitude'])
                magnitude = float(events[ei]['magnitude'])
                m.scatter(x, y, color="blue", s=10*magnitude,
                          edgecolors='none', marker="o",
                          zorder=5, alpha=0.65)
        if plt_stations or plt_availability or plt_ray_path:
            target_path = locate(input_dics['datapath'],
                                 events[ei]['event_id'])
            if len(target_path) == 0:
                continue
            if len(target_path) > 1:
                print("[LOCAL] more than one path was found for the event:")
                print(target_path)
                print("[INFO] use the first one:")
                target_path = target_path[0]
                print(target_path)
            else:
                print("[LOCAL] Path:")
                target_path = target_path[0]
                print(target_path)

            update_sta_ev_file(target_path, events[ei])
            if not input_dics['plot_availability']:
                sta_ev_arr = np.loadtxt(os.path.join(target_path,
                                                     'info', 'station_event'),
                                        delimiter=',', dtype=bytes, ndmin=2).astype(np.str)
            else:
                sta_ev_arr = np.loadtxt(os.path.join(target_path,
                                                     'info',
                                                     'availability.txt'),
                                        delimiter=',', dtype=bytes, ndmin=2).astype(np.str)
            sta_ev_arr = sta_ev_arr.astype(np.object)

            if events[ei]['magnitude'] > 0:
                del_index = []
                for sti in range(len(sta_ev_arr)):

                    if not plot_filter_station(input_dics, sta_ev_arr[sti]):
                        del_index.append(sti)

                    dist, azi, bazi = gps2DistAzimuth(
                        events[ei]['latitude'],
                        events[ei]['longitude'],
                        float(sta_ev_arr[sti, 4]),
                        float(sta_ev_arr[sti, 5]))

                    epi_dist = dist/111.194/1000.
                    if input_dics['min_azi'] or input_dics['max_azi'] or \
                            input_dics['min_epi'] or input_dics['max_epi']:
                        if input_dics['min_epi']:
                            if epi_dist < input_dics['min_epi']:
                                del_index.append(sti)
                        if input_dics['max_epi']:
                            if epi_dist > input_dics['max_epi']:
                                del_index.append(sti)
                        if input_dics['min_azi']:
                            if azi < input_dics['min_azi']:
                                del_index.append(sti)
                        if input_dics['max_azi']:
                            if azi > input_dics['max_azi']:
                                del_index.append(sti)

                del_index = list(set(del_index))
                del_index.sort(reverse=True)
                for di in del_index:
                    sta_ev_arr = np.delete(sta_ev_arr, (di), axis=0)

        if plt_stations or plt_availability:
            if len(sta_ev_arr) > 0:
                x, y = m(sta_ev_arr[:, 5], sta_ev_arr[:, 4])
                m.scatter(x, y, color='red', s=width_station,
                          edgecolors='none', marker='v',
                          zorder=4, alpha=0.9)

        if plt_ray_path:
            for si in range(len(sta_ev_arr)):
                gcline = m.drawgreatcircle(float(events[ei]['longitude']),
                                           float(events[ei]['latitude']),
                                           float(sta_ev_arr[si][5]),
                                           float(sta_ev_arr[si][4]),
                                           color='k', alpha=0.0)

                gcx, gcy = gcline[0].get_data()
                gcx_diff = gcx[0:-1] - gcx[1:]
                gcy_diff = gcy[0:-1] - gcy[1:]
                if np.max(abs(gcx_diff))/abs(gcx_diff[0]) > 300:
                    gcx_max_arg = abs(gcx_diff).argmax()
                    plt.plot(gcx[0:gcx_max_arg], gcy[0:gcx_max_arg],
                             color='k', alpha=0.1)
                    plt.plot(gcx[gcx_max_arg+1:], gcy[gcx_max_arg+1:],
                             color='k', alpha=0.1)
                elif np.max(abs(gcy_diff))/abs(gcy_diff[0]) > 400:
                    gcy_max_arg = abs(gcy_diff).argmax()
                    plt.plot(gcy[0:gcy_max_arg], gcy[0:gcy_max_arg],
                             color='k', alpha=0.1)
                    plt.plot(gcy[gcy_max_arg+1:], gcy[gcy_max_arg+1:],
                             color='k', alpha=0.1)
                else:
                    m.drawgreatcircle(float(events[ei]['longitude']),
                                      float(events[ei]['latitude']),
                                      float(sta_ev_arr[si][5]),
                                      float(sta_ev_arr[si][4]),
                                      color='k', alpha=0.1)

    plt.savefig(os.path.join(input_dics['plot_save'],
                             'event_station.%s' % input_dics['plot_format']))
    plt.show()