예제 #1
0
    def plot(self,
             depth_range=(0, 60000.),
             ddepth=100.,
             ddbin=2000.,
             vel_range=None,
             dvbin=100.,
             percent=False,
             plot_mode=True,
             plot_median=True,
             plot_mean=False,
             show_cbar=True,
             aspect=.02,
             phase='p',
             axes=None):
        ''' Plot a two 2D Histogram of seismic velocities

        :param depth_range: Depth range, ``(dmin, dmax)``,
            defaults to ``(0, 60)``
        :type depth_range: tuple
        :param vel_range: Velocity range, ``(vmin, vmax)``
        :type vel_range: tuple
        :param ddepth: Stepping in [m], defaults to ``.1``
        :type ddepth: float
        :param dvbin: Bin size in velocity dimension [m/s], defaults to .1
        :type dvbin: float
        :param dvbin: Bin size in depth dimension [m], defaults to 2000.
        :type dvbin: float
        :param phase: Phase to calculate ``p`` or ``s``, defaults to ``p``
        :type phase: str
        :param plot_mode: Plot the Mode
        :type plot_mode: bool
        :param plot_mean: Plot the Mean
        :type plot_mean: bool
        :param plot_median: Plot the Median
        :type plot_median: bool
        :param axes: Axes to plot into, defaults to None
        :type axes: :class:`matplotlib.Axes`
        '''

        import matplotlib.pyplot as plt

        fig, ax = _getCanvas(axes)

        ax = fig.gca()

        if vel_range is not None:
            vmin, vmax = vel_range
        dmin, dmax = depth_range

        vfield, vedg, dedg = self.histogram2d(vel_range=vel_range,
                                              depth_range=depth_range,
                                              ddepth=ddepth,
                                              dvbin=dvbin,
                                              ddbin=ddbin,
                                              phase=phase)
        vfield /= (ddbin / ddepth)

        if percent:
            vfield /= vfield.sum(axis=1)[num.newaxis, :]

        grid_ext = [vedg[0], vedg[-1], dedg[-1], dedg[0]]
        histogram = ax.imshow(vfield.swapaxes(0, 1),
                              interpolation='nearest',
                              extent=grid_ext,
                              aspect=aspect)

        if show_cbar:
            cticks = num.unique(
                num.arange(0, vfield.max(),
                           vfield.max() // 10).round())
            cbar = fig.colorbar(histogram,
                                ticks=cticks,
                                format='%1i',
                                orientation='horizontal')
            if percent:
                cbar.set_label('Percent')
            else:
                cbar.set_label('Number of Profiles')

        if plot_mode:
            sdepth, vel_mode, _ = self.modeVelocity(depth_range=depth_range,
                                                    ddepth=ddepth)
            ax.plot(vel_mode[sdepth < dmax] + ddepth / 2,
                    sdepth[sdepth < dmax],
                    alpha=.8,
                    color='w',
                    label='Mode')

        if plot_mean:
            sdepth, vel_mean, _ = self.meanVelocity(depth_range=depth_range,
                                                    ddepth=ddepth)
            ax.plot(vel_mean[sdepth < dmax] + ddepth / 2,
                    sdepth[sdepth < dmax],
                    alpha=.8,
                    color='w',
                    linestyle='--',
                    label='Mean')

        if plot_median:
            sdepth, vel_median, _ = self.medianVelocity(
                depth_range=depth_range, ddepth=ddepth)
            ax.plot(vel_median[sdepth < dmax] + ddepth / 2,
                    sdepth[sdepth < dmax],
                    alpha=.8,
                    color='w',
                    linestyle=':',
                    label='Median')

        ax.grid(True, which="both", color="w", linewidth=.8, alpha=.4)

        ax.text(.025,
                .025,
                '%d Profiles' % self.nprofiles,
                color='w',
                alpha=.7,
                transform=ax.transAxes,
                fontsize=9,
                va='bottom',
                ha='left')

        ax.set_title('Crustal Velocity Distribution')
        ax.set_xlabel('%s [km/s]' % vel_labels[phase])
        ax.set_ylabel('Depth [km]')
        yscaled(1. / km, ax)
        xoffset_scale(dvbin / 2, 1. / km, ax)
        ax.set_xlim(vel_range)

        if self.name is not None:
            ax.set_title('%s for %s' % (ax.get_title(), self.name))

        if plot_mode or plot_mean or plot_median:
            leg = ax.legend(loc=1, fancybox=True, prop={'size': 10.})
            leg.get_frame().set_alpha(.6)

        if axes is None:
            plt.show()
예제 #2
0
def command_tttview(args):
    import numpy as num
    import matplotlib.pyplot as plt
    from pyrocko.plot.cake_plot import mpl_init, labelspace, xscaled, yscaled
    mpl_init()

    def setup(parser):
        parser.add_option('--source-depth',
                          dest='depth',
                          type=float,
                          help='Source depth in km')

    parser, options, args = cl_parse(
        'tttview',
        args,
        setup=setup,
        details="Comma seperated <phase-ids>, eg. 'fomosto tttview Pdiff,S'.")

    try:
        phase_ids = args.pop().split(',')
    except Exception:
        parser.error('cannot get <phase-ids> argument')

    np = 1
    store_dir = get_store_dir(args)
    for phase_id in phase_ids:
        try:
            store = gf.Store(store_dir)
            phase = store.get_stored_phase(phase_id)
            axes = plt.subplot(2, len(phase_ids), np)
            labelspace(axes)
            xscaled(1. / km, axes)
            yscaled(1. / km, axes)
            phase.plot_2d(axes)
            axes.set_title(phase_id)
            np += 1
        except gf.StoreError as e:
            die(e)

    axes = plt.subplot(2, 1, 2)
    num_d = 100
    distances = num.linspace(store.config.distance_min,
                             store.config.distance_max, num_d)
    if options.depth:
        depth = options.depth
        depth *= 1000
    else:
        depth = store.config.source_depth_min + (
            store.config.source_depth_max - store.config.source_depth_min) / 2.

    if isinstance(store.config, gf.ConfigTypeA):
        arrivals = num.empty(num_d)
        for phase_id in phase_ids:
            arrivals[:] = num.NAN
            for i, d in enumerate(distances):
                arrivals[i] = store.t(phase_id, (depth, d))
            axes.plot(distances / 1000, arrivals, label=phase_id)
        axes.set_title('source depth %s km' % (depth / 1000))
        axes.set_xlabel('distance [km]')
        axes.set_ylabel('TT [s]')
        axes.legend()

    plt.tight_layout()
    plt.show()
예제 #3
0
def command_modelview(args):

    import matplotlib.pyplot as plt
    import numpy as num
    from pyrocko.plot.cake_plot import mpl_init, labelspace, xscaled, yscaled
    mpl_init()

    neat_labels = {
        'vp': '$v_p$',
        'vs': '$v_s$',
        'qp': '$Q_p$',
        'qs': '$Q_s$',
        'rho': '$\\rho$'
    }

    def setup(parser):
        parser.add_option(
            '--parameters',
            dest='parameters',
            default='vp,vs',
            metavar='vp,vs,....',
            help='select one or several of vp, vs, rho, qp, qs, vp/vs, qp/qs')

    units = {'vp': '[km/s]', 'vs': '[km/s]', 'rho': '[g/cm^3]'}

    parser, options, args = cl_parse('modelview', args, setup=setup)

    store_dirs = get_store_dirs(args)

    parameters = options.parameters.split(',')

    fig, axes = plt.subplots(1,
                             len(parameters),
                             sharey=True,
                             figsize=(len(parameters) * 3, 5))

    if not isinstance(axes, num.ndarray):
        axes = [axes]

    axes = dict(zip(parameters, axes))

    for store_id in store_dirs:
        try:
            store = gf.Store(store_id)
            mod = store.config.earthmodel_1d
            z = mod.profile('z')

            for p in parameters:
                ax = axes[p]
                labelspace(ax)
                if '/' in p:
                    p1, p2 = p.split('/')
                    profile = mod.profile(p1) / mod.profile(p2)
                else:
                    profile = mod.profile(p)

                ax.plot(profile, -z, label=store_id.split('/')[-1])
                if p in ['vs', 'vp', 'rho']:
                    xscaled(1. / 1000., ax)

                yscaled(1. / km, ax)

        except gf.StoreError as e:
            die(e)

    for p, ax in axes.items():
        ax.grid()
        if p in neat_labels:
            lab = neat_labels[p]
        elif all(x in neat_labels for x in p.split('/')):
            lab = '/'.join(neat_labels[x] for x in p.split('/'))
        else:
            lab = p

        ax.set_title(lab, y=1.02)

        if p in units:
            lab += ' ' + units[p]

        ax.autoscale()
        ax.set_xlabel(lab)

    axes[parameters[0]].set_ylabel('Depth [km]')

    handles, labels = ax.get_legend_handles_labels()

    if len(store_dirs) > 1:
        ax.legend(handles,
                  labels,
                  bbox_to_anchor=(0.5, 0.12),
                  bbox_transform=fig.transFigure,
                  ncol=3,
                  loc='upper center',
                  fancybox=True)

    plt.subplots_adjust(bottom=0.22, wspace=0.05)

    plt.show()
예제 #4
0
파일: fomosto.py 프로젝트: emolch/pyrocko
def command_tttview(args):
    import numpy as num
    import matplotlib.pyplot as plt
    from pyrocko.plot.cake_plot import mpl_init, labelspace, xscaled, yscaled
    mpl_init()

    def setup(parser):
        parser.add_option(
            '--source-depth', dest='depth', type=float,
            help='Source depth in km')

    parser, options, args = cl_parse(
        'tttview', args, setup=setup,
        details="Comma seperated <phase-ids>, eg. 'fomosto tttview Pdiff,S'.")

    try:
        phase_ids = args.pop().split(',')
    except Exception:
        parser.error('cannot get <phase-ids> argument')

    np = 1
    store_dir = get_store_dir(args)
    for phase_id in phase_ids:
        try:
            store = gf.Store(store_dir)
            phase = store.get_stored_phase(phase_id)
            axes = plt.subplot(2, len(phase_ids), np)
            labelspace(axes)
            xscaled(1./km, axes)
            yscaled(1./km, axes)
            phase.plot_2d(axes)
            axes.set_title(phase_id)
            np += 1
        except gf.StoreError as e:
            die(e)

    axes = plt.subplot(2, 1, 2)
    num_d = 100
    distances = num.linspace(store.config.distance_min,
                             store.config.distance_max,
                             num_d)
    if options.depth:
        depth = options.depth
        depth *= 1000
    else:
        depth = store.config.source_depth_min + (
            store.config.source_depth_max - store.config.source_depth_min)/2.

    if isinstance(store.config, gf.ConfigTypeA):
        arrivals = num.empty(num_d)
        for phase_id in phase_ids:
            arrivals[:] = num.NAN
            for i, d in enumerate(distances):
                arrivals[i] = store.t(phase_id, (depth, d))
            axes.plot(distances/1000, arrivals, label=phase_id)
        axes.set_title('source depth %s km' % (depth/1000))
        axes.set_xlabel('distance [km]')
        axes.set_ylabel('TT [s]')
        axes.legend()

    plt.tight_layout()
    plt.show()
예제 #5
0
파일: fomosto.py 프로젝트: emolch/pyrocko
def command_modelview(args):

    import matplotlib.pyplot as plt
    import numpy as num
    from pyrocko.plot.cake_plot import mpl_init, labelspace, xscaled, yscaled
    mpl_init()

    neat_labels = {
        'vp': '$v_p$',
        'vs': '$v_s$',
        'qp': '$Q_p$',
        'qs': '$Q_s$',
        'rho': '$\\rho$'}

    def setup(parser):
        parser.add_option(
            '--parameters', dest='parameters',
            default='vp,vs', metavar='vp,vs,....',
            help='select one or several of vp, vs, rho, qp, qs, vp/vs, qp/qs')

    units = {'vp': '[km/s]', 'vs': '[km/s]', 'rho': '[g/cm^3]'}

    parser, options, args = cl_parse('modelview', args, setup=setup)

    store_dirs = get_store_dirs(args)

    parameters = options.parameters.split(',')

    fig, axes = plt.subplots(1,
                             len(parameters),
                             sharey=True,
                             figsize=(len(parameters)*3, 5))

    if not isinstance(axes, num.ndarray):
        axes = [axes]

    axes = dict(zip(parameters, axes))

    for store_id in store_dirs:
        try:
            store = gf.Store(store_id)
            mod = store.config.earthmodel_1d
            z = mod.profile('z')

            for p in parameters:
                ax = axes[p]
                labelspace(ax)
                if '/' in p:
                    p1, p2 = p.split('/')
                    profile = mod.profile(p1)/mod.profile(p2)
                else:
                    profile = mod.profile(p)

                ax.plot(profile, -z, label=store_id.split('/')[-1])
                if p in ['vs', 'vp', 'rho']:
                    xscaled(1./1000., ax)

                yscaled(1./km, ax)

        except gf.StoreError as e:
            die(e)

    for p, ax in axes.items():
        ax.grid()
        if p in neat_labels:
            lab = neat_labels[p]
        elif all(x in neat_labels for x in p.split('/')):
            lab = '/'.join(neat_labels[x] for x in p.split('/'))
        else:
            lab = p

        ax.set_title(lab, y=1.02)

        if p in units:
            lab += ' ' + units[p]

        ax.autoscale()
        ax.set_xlabel(lab)

    axes[parameters[0]].set_ylabel('Depth [km]')

    handles, labels = ax.get_legend_handles_labels()

    if len(store_dirs) > 1:
        ax.legend(
            handles,
            labels,
            bbox_to_anchor=(0.5, 0.12),
            bbox_transform=fig.transFigure,
            ncol=3,
            loc='upper center',
            fancybox=True)

    plt.subplots_adjust(bottom=0.22,
                        wspace=0.05)

    plt.show()
예제 #6
0
    def plot(self, depth_range=(0, 60000.), ddepth=100., ddbin=2000.,
             vel_range=None, dvbin=100.,
             percent=False,
             plot_mode=True, plot_median=True, plot_mean=False,
             show_cbar=True,
             aspect=.02,
             phase='p',
             axes=None):
        ''' Plot a two 2D Histogram of seismic velocities

        :param depth_range: Depth range, ``(dmin, dmax)``,
            defaults to ``(0, 60)``
        :type depth_range: tuple
        :param vel_range: Velocity range, ``(vmin, vmax)``
        :type vel_range: tuple
        :param ddepth: Stepping in [m], defaults to ``.1``
        :type ddepth: float
        :param dvbin: Bin size in velocity dimension [m/s], defaults to .1
        :type dvbin: float
        :param dvbin: Bin size in depth dimension [m], defaults to 2000.
        :type dvbin: float
        :param phase: Phase to calculate ``p`` or ``s``, defaults to ``p``
        :type phase: str
        :param plot_mode: Plot the Mode
        :type plot_mode: bool
        :param plot_mean: Plot the Mean
        :type plot_mean: bool
        :param plot_median: Plot the Median
        :type plot_median: bool
        :param axes: Axes to plot into, defaults to None
        :type axes: :class:`matplotlib.Axes`
        '''

        import matplotlib.pyplot as plt

        fig, ax = _getCanvas(axes)

        ax = fig.gca()

        if vel_range is not None:
            vmin, vmax = vel_range
        dmin, dmax = depth_range

        vfield, vedg, dedg = self.histogram2d(vel_range=vel_range,
                                              depth_range=depth_range,
                                              ddepth=ddepth, dvbin=dvbin,
                                              ddbin=ddbin, phase=phase)
        vfield /= (ddbin / ddepth)

        if percent:
            vfield /= vfield.sum(axis=1)[num.newaxis, :]

        grid_ext = [vedg[0], vedg[-1], dedg[-1], dedg[0]]
        histogram = ax.imshow(vfield.swapaxes(0, 1),
                              interpolation='nearest',
                              extent=grid_ext, aspect=aspect)

        if show_cbar:
            cticks = num.unique(
                num.arange(0, vfield.max(), vfield.max() // 10).round())
            cbar = fig.colorbar(histogram, ticks=cticks, format='%1i',
                                orientation='horizontal')
            if percent:
                cbar.set_label('Percent')
            else:
                cbar.set_label('Number of Profiles')

        if plot_mode:
            sdepth, vel_mode, _ = self.modeVelocity(depth_range=depth_range,
                                                    ddepth=ddepth)
            ax.plot(vel_mode[sdepth < dmax] + ddepth/2,
                    sdepth[sdepth < dmax],
                    alpha=.8, color='w', label='Mode')

        if plot_mean:
            sdepth, vel_mean, _ = self.meanVelocity(depth_range=depth_range,
                                                    ddepth=ddepth)
            ax.plot(vel_mean[sdepth < dmax] + ddepth/2,
                    sdepth[sdepth < dmax],
                    alpha=.8, color='w', linestyle='--', label='Mean')

        if plot_median:
            sdepth, vel_median, _ = self.medianVelocity(
                                        depth_range=depth_range,
                                        ddepth=ddepth)
            ax.plot(vel_median[sdepth < dmax] + ddepth/2,
                    sdepth[sdepth < dmax],
                    alpha=.8, color='w', linestyle=':', label='Median')

        ax.grid(True, which="both", color="w", linewidth=.8, alpha=.4)

        ax.text(.025, .025, '%d Profiles' % self.nprofiles,
                color='w', alpha=.7,
                transform=ax.transAxes, fontsize=9, va='bottom', ha='left')

        ax.set_title('Crustal Velocity Distribution')
        ax.set_xlabel('%s [km/s]' % vel_labels[phase])
        ax.set_ylabel('Depth [km]')
        yscaled(1./km, ax)
        xoffset_scale(dvbin/2, 1./km, ax)
        ax.set_xlim(vel_range)

        if self.name is not None:
            ax.set_title('%s for %s' % (ax.get_title(), self.name))

        if plot_mode or plot_mean or plot_median:
            leg = ax.legend(loc=1, fancybox=True, prop={'size': 10.})
            leg.get_frame().set_alpha(.6)

        if axes is None:
            plt.show()