Ejemplo n.º 1
0
    def _old_test_plot_synthetics(self):
        from matplotlib import pyplot as plt

        fig, ax = plt.subplots(nrows=1,
                               ncols=3,
                               figsize=plot.mpl_papersize('a4', 'portrait'))

        cmap = plt.cm.jet
        fontsize = 12
        sz = 10.

        if self.reference is None:
            self._get_synthetic_data()


#        disp = self.test_block_geometry()
#        disp = self.test_block_synthetics()
        disp = self._test_backslip_synthetics(2)

        for i, comp in enumerate('NEZ'):
            im = ax[i].scatter(self.lons, self.lats, sz, disp[:, i], cmap=cmap)
            cblabel = '%s displacement [m]' % comp
            cbs = plt.colorbar(im,
                               ax=ax[i],
                               orientation='horizontal',
                               cmap=cmap)
            cbs.set_label(cblabel, fontsize=fontsize)

        plt.show()
Ejemplo n.º 2
0
def plot_init(size, save, show):
    fontsize = 9
    mpl_init()
    fig = plt.figure(figsize=mpl_papersize(size, 'landscape'))

    labelpos = mpl_margins(fig, w=7., h=5., units=fontsize)
    axes = fig.add_subplot(1, 1, 1)
    labelpos(axes, 2., 1.5)

    showplt = bool(show or not save)

    return fig, axes, showplt
Ejemplo n.º 3
0
    def _test_sample(self, n_jobs, test_folder):
        logger.info('Running on %i cores...' % n_jobs)

        n = 4

        mu1 = num.ones(n) * (1. / 2)
        mu2 = -mu1

        stdev = 0.1
        sigma = num.power(stdev, 2) * num.eye(n)
        isigma = num.linalg.inv(sigma)
        dsigma = num.linalg.det(sigma)

        w1 = stdev
        w2 = (1 - stdev)

        def two_gaussians(x):
            log_like1 = - 0.5 * n * tt.log(2 * num.pi) \
                        - 0.5 * tt.log(dsigma) \
                        - 0.5 * (x - mu1).T.dot(isigma).dot(x - mu1)
            log_like2 = - 0.5 * n * tt.log(2 * num.pi) \
                        - 0.5 * tt.log(dsigma) \
                        - 0.5 * (x - mu2).T.dot(isigma).dot(x - mu2)
            return tt.log(w1 * tt.exp(log_like1) + w2 * tt.exp(log_like2))

        with pm.Model() as PT_test:
            X = pm.Uniform('X',
                           shape=n,
                           lower=-2. * num.ones_like(mu1),
                           upper=2. * num.ones_like(mu1),
                           testval=-1. * num.ones_like(mu1),
                           transform=None)
            like = pm.Deterministic('tmp', two_gaussians(X))
            llk = pm.Potential('like', like)

        with PT_test:
            step = metropolis.Metropolis(
                n_chains=n_jobs,
                likelihood_name=PT_test.deterministics[0].name,
                proposal_name='MultivariateCauchy',
                tune_interval=self.tune_interval)

        pt.pt_sample(
            step,
            n_chains=n_jobs,
            n_samples=self.n_samples,
            swap_interval=self.swap_interval,
            beta_tune_interval=self.beta_tune_interval,
            n_workers_posterior=self.n_workers_posterior,
            homepath=test_folder,
            progressbar=False,
            buffer_size=self.buffer_size,
            model=PT_test,
            rm_flag=False,
            keep_tmp=False)

        stage_handler = TextStage(test_folder)

        mtrace = stage_handler.load_multitrace(-1, model=PT_test)
        history = load_objects(os.path.join(stage_handler.stage_path(-1), sample_p_outname))

        n_steps = self.n_samples
        burn = self.burn
        thin = self.thin

        def burn_sample(x):
            if n_steps == 1:
                return x
            else:
                nchains = int(x.shape[0] / n_steps)
                xout = []
                for i in range(nchains):
                    nstart = int((n_steps * i) + (n_steps * burn))
                    nend = int(n_steps * (i + 1) - 1)
                    xout.append(x[nstart:nend:thin])

                return num.vstack(xout)

        from pymc3 import traceplot
        from matplotlib import pyplot as plt
        traceplot(mtrace, transform=burn_sample)

        fig, axes = plt.subplots(
            nrows=1, ncols=2, figsize=mpl_papersize('a5', 'portrait'))
        axes[0].plot(history.acceptance, 'r')
        axes[0].set_ylabel('Acceptance ratio')
        axes[0].set_xlabel('Update interval')
        axes[1].plot(num.array(history.t_scales), 'k')
        axes[1].set_ylabel('Temperature scaling')
        axes[1].set_xlabel('Update interval')

        n_acceptances = len(history)
        ncol = 3
        nrow = int(num.ceil(n_acceptances / float(ncol)))

        fig2, axes1 = plt.subplots(
            nrows=nrow, ncols=ncol, figsize=mpl_papersize('a4', 'portrait'))
        axes1 = num.atleast_2d(axes1)
        fig3, axes2 = plt.subplots(
            nrows=nrow, ncols=ncol, figsize=mpl_papersize('a4', 'portrait'))
        axes2 = num.atleast_2d(axes2)

        acc_arrays = history.get_acceptance_matrixes_array()
        sc_arrays = history.get_sample_counts_array()
        scvmin = sc_arrays.min(0).min(0)
        scvmax = sc_arrays.max(0).max(0)
        accvmin = acc_arrays.min(0).min(0)
        accvmax = acc_arrays.max(0).max(0)

        for i in range(ncol * nrow):
            rowi, coli = mod_i(i, ncol)
            #if i == n_acceptances:
             #   pass
                #plt.colorbar(im, axes1[rowi, coli])
                #plt.colorbar(im2, axes2[rowi, coli])

            if i > n_acceptances - 1:
                try:
                    fig2.delaxes(axes1[rowi, coli])
                    fig3.delaxes(axes2[rowi, coli])
                except KeyError:
                    pass
            else:
                axes1[rowi, coli].matshow(
                    history.acceptance_matrixes[i],
                    vmin=accvmin[i], vmax=accvmax[i], cmap='hot')
                axes1[rowi, coli].set_title('min %i, max%i' % (accvmin[i], accvmax[i]))
                axes1[rowi, coli].get_xaxis().set_ticklabels([])
                axes2[rowi, coli].matshow(
                    history.sample_counts[i], vmin=scvmin[i], vmax=scvmax[i], cmap='hot')
                axes2[rowi, coli].set_title('min %i, max%i' % (scvmin[i], scvmax[i]))
                axes2[rowi, coli].get_xaxis().set_ticklabels([])


        fig2.suptitle('Accepted number of samples')
        fig2.tight_layout()
        fig3.tight_layout()
        fig3.suptitle('Total number of samples')
        plt.show()
Ejemplo n.º 4
0
def plot_detection(grid,
                   receivers,
                   frames,
                   tmin_frames,
                   deltat_cf,
                   imax,
                   iframe,
                   xpeak,
                   ypeak,
                   zpeak,
                   tr_stackmax,
                   tpeaks,
                   apeaks,
                   detector_threshold,
                   wmin,
                   wmax,
                   pdata,
                   trs_raw,
                   fmin,
                   fmax,
                   idetection,
                   tpeaksearch,
                   movie=False,
                   save_filename=None,
                   show=True,
                   event=None):
    from matplotlib import pyplot as plt
    from matplotlib import cm
    from matplotlib.animation import FuncAnimation

    nsls = set(tr.nslc_id[:3] for tr in trs_raw)
    receivers_on = [r for r in receivers if r.codes in nsls]
    receivers_off = [r for r in receivers if r.codes not in nsls]

    distances = grid.distances(receivers)

    plot.mpl_init(fontsize=9)

    fig = plt.figure(figsize=plot.mpl_papersize('a4', 'landscape'))

    axes = plt.subplot2grid((2, 3), (0, 2), aspect=1.0)
    plot.mpl_labelspace(axes)

    axes2 = plt.subplot2grid((2, 3), (1, 2))
    plot.mpl_labelspace(axes2)

    axes3 = plt.subplot2grid((2, 3), (0, 1), rowspan=2)
    axes4 = plt.subplot2grid((2, 3), (0, 0), rowspan=2)
    if grid.distance_max() > km:
        dist_units = km
        axes.set_xlabel('Easting [km]')
        axes.set_ylabel('Northing [km]')
        axes4.set_ylabel('Distance [km]')
    else:
        dist_units = 1.0
        axes.set_xlabel('Easting [m]')
        axes.set_ylabel('Northing [m]')
        axes4.set_ylabel('Distance [m]')

    axes.locator_params(nbins=6, tight=True)

    axes2.set_xlabel('Time [s]')
    axes2.set_ylabel('Detector level')

    axes3.set_xlabel('Time [s]')
    for el in axes3.get_yticklabels():
        el.set_visible(False)

    axes4.set_xlabel('Time [s]')

    tpeak_current = tmin_frames + deltat_cf * iframe
    t0 = tpeak_current
    tduration = 2.0 * tpeaksearch

    axes2.axvspan(tr_stackmax.tmin - t0,
                  wmin - t0,
                  color=plot.mpl_color('aluminium2'))

    axes2.axvspan(wmax - t0,
                  tr_stackmax.tmax - t0,
                  color=plot.mpl_color('aluminium2'))

    axes2.axvspan(tpeak_current - 0.5 * tduration - t0,
                  tpeak_current + 0.5 * tduration - t0,
                  color=plot.mpl_color('scarletred2'),
                  alpha=0.3,
                  lw=0.)

    axes2.set_xlim(tr_stackmax.tmin - t0, tr_stackmax.tmax - t0)

    axes2.axhline(detector_threshold,
                  color=plot.mpl_color('aluminium6'),
                  lw=2.)

    t = tr_stackmax.get_xdata()
    amp = tr_stackmax.get_ydata()
    axes2.plot(t - t0, amp, color=plot.mpl_color('scarletred2'), lw=1.)

    for tpeak, apeak in zip(tpeaks, apeaks):
        axes2.plot(tpeak - t0, apeak, '*', ms=20., mfc='white', mec='black')

    station_index = dict((rec.codes, i) for (i, rec) in enumerate(receivers))

    dists_all = []
    amps = []
    shifts = []
    pdata2 = []
    for trs, shift_table, shifter in pdata:
        trs = [tr.copy() for tr in trs]
        dists = []
        for tr in trs:
            istation = station_index[tr.nslc_id[:3]]
            shift = shift_table[imax, istation]
            tr2 = tr.chop(tpeak_current - 0.5 * tduration + shift,
                          tpeak_current + 0.5 * tduration + shift,
                          inplace=False)

            dists.append(distances[imax, istation])
            amp = tr2.get_ydata() * shifter.weight
            amps.append(num.max(num.abs(amp)))
            shifts.append(shift)

        pdata2.append((trs, dists, shift_table, shifter))
        dists_all.extend(dists)

    dist_min = min(dists_all)
    dist_max = max(dists_all)

    shift_min = min(shifts)
    shift_max = max(shifts)

    amp_max = max(amps)

    scalefactor = (dist_max - dist_min) / len(trs) * 0.5

    axes3.set_xlim(-0.5 * tduration + shift_min, 0.5 * tduration + shift_max)
    axes3.set_ylim((dist_min - scalefactor) / dist_units,
                   (dist_max + scalefactor) / dist_units)

    axes4.set_xlim(-0.5 * tduration + shift_min, 0.5 * tduration + shift_max)
    axes4.set_ylim((dist_min - scalefactor) / dist_units,
                   (dist_max + scalefactor) / dist_units)

    axes3.axvline(0., color=plot.mpl_color('aluminium3'), lw=2.)

    nsl_have = set()
    phase_markers = []
    picks = []
    for ishifter, (trs, dists, shift_table, shifter) in enumerate(pdata2):
        color = plot.mpl_graph_color(ishifter)

        for tr, dist in zip(trs, dists):
            tmint = tr.tmin
            tr = tr.chop(tpeak_current - 0.5 * tduration + shift_min,
                         tpeak_current + 0.5 * tduration + shift_max,
                         inplace=False)

            nsl = tr.nslc_id[:3]
            istation = station_index[nsl]
            shift = shift_table[imax, istation]

            phase_markers.append(
                PhaseMarker([(nsl[0], nsl[1], "", nsl[2])],
                            tmin=tmint + shift,
                            tmax=tmint + shift,
                            phasename=shifter.name,
                            event_time=t0,
                            event_hash=idetection))
            p = Pick(time=UTCDateTime(tmint + shift),
                     waveform_id=WaveformStreamID(network_code=nsl[0],
                                                  station_code=nsl[1]),
                     phase_hint=shifter.name,
                     method_id="lassie")
            picks.append(p)
            axes3.plot(shift,
                       dist / dist_units,
                       '|',
                       mew=2,
                       mec=color,
                       ms=10,
                       zorder=2)

            t = tr.get_xdata()
            amp = tr.get_ydata() * shifter.weight
            amp /= amp_max
            axes3.plot(
                t - t0,
                (dist + scalefactor * amp + ishifter * scalefactor * 0.1) /
                dist_units,
                color=color,
                zorder=1)

            if nsl not in nsl_have:
                axes3.annotate('.'.join(nsl),
                               xy=(t[0] - t0, dist / dist_units),
                               xytext=(10., 0.),
                               textcoords='offset points',
                               verticalalignment='top')

                nsl_have.add(nsl)

        for tr in trs_raw:
            istation = station_index[tr.nslc_id[:3]]
            dist = distances[imax, istation]
            shift = shift_table[imax, istation]

            tr = tr.copy()

            tr.highpass(4, fmin, demean=True)
            tr.lowpass(4, fmax, demean=False)

            tr.chop(tpeak_current - 0.5 * tduration + shift_min,
                    tpeak_current + 0.5 * tduration + shift_max)

            t = tr.get_xdata()
            amp = tr.get_ydata().astype(num.float)
            amp = amp / num.max(num.abs(amp))

            axes4.plot(t - t0, (dist + scalefactor * amp) / dist_units,
                       color='black',
                       alpha=0.5,
                       zorder=1)

            axes4.plot(shift,
                       dist / dist_units,
                       '|',
                       mew=2,
                       mec=color,
                       ms=10,
                       zorder=2)
    PhaseMarker.save_markers(phase_markers,
                             "%s.pym" % (save_filename[:-4]),
                             fdigits=3)
    event_obspy = Event()
    origin = Origin(time=UTCDateTime(t0),
                    longitude=event.lon,
                    latitude=event.lat,
                    method="lassie")
    event_obspy.origins.append(origin)
    event_obspy.picks = picks
    cat = Catalog()
    cat.append(event_obspy)
    cat.write(save_filename[:-4] + ".qml", format="QUAKEML")
    nframes = frames.shape[1]

    iframe_min = max(0, int(round(iframe - 0.5 * tduration / deltat_cf)))
    iframe_max = min(nframes - 1,
                     int(round(iframe + 0.5 * tduration / deltat_cf)))

    amax = frames[imax, iframe]

    axes.set_xlim(grid.ymin / dist_units, grid.ymax / dist_units)
    axes.set_ylim(grid.xmin / dist_units, grid.xmax / dist_units)

    cmap = cm.YlOrBr
    system = ('ne', grid.lat, grid.lon)

    static_artists = []
    static_artists.extend(
        plot_receivers(axes,
                       receivers_on,
                       system=system,
                       units=dist_units,
                       style=dict(mfc='black', ms=5.0)))

    static_artists.extend(
        plot_receivers(axes,
                       receivers_off,
                       system=system,
                       units=dist_units,
                       style=dict(mfc='none', ms=5.0)))

    static_artists.extend(
        axes.plot(ypeak / dist_units,
                  xpeak / dist_units,
                  '*',
                  ms=20.,
                  mec='black',
                  mfc='white'))

    static_artists.append(
        fig.suptitle('%06i - %s' % (idetection, util.time_to_str(t0))))

    frame_artists = []
    progress_artists = []

    def update(iframe):
        if iframe is not None:
            frame = frames[:, iframe]
            if not progress_artists:
                progress_artists[:] = [
                    axes2.axvline(tmin_frames - t0 + deltat_cf * iframe,
                                  color=plot.mpl_color('scarletred3'),
                                  alpha=0.5,
                                  lw=2.)
                ]

            else:
                progress_artists[0].set_xdata(tmin_frames - t0 +
                                              deltat_cf * iframe)

        else:
            frame = num.max(frames[:, iframe_min:iframe_max + 1], axis=1)

        frame_artists[:] = grid.plot(axes,
                                     frame,
                                     amin=0.0,
                                     amax=amax,
                                     cmap=cmap,
                                     system=system,
                                     artists=frame_artists,
                                     units=dist_units,
                                     shading='gouraud')

        return frame_artists + progress_artists + static_artists

    if movie:
        ani = FuncAnimation(
            fig,
            update,
            frames=list(range(iframe_min, iframe_max + 1))[::10] + [None],
            interval=20.,
            repeat=False,
            blit=True)

    else:
        ani = None
        update(None)

    if save_filename:
        fig.savefig(save_filename)

    if show:
        plt.show()
    else:
        plt.close()

    del ani
Ejemplo n.º 5
0
def bayesian_model_plot(models, axes=None, draw_bg=True, highlightidx=[]):
    """
    Plot cake layered earth models.
    """
    fontsize = 10
    if axes is None:
        mpl_init(fontsize=fontsize)
        fig, axes = plt.subplots(
            nrows=1, ncols=1, figsize=mpl_papersize('a6', 'portrait'))
        labelpos = mpl_margins(
            fig, left=6, bottom=4, top=1.5, right=0.5, units=fontsize)
        labelpos(axes, 2., 1.5)

    def plot_profile(mod, axes, vp_c, vs_c, lw=0.5):
        z = mod.profile('z')
        vp = mod.profile('vp')
        vs = mod.profile('vs')
        axes.plot(vp, z, color=vp_c, lw=lw)
        axes.plot(vs, z, color=vs_c, lw=lw)

    cp.labelspace(axes)
    cp.labels_model(axes=axes)
    if draw_bg:
        cp.sketch_model(models[0], axes=axes)
    else:
        axes.spines['right'].set_visible(False)
        axes.spines['top'].set_visible(False)

    ref_vp_c = scolor('aluminium5')
    ref_vs_c = scolor('aluminium5')
    vp_c = scolor('scarletred2')
    vs_c = scolor('skyblue2')

    for i, mod in enumerate(models):
            plot_profile(
            mod, axes, vp_c=light(vp_c, 0.3), vs_c=light(vs_c, 0.3), lw=1.)

    for count, i in enumerate(sorted(highlightidx)):
        if count == 0:
            vpcolor = ref_vp_c
            vscolor = ref_vs_c
        elif count == 1:
            vpcolor = scolor('butter3')
            vscolor = scolor('butter3')
        elif count == 2:
            vpcolor = scolor('skyblue2')
            vscolor = scolor('skyblue2')
        elif count == 3:
            vpcolor = scolor('plum2')
            vscolor = scolor('plum2')
        else:
            vpcolor = scolor('scarletred2')
            vscolor = scolor('scarletred2')

        plot_profile(
            models[i], axes, vp_c=vpcolor, vs_c=vscolor, lw=2.)

    ymin, ymax = axes.get_ylim()
    xmin, xmax = axes.get_xlim()
    xmin = 0.
    my = (ymax - ymin) * 0.05
    mx = (xmax - xmin) * 0.2
    axes.set_ylim(ymax, ymin - my)
    axes.set_xlim(xmin, xmax + mx)
    return fig, axes
Ejemplo n.º 6
0
def plot(
        responses,
        filename=None,
        dpi=100,
        fmin=0.01, fmax=100., nf=100,
        normalize=False,
        fontsize=10.,
        figsize=None,
        styles=None,
        labels=None):

    '''
    Draw instrument responses in Bode plot style.

    :param responses: instrument responses as
        :py:class:`pyrocko.trace.FrequencyResponse` objects
    :param fmin: minimum frequency [Hz]
    :param fmax: maximum frequency [Hz]
    :param nf: number of frequencies where to evaluate the response
    :param normalize: if ``True`` normalize flat part of response to be ``1``
    :param styles: :py:class:`list` of :py:class:`dict` objects  with keyword
        arguments to be passed to matplotlib's
        :py:meth:`matplotlib.axes.Axes.plot` function when drawing the response
        lines. Length must match number of responses.
    :param filename: file name to pass to matplotlib's ``savefig`` function. If
        ``None``, the plot is shown with :py:func:`matplotlib.pyplot.show`.
    :param fontsize: font size in points used in axis labels and legend
    :param figsize: :py:class:`tuple`, ``(width, height)`` in inches
    :param labels: :py:class:`list` of names to show in legend. Length must
        correspond to number of responses.
    '''

    from matplotlib import pyplot as plt
    from pyrocko.plot import mpl_init, mpl_margins, mpl_papersize
    from pyrocko.plot import graph_colors, to01

    mpl_init(fontsize=fontsize)

    if figsize is None:
        figsize = mpl_papersize('a4', 'portrait')

    fig = plt.figure(figsize=figsize)
    labelpos = mpl_margins(
        fig, w=7., h=5., units=fontsize, nw=1, nh=2, hspace=2.)
    axes_amplitude = fig.add_subplot(2, 1, 1)
    labelpos(axes_amplitude, 2., 1.5)
    axes_phase = fig.add_subplot(2, 1, 2)
    labelpos(axes_phase, 2., 1.5)

    setup_axes(axes_amplitude, axes_phase)

    if styles is None:
        styles = [
            dict(color=to01(graph_colors[i % len(graph_colors)]))
            for i in range(len(responses))]
    else:
        assert len(styles) == len(responses)

    if labels is None:
        labels = [None] * len(responses)
    else:
        assert len(labels) == len(responses)

    a_ranges, p_ranges = [], []
    have_labels = False
    for style, resp, label in zip(styles, responses, labels):
        a_range, p_range = draw(
            response=resp,
            axes_amplitude=axes_amplitude,
            axes_phase=axes_phase,
            fmin=fmin, fmax=fmax, nf=nf,
            normalize=normalize,
            style=style,
            label=label)

        if label is not None:
            have_labels = True

        a_ranges.append(a_range)
        p_ranges.append(p_range)

    if have_labels:
        axes_amplitude.legend(loc='lower right', prop=dict(size=fontsize))

    a_ranges = num.array(a_ranges)
    p_ranges = num.array(p_ranges)

    amin, amax = num.min(a_ranges), num.max(a_ranges)
    pmin, pmax = num.min(p_ranges), num.max(p_ranges)

    amin *= 0.5
    amax *= 2.0

    pmin -= 0.5
    pmax += 0.5

    axes_amplitude.set_ylim(amin, amax)
    axes_phase.set_ylim(pmin, pmax)
    axes_amplitude.set_xlim(fmin, fmax)
    axes_phase.set_xlim(fmin, fmax)

    if filename is not None:
        fig.savefig(filename, dpi=dpi)
    else:
        plt.show()
Ejemplo n.º 7
0
    def draw_figures(self, history):
        misfit_cutoff = self.misfit_cutoff
        sort_by = self.sort_by

        problem = history.problem
        models = history.models

        npar = problem.nparameters
        ndep = problem.ndependants
        fontsize = self.font_size
        nfx, nfy = self.subplot_layout

        imodels = num.arange(history.nmodels)
        bounds = problem.get_combined_bounds()

        xref = problem.get_reference_model(expand=True)

        gms = problem.combine_misfits(history.misfits)
        gms_softclip = num.where(gms > 1.0, 0.2 * num.log10(gms) + 1.0, gms)

        isort = num.argsort(gms)[::-1]

        if sort_by == 'iteration':
            imodels = imodels[isort]
        elif sort_by == 'misfit':
            imodels = num.arange(imodels.size)
        else:
            assert False

        gms = gms[isort]
        gms_softclip = gms_softclip[isort]
        models = models[isort, :]

        iorder = num.empty_like(isort)
        iorder = num.arange(iorder.size)

        if misfit_cutoff is None:
            ibest = num.ones(gms.size, dtype=num.bool)
        else:
            ibest = gms < misfit_cutoff

        def config_axes(axes, nfx, nfy, impl, iplot, nplots):
            if (impl - 1) % nfx != nfx - 1:
                axes.get_yaxis().tick_left()

            if (impl - 1) >= (nfx * (nfy - 1)) or iplot >= nplots - nfx:
                axes.set_xlabel('Iteration')
                if not (impl - 1) // nfx == 0:
                    axes.get_xaxis().tick_bottom()
            elif (impl - 1) // nfx == 0:
                axes.get_xaxis().tick_top()
                axes.set_xticklabels([])
            else:
                axes.get_xaxis().set_visible(False)

        # nfz = (npar + ndep + 1 - 1) / (nfx*nfy) + 1
        cmap = cm.YlOrRd
        cmap = cm.jet
        msize = self.marker_size
        axes = None
        figs = []
        fig = None
        alpha = 0.5
        for ipar in range(npar):
            impl = ipar % (nfx * nfy) + 1

            if impl == 1:
                fig = plt.figure(figsize=self.size_inch)
                labelpos = mpl_margins(fig,
                                       nw=nfx,
                                       nh=nfy,
                                       w=7.,
                                       h=5.,
                                       wspace=7.,
                                       hspace=2.,
                                       units=fontsize)

                item = PlotItem(name='fig_%i' % (len(figs) + 1))
                item.attributes['parameters'] = []
                figs.append((item, fig))

            par = problem.parameters[ipar]

            figs[-1][0].attributes['parameters'].append(par.name)

            axes = fig.add_subplot(nfy, nfx, impl)
            labelpos(axes, 2.5, 2.0)

            axes.set_ylabel(par.get_label())
            axes.get_yaxis().set_major_locator(plt.MaxNLocator(4))

            config_axes(axes, nfx, nfy, impl, ipar, npar + ndep + 1)

            axes.set_ylim(*fixlim(*par.scaled(bounds[ipar])))
            axes.set_xlim(0, history.nmodels)

            axes.scatter(imodels[ibest],
                         par.scaled(models[ibest, ipar]),
                         s=msize,
                         c=iorder[ibest],
                         edgecolors='none',
                         cmap=cmap,
                         alpha=alpha)

            axes.axhline(par.scaled(xref[ipar]), color='black', alpha=0.3)

        for idep in range(ndep):
            # ifz, ify, ifx = num.unravel_index(ipar, (nfz, nfy, nfx))
            impl = (npar + idep) % (nfx * nfy) + 1

            if impl == 1:
                fig = plt.figure(figsize=mpl_papersize('a5', 'landscape'))
                labelpos = mpl_margins(fig,
                                       nw=nfx,
                                       nh=nfy,
                                       w=7.,
                                       h=5.,
                                       wspace=7.,
                                       hspace=2.,
                                       units=fontsize)

                item = PlotItem(name='fig_%i' % (len(figs) + 1))
                item.attributes['parameters'] = []

                figs.append((item, fig))

            par = problem.dependants[idep]
            figs[-1][0].attributes['parameters'].append(par.name)

            axes = fig.add_subplot(nfy, nfx, impl)
            labelpos(axes, 2.5, 2.0)

            axes.set_ylabel(par.get_label())
            axes.get_yaxis().set_major_locator(plt.MaxNLocator(4))

            config_axes(axes, nfx, nfy, impl, npar + idep, npar + ndep + 1)

            axes.set_ylim(*fixlim(*par.scaled(bounds[npar + idep])))
            axes.set_xlim(0, history.nmodels)

            ys = problem.make_dependant(models[ibest, :], par.name)
            axes.scatter(imodels[ibest],
                         par.scaled(ys),
                         s=msize,
                         c=iorder[ibest],
                         edgecolors='none',
                         cmap=cmap,
                         alpha=alpha)

            y = problem.make_dependant(xref, par.name)
            axes.axhline(par.scaled(y), color='black', alpha=0.3)

        impl = (npar + ndep) % (nfx * nfy) + 1
        if impl == 1:
            fig = plt.figure(figsize=mpl_papersize('a5', 'landscape'))
            labelpos = mpl_margins(fig,
                                   nw=nfx,
                                   nh=nfy,
                                   w=7.,
                                   h=5.,
                                   wspace=7.,
                                   hspace=2.,
                                   units=fontsize)

            item = PlotItem(name='fig_%i' % (len(figs) + 1))
            item.attributes['parameters'] = []

            figs.append((item, fig))

        axes = fig.add_subplot(nfy, nfx, impl)
        labelpos(axes, 2.5, 2.0)

        config_axes(axes, nfx, nfy, impl, npar + ndep, npar + ndep + 1)

        axes.set_ylim(0., 1.5)
        axes.set_yticks([0., 0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4])
        axes.set_yticklabels(
            ['0.0', '0.2', '0.4', '0.6', '0.8', '1', '10', '100'])

        axes.scatter(imodels[ibest],
                     gms_softclip[ibest],
                     c=iorder[ibest],
                     s=msize,
                     edgecolors='none',
                     cmap=cmap,
                     alpha=alpha)

        axes.axhspan(1.0, 1.5, color=(0.8, 0.8, 0.8), alpha=0.2)
        axes.axhline(1.0, color=(0.5, 0.5, 0.5), zorder=2)

        axes.set_xlim(0, history.nmodels)
        axes.set_xlabel('Iteration')

        axes.set_ylabel('Misfit')

        return figs
Ejemplo n.º 8
0
def run_plot(results_path,
             formats=['png'],
             min_bin_count=10,
             mag_step=0.1,
             nbins_dist=20):

    config = wconfig.read_config(op.join(results_path, 'config.yaml'))

    dists = []
    mags = []
    measures = []
    old_event_name = None
    with open(op.join(results_path, 'measures.txt'), 'r') as f:
        for line in f:

            if line.strip().startswith('#'):
                continue

            toks = line.split()
            event_name, station_codes = toks[:2]
            measures_this = list(map(float, toks[2:]))

            if event_name != old_event_name:
                ds = config.get_dataset(event_name)

            old_event_name = event_name

            station = ds.get_station(tuple(station_codes.split('.')))

            event = ds.get_event()
            dist = station.distance_to(event)
            mag = event.magnitude

            dists.append(dist)
            mags.append(mag)
            measures.append(measures_this)

    dists = num.array(dists, dtype=num.float)
    mags = num.array(mags, dtype=num.float)
    measures = num.array(measures, dtype=num.float)

    from matplotlib import pyplot as plt
    from pyrocko import plot
    from scipy.stats import binned_statistic_2d

    plot.mpl_init()

    mag_min = num.floor(num.min(mags) / mag_step) * mag_step - mag_step / 2.
    mag_max = num.ceil(num.max(mags) / mag_step) * mag_step + mag_step / 2.
    nbins_mag = int(round((mag_max - mag_min) / mag_step))
    mag_bins = num.linspace(mag_min, mag_max, nbins_mag + 1)
    # mag_centers = 0.5*(mag_bins[:-1] + mag_bins[1:])

    dist_min = num.min(dists)
    dist_max = num.max(dists)
    dist_bins = num.linspace(dist_min, dist_max, nbins_dist + 1)
    # dist_centers = 0.5*(dist_bins[:-1] + dist_bins[1:])

    measure_names = [m.name for m in config.measures]
    for imeasure, measure_name in enumerate(measure_names):
        fontsize = 9.0
        fig = plt.figure(figsize=plot.mpl_papersize('a5', 'landscape'))
        labelpos = plot.mpl_margins(fig, w=7, h=5., units=fontsize)

        axes = fig.add_subplot(1, 1, 1)
        axes.set_xlabel('Distance [km]')
        axes.set_ylabel('Magnitude')

        labelpos(axes, 2., 1.5)

        fig.suptitle(measure_name)

        medians, _, _, _ = binned_statistic_2d(dists,
                                               mags,
                                               measures[:, imeasure],
                                               statistic='median',
                                               bins=[dist_bins, mag_bins])

        counts, _, _, _ = binned_statistic_2d(dists,
                                              mags,
                                              measures[:, imeasure],
                                              statistic='count',
                                              bins=[dist_bins, mag_bins])

        medians[counts < min_bin_count] = None
        medians = num.log10(medians)

        im = axes.pcolorfast(dist_bins / km,
                             mag_bins,
                             medians.T,
                             vmin=num.nanmin(medians),
                             vmax=num.nanmax(medians),
                             cmap='YlOrBr')

        fig.colorbar(im).set_label('$log_{10}$ measure')

        for fmt in formats:
            plot_path = op.join(results_path, 'plots',
                                'dist_mag_median_%s.%s' % (measure_name, fmt))

            util.ensuredirs(plot_path)

            fig.savefig(plot_path)
            logger.info('plot saved: %s' % plot_path)
Ejemplo n.º 9
0
from pyrocko import topo, plot, orthodrome as od

lon_min, lon_max, lat_min, lat_max = 14.34, 14.50, 40.77, 40.87
dem_name = 'SRTMGL3'

# extract gridded topography (possibly downloading first)
tile = topo.get(dem_name, (lon_min, lon_max, lat_min, lat_max))

# geographic to local cartesian coordinates
lons = tile.x()
lats = tile.y()
lons2 = num.tile(lons, lats.size)
lats2 = num.repeat(lats, lons.size)
norths, easts = od.latlon_to_ne_numpy(lats[0], lons[0], lats2, lons2)
norths = norths.reshape((lats.size, lons.size))
easts = easts.reshape((lats.size, lons.size))

# plot it
plt = plot.mpl_init(fontsize=10.)
fig = plt.figure(figsize=plot.mpl_papersize('a5', 'landscape'))
axes = fig.add_subplot(1, 1, 1, aspect=1.0)
cbar  = axes.pcolormesh(easts, norths, tile.data,
                        cmap='gray', shading='gouraud')
fig.colorbar(cbar, label='Altitude [m]')
axes.set_title(dem_name)
axes.set_xlim(easts.min(), easts.max())
axes.set_ylim(norths.min(), norths.max())
axes.set_xlabel('Easting [m]')
axes.set_ylabel('Northing [m]')
fig.savefig('topo_example.png')
Ejemplo n.º 10
0
def correlation_plot(mtrace, varnames=None,
        transform=lambda x: x, figsize=None, cmap=None, grid=200, point=None,
        point_style='.', point_color='white', point_size='8'):
    """
    Plot 2d marginals (with kernel density estimation) showing the correlations
    of the model parameters.

    Parameters
    ----------
    mtrace : :class:`pymc3.base.MutliTrace`
        Mutlitrace instance containing the sampling results
    varnames : list of variable names
        Variables to be plotted, if None all variable are plotted
    transform : callable
        Function to transform data (defaults to identity)
    figsize : figure size tuple
        If None, size is (12, num of variables * 2) inch
    cmap : matplotlib colormap
    grid : resolution of kernel density estimation
    point : dict
        Dictionary of variable name / value  to be overplotted as marker
        to the posteriors e.g. mean of posteriors, true values of a simulation
    point_style : str
        style of marker according to matplotlib conventions
    point_color : str or tuple of 3
        color according to matplotlib convention
    point_size : str
        marker size according to matplotlib conventions

    Returns
    -------
    fig : figure object
    axs : subplot axis handles
    """

    if varnames is None:
        varnames = mtrace.varnames

    nvar = len(varnames)

    if figsize is None:
        figsize = mpl_papersize('a4', 'landscape')

    fig, axs = plt.subplots(sharey='row', sharex='col',
        nrows=nvar - 1, ncols=nvar - 1, figsize=figsize)

    d = dict()
    for var in varnames:
        d[var] = transform(mtrace.get_values(
                var, combine=True, squeeze=True))

    for k in range(nvar - 1):
        a = d[varnames[k]]
        for l in range(k + 1, nvar):
            logger.debug('%s, %s' % (varnames[k], varnames[l]))
            b = d[varnames[l]]

            pmp.kde2plot(
                a, b, grid=grid, ax=axs[l - 1, k], cmap=cmap, aspect='auto')

            if point is not None:
                axs[l - 1, k].plot(point[varnames[k]], point[varnames[l]],
                    color=point_color, marker=point_style,
                    markersize=point_size)

            axs[l - 1, k].tick_params(direction='in')

            if k == 0:
                axs[l - 1, k].set_ylabel(varnames[l])

        axs[l - 1, k].set_xlabel(varnames[k])

    for k in range(nvar - 1):
        for l in range(k):
            fig.delaxes(axs[l, k])

    fig.subplots_adjust(wspace=0.05, hspace=0.05)

    return fig, axs
Ejemplo n.º 11
0
def seismic_fits(problem, stage, plot_options):
    """
    Modified from grond. Plot synthetic and data waveforms and the misfit for
    the selected posterior model.
    """

    fontsize = 8
    fontsize_title = 10

    target_index = dict(
        (target, i) for (i, target) in enumerate(problem.stargets))

    po = plot_options

    population, _, llk = stage.step.select_end_points(stage.mtrace)

    posterior_idxs = get_fit_indexes(llk)
    idx = posterior_idxs[po.post_llk]

    n_steps = problem.config.sampler_config.parameters.n_steps - 1
    d = stage.mtrace.point(idx=n_steps, chain=idx)
    gcms = d['seis_like']
    gcm_max = d['like']

    out_point = population[idx]

    results = problem.assemble_seismic_results(out_point)
    source = problem.sources[0]

    logger.info('Plotting waveforms ...')
    target_to_result = {}
    all_syn_trs = []
    dtraces = []
    for target in problem.stargets:
        i = target_index[target]
        target_to_result[target] = results[i]

        all_syn_trs.append(results[i].processed_syn)
        dtraces.append(results[i].processed_res)

    skey = lambda tr: tr.channel

    trace_minmaxs = trace.minmax(all_syn_trs, skey)
    dminmaxs = trace.minmax(dtraces, skey)

    for tr in dtraces:
        if tr:
            dmin, dmax = dminmaxs[skey(tr)]
            tr.ydata /= max(abs(dmin), abs(dmax))

    cg_to_targets = utility.gather(
        problem.stargets,
        lambda t: t.codes[3],
        filter=lambda t: t in target_to_result)

    cgs = cg_to_targets.keys()

    figs = []

    for cg in cgs:
        targets = cg_to_targets[cg]

        # can keep from here ... until
        nframes = len(targets)

        nx = int(math.ceil(math.sqrt(nframes)))
        ny = (nframes - 1) / nx + 1

        nxmax = 4
        nymax = 4

        nxx = (nx - 1) / nxmax + 1
        nyy = (ny - 1) / nymax + 1

        xs = num.arange(nx) / ((max(2, nx) - 1.0) / 2.)
        ys = num.arange(ny) / ((max(2, ny) - 1.0) / 2.)

        xs -= num.mean(xs)
        ys -= num.mean(ys)

        fxs = num.tile(xs, ny)
        fys = num.repeat(ys, nx)

        data = []

        for target in targets:
            azi = source.azibazi_to(target)[0]
            dist = source.distance_to(target)
            x = dist * num.sin(num.deg2rad(azi))
            y = dist * num.cos(num.deg2rad(azi))
            data.append((x, y, dist))

        gxs, gys, dists = num.array(data, dtype=num.float).T

        iorder = num.argsort(dists)

        gxs = gxs[iorder]
        gys = gys[iorder]
        targets_sorted = [targets[ii] for ii in iorder]

        gxs -= num.mean(gxs)
        gys -= num.mean(gys)

        gmax = max(num.max(num.abs(gys)), num.max(num.abs(gxs)))
        if gmax == 0.:
            gmax = 1.

        gxs /= gmax
        gys /= gmax

        dists = num.sqrt(
            (fxs[num.newaxis, :] - gxs[:, num.newaxis]) ** 2 +
            (fys[num.newaxis, :] - gys[:, num.newaxis]) ** 2)

        distmax = num.max(dists)

        availmask = num.ones(dists.shape[1], dtype=num.bool)
        frame_to_target = {}
        for itarget, target in enumerate(targets_sorted):
            iframe = num.argmin(
                num.where(availmask, dists[itarget], distmax + 1.))
            availmask[iframe] = False
            iy, ix = num.unravel_index(iframe, (ny, nx))
            frame_to_target[iy, ix] = target

        figures = {}
        for iy in xrange(ny):
            for ix in xrange(nx):
                if (iy, ix) not in frame_to_target:
                    continue

                ixx = ix / nxmax
                iyy = iy / nymax
                if (iyy, ixx) not in figures:
                    figures[iyy, ixx] = plt.figure(
                        figsize=mpl_papersize('a4', 'landscape'))

                    figures[iyy, ixx].subplots_adjust(
                        left=0.03,
                        right=1.0 - 0.03,
                        bottom=0.03,
                        top=1.0 - 0.06,
                        wspace=0.2,
                        hspace=0.2)

                    figs.append(figures[iyy, ixx])

                fig = figures[iyy, ixx]

                target = frame_to_target[iy, ix]

                amin, amax = trace_minmaxs[target.codes[3]]
                absmax = max(abs(amin), abs(amax))

                ny_this = nymax  # min(ny, nymax)
                nx_this = nxmax  # min(nx, nxmax)
                i_this = (iy % ny_this) * nx_this + (ix % nx_this) + 1

                axes2 = fig.add_subplot(ny_this, nx_this, i_this)

                space = 0.5
                space_factor = 1.0 + space
                axes2.set_axis_off()
                axes2.set_ylim(-1.05 * space_factor, 1.05)

                axes = axes2.twinx()
                axes.set_axis_off()

                axes.set_ylim(- absmax * 1.33 * space_factor, absmax * 1.33)

                itarget = target_index[target]
                result = target_to_result[target]

                dtrace = dtraces[itarget]

                tap_color_annot = (0.35, 0.35, 0.25)
                tap_color_edge = (0.85, 0.85, 0.80)
                tap_color_fill = (0.95, 0.95, 0.90)

                plot_taper(
                    axes2, result.processed_obs.get_xdata(), result.taper,
                    fc=tap_color_fill, ec=tap_color_edge)

                obs_color = scolor('aluminium5')
                obs_color_light = light(obs_color, 0.5)

                syn_color = scolor('scarletred2')
                syn_color_light = light(syn_color, 0.5)

                misfit_color = scolor('scarletred2')

                plot_dtrace(
                    axes2, dtrace, space, 0., 1.,
                    fc=light(misfit_color, 0.3),
                    ec=misfit_color)

                plot_trace(
                    axes, result.filtered_syn,
                    color=syn_color_light, lw=1.0)

                plot_trace(
                    axes, result.filtered_obs,
                    color=obs_color_light, lw=0.75)

                plot_trace(
                    axes, result.processed_syn,
                    color=syn_color, lw=1.0)

                plot_trace(
                    axes, result.processed_obs,
                    color=obs_color, lw=0.75)

                xdata = result.filtered_obs.get_xdata()
                axes.set_xlim(xdata[0], xdata[-1])

                tmarks = [
                    result.processed_obs.tmin,
                    result.processed_obs.tmax]

                for tmark in tmarks:
                    axes2.plot(
                        [tmark, tmark], [-0.9, 0.1], color=tap_color_annot)

                for tmark, text, ha, va in [
                        (tmarks[0],
                         '$\,$ ' + str_duration(tmarks[0] - source.time),
                         'right',
                         'bottom'),
                        (tmarks[1],
                         '$\Delta$ ' + str_duration(tmarks[1] - tmarks[0]),
                         'left',
                         'top')]:

                    axes2.annotate(
                        text,
                        xy=(tmark, -0.9),
                        xycoords='data',
                        xytext=(
                            fontsize * 0.4 * [-1, 1][ha == 'left'],
                            fontsize * 0.2),
                        textcoords='offset points',
                        ha=ha,
                        va=va,
                        color=tap_color_annot,
                        fontsize=fontsize)

#                rel_c = num.exp(gcms[itarget] - gcm_max)

#                sw = 0.25
#                sh = 0.1
#                ph = 0.01

#                for (ih, rw, facecolor, edgecolor) in [
#                        (1, rel_c,  light(misfit_color, 0.5), misfit_color)]:

#                    bar = patches.Rectangle(
#                        (1.0 - rw * sw, 1.0 - (ih + 1) * sh + ph),
#                        rw * sw,
#                        sh - 2 * ph,
#                        facecolor=facecolor, edgecolor=edgecolor,
#                        zorder=10,
#                        transform=axes.transAxes, clip_on=False)

#                    axes.add_patch(bar)

                scale_string = None

                infos = []
                if scale_string:
                    infos.append(scale_string)

                infos.append('.'.join(x for x in target.codes if x))
                dist = source.distance_to(target)
                azi = source.azibazi_to(target)[0]
                infos.append(str_dist(dist))
                infos.append(u'%.0f\u00B0' % azi)
                infos.append('%.3f' % gcms[itarget])
                axes2.annotate(
                    '\n'.join(infos),
                    xy=(0., 1.),
                    xycoords='axes fraction',
                    xytext=(2., 2.),
                    textcoords='offset points',
                    ha='left',
                    va='top',
                    fontsize=fontsize,
                    fontstyle='normal')

        for (iyy, ixx), fig in figures.iteritems():
            title = '.'.join(x for x in cg if x)
            if len(figures) > 1:
                title += ' (%i/%i, %i/%i)' % (iyy + 1, nyy, ixx + 1, nxx)

            fig.suptitle(title, fontsize=fontsize_title)

    return figs
Ejemplo n.º 12
0
def geodetic_fits(problem, stage, plot_options):
    """
    Plot geodetic data, synthetics and residuals.
    """
    scattersize = 16
    fontsize = 10
    fontsize_title = 12
    ndmax = 3
    nxmax = 3
    cmap = plt.cm.jet

    po = plot_options

    if po.reference is not None:
        problem.get_synthetics(po.reference)
        ref_sources = copy.deepcopy(problem.sources)

    target_index = dict(
        (target, i) for (i, target) in enumerate(problem.gtargets))

    population, _, llk = stage.step.select_end_points(stage.mtrace)

    posterior_idxs = get_fit_indexes(llk)
    idx = posterior_idxs[po.post_llk]

    out_point = population[idx]
    results = problem.assemble_geodetic_results(out_point)
    nrmax = len(results)

    target_to_result = {}
    for target, result in zip(problem.gtargets, results):
        target_to_result[target] = result

    nfigs = int(num.ceil(float(nrmax) / float(ndmax)))

    figures = []
    axes = []

    for f in range(nfigs):
        fig, ax = plt.subplots(
            nrows=ndmax, ncols=nxmax, figsize=mpl_papersize('a4', 'portrait'))
        fig.tight_layout()
        fig.subplots_adjust(
                        left=0.08,
                        right=1.0 - 0.03,
                        bottom=0.06,
                        top=1.0 - 0.06,
                        wspace=0.,
                        hspace=0.3)
        figures.append(fig)
        axes.append(ax)

    def axis_config(axes, po):
        axes[1].get_yaxis().set_ticklabels([])
        axes[2].get_yaxis().set_ticklabels([])
        axes[1].get_xaxis().set_ticklabels([])
        axes[2].get_xaxis().set_ticklabels([])

        if po.plot_projection == 'latlon':
            ystr = 'Latitude [deg]'
            xstr = 'Longitude [deg]'
        elif po.plot_projection == 'utm':
            ystr = 'UTM Northing [km]'
            xstr = 'UTM Easting [km]'
        elif po.plot_projection == 'local':
            ystr = 'Distance [km]'
            xstr = 'Distance [km]'
        else:
            raise Exception(
                'Plot projection %s not available' % po.plot_projection)

        axes[0].set_ylabel(ystr, fontsize=fontsize)
        axes[0].set_xlabel(xstr, fontsize=fontsize)

    def draw_sources(ax, sources, po, **kwargs):
        for source in sources:
            rf = source.patches(1, 1, 'seismic')[0]
            if po.plot_projection == 'latlon':
                outline = rf.outline(cs='lonlat')
            elif po.plot_projection == 'utm':
                outline = rf.outline(cs='lonlat')
                utme, utmn = utility.lonlat_to_utm(
                    lon=outline[:, 0], lat=outline[:, 1], zone=po.utm_zone)
                outline = num.vstack([utme / km, utmn / km]).T
            elif po.plot_projection == 'local':
                outline = rf.outline(cs='xy')
            ax.plot(outline[:, 0], outline[:, 1], '-', linewidth=1.0, **kwargs)
            ax.plot(
                outline[0:2, 0], outline[0:2, 1], '-k', linewidth=1.0)

    def cbtick(x):
        rx = math.floor(x * 1000.) / 1000.
        return [-rx, rx]

    def str_title(track):
        if track[0] == 'A':
            orbit = 'ascending'
        elif track[0] == 'D':
            orbit = 'descending'

        title = 'Orbit: ' + orbit
        return title

    orbits_to_targets = utility.gather(
        problem.gtargets,
        lambda t: t.track,
        filter=lambda t: t in target_to_result)

    ott = orbits_to_targets.keys()

    colims = [num.max([
        num.max(num.abs(r.processed_obs)),
        num.max(num.abs(r.processed_syn))]) for r in results]
    dcolims = [num.max(num.abs(r.processed_res)) for r in results]

    for o in ott:
        targets = orbits_to_targets[o]

        for target in targets:
            if po.plot_projection == 'local':
                target.update_local_coords(problem.event)

            result = target_to_result[target]
            tidx = target_index[target]

            figidx, rowidx = utility.mod_i(tidx, ndmax)

            plot_scene(
                axes[figidx][rowidx, 0],
                target,
                result.processed_obs,
                scattersize,
                colim=colims[tidx],
                outmode=po.plot_projection,
                cmap=cmap)

            syn = plot_scene(
                axes[figidx][rowidx, 1],
                target,
                result.processed_syn,
                scattersize,
                colim=colims[tidx],
                outmode=po.plot_projection,
                cmap=cmap)

            res = plot_scene(
                axes[figidx][rowidx, 2],
                target,
                result.processed_res,
                scattersize,
                colim=dcolims[tidx],
                outmode=po.plot_projection,
                cmap=cmap)

            titley = 0.91
            titlex = 0.16

            axes[figidx][rowidx, 0].annotate(
                o,
                xy=(titlex, titley),
                xycoords='axes fraction',
                xytext=(2., 2.),
                textcoords='offset points',
                weight='bold',
                fontsize=fontsize_title)

            syn_color = scolor('plum1')
            ref_color = scolor('aluminium3')

            draw_sources(
                axes[figidx][rowidx, 1], problem.sources, po, color=syn_color)

            if po.reference is not None:
                draw_sources(
                    axes[figidx][rowidx, 1],
                    ref_sources, po, color=ref_color)

            cbb = 0.68 - (0.3175 * rowidx)
            cbl = 0.46
            cbw = 0.15
            cbh = 0.01

            cbaxes = figures[figidx].add_axes([cbl, cbb, cbw, cbh])
            dcbaxes = figures[figidx].add_axes([cbl + 0.3, cbb, cbw, cbh])

            cblabel = 'LOS displacement [m]'
            cbs = plt.colorbar(syn,
                ax=axes[figidx][rowidx, 0],
                ticks=cbtick(colims[tidx]),
                cax=cbaxes,
                orientation='horizontal',
                cmap=cmap)
            cbs.set_label(cblabel, fontsize=fontsize)

            cbr = plt.colorbar(res,
                ax=axes[figidx][rowidx, 2],
                ticks=cbtick(dcolims[tidx]),
                cax=dcbaxes,
                orientation='horizontal',
                cmap=cmap)
            cbr.set_label(cblabel, fontsize=fontsize)

            axis_config(axes[figidx][rowidx, :], po)

            title = str_title(o) + ' Llk_' + po.post_llk
            figures[figidx].suptitle(
                title, fontsize=fontsize_title, weight='bold')

    nplots = ndmax * nfigs
    for delidx in range(nrmax, nplots):
        figidx, rowidx = utility.mod_i(delidx, ndmax)
        for colidx in range(nxmax):
            figures[figidx].delaxes(axes[figidx][rowidx, colidx])

    return figures
Ejemplo n.º 13
0
def correlation_plot_hist(mtrace, varnames=None,
        transform=lambda x: x, figsize=None, hist_color='orange', cmap=None,
        grid=200, point=None,
        point_style='.', point_color='red', point_size='8', alpha=0.35):
    """
    Plot 2d marginals (with kernel density estimation) showing the correlations
    of the model parameters. In the main diagonal is shown the parameter
    histograms.

    Parameters
    ----------
    mtrace : :class:`pymc3.base.MutliTrace`
        Mutlitrace instance containing the sampling results
    varnames : list of variable names
        Variables to be plotted, if None all variable are plotted
    transform : callable
        Function to transform data (defaults to identity)
    figsize : figure size tuple
        If None, size is (12, num of variables * 2) inch
    cmap : matplotlib colormap
    hist_color : str or tuple of 3
        color according to matplotlib convention
    grid : resolution of kernel density estimation
    point : dict
        Dictionary of variable name / value  to be overplotted as marker
        to the posteriors e.g. mean of posteriors, true values of a simulation
    point_style : str
        style of marker according to matplotlib conventions
    point_color : str or tuple of 3
        color according to matplotlib convention
    point_size : str
        marker size according to matplotlib conventions

    Returns
    -------
    fig : figure object
    axs : subplot axis handles
    """

    logger.info('Drawing correlation figure ...')

    if varnames is None:
        varnames = mtrace.varnames

    nvar = len(varnames)

    if figsize is None:
        figsize = mpl_papersize('a4', 'landscape')

    fig, axs = plt.subplots(nrows=nvar, ncols=nvar, figsize=figsize,
            subplot_kw={'adjustable': 'box-forced'})

    d = dict()

    for var in varnames:
        d[var] = transform(mtrace.get_values(
                var, combine=True, squeeze=True))

    for k in range(nvar):
        a = d[varnames[k]]

        for l in range(k, nvar):
            logger.debug('%s, %s' % (varnames[k], varnames[l]))
            if l == k:
                histplot_op(
                    axs[l, k], pmp.make_2d(a), alpha=alpha, color='orange')
                axs[l, k].set_xbound(a.min(), a.max())
                axs[l, k].get_yaxis().set_visible(False)

                if point is not None:
                    axs[l, k].axvline(
                        x=point[varnames[k]], color=point_color,
                        lw=int(point_size) / 4.)
            else:
                b = d[varnames[l]]

                pmp.kde2plot(
                    a, b, grid=grid, ax=axs[l, k], cmap=cmap, aspect='auto')

                if point is not None:
                    axs[l, k].plot(point[varnames[k]], point[varnames[l]],
                        color=point_color, marker=point_style,
                        markersize=point_size)

            if l != nvar - 1:
                axs[l, k].get_xaxis().set_ticklabels([])

            if k == 0:
                axs[l, k].set_ylabel(varnames[l])
            else:
                axs[l, k].get_yaxis().set_ticklabels([])

            axs[l, k].tick_params(direction='in')

        axs[l, k].set_xlabel(varnames[k])

    for k in range(nvar):
        for l in range(k):
            fig.delaxes(axs[l, k])

    fig.subplots_adjust(wspace=0.05, hspace=0.05)
    return fig, axs
Ejemplo n.º 14
0
def plot_waveforms(traces, event, stations, savedir, picks, show=True):
    fig = plt.figure(figsize=plot.mpl_papersize('a4', 'landscape'))
    tap_color_annot = (0.35, 0.35, 0.25)
    tap_color_edge = (0.85, 0.85, 0.80)
    waveform_color = scolor('aluminium5')
    misfit_color = scolor('scarletred1')
    ncomps = 3
    k = 0
    nstations = len(stations)
    ntraces = nstations * ncomps
    i = 0
    for st in stations:
        for comp in st.channels:
            for tr in traces:
                if tr.station == st.station:
                    if comp.name == tr.channel:
                        #    tr.downsample_to(0.05)
                        #    tr.highpass(4, 0.01)
                        #    tr.lowpass(4, 0.2)
                        dtrace = tr
                        i = i + 1
            target = st

            tmin_fit = dtrace.tmin
            tmax_fit = dtrace.tmax

            tfade_taper = 1. / 0.2

            taper = trace.CosTaper(tmin_fit - 20, tmin_fit, tmax_fit,
                                   tmax_fit + 30)
            k = k + 1
            axes2 = fig.add_subplot(nstations / 3, nstations / 3, k)
            space = 0.5
            space_factor = 1.0 + space
            axes2.set_axis_off()
            axes2.set_ylim(-1.05 * space_factor, 1.05)

            axes = axes2.twinx()
            axes.set_axis_off()

            bw_filter = trace.ButterworthResponse(corner=2,
                                                  order=4,
                                                  type='low')

            setup = trace.MisfitSetup(description='setup',
                                      norm=2,
                                      taper=taper,
                                      filter=bw_filter,
                                      domain='time_domain')

            abs_tr = dtrace.copy()
            abs_tr.set_ydata(abs(dtrace.get_ydata()))

            plot_cc(axes2,
                    abs_tr,
                    space,
                    0.,
                    num.max(abs_tr.get_ydata()),
                    fc=light(misfit_color, 0.3),
                    ec=misfit_color,
                    zorder=4)

            plot_trace(axes, dtrace, color=waveform_color, lw=0.5, zorder=5)

            tmarks = [dtrace.tmin, dtrace.tmax]

            for tmark in tmarks:
                axes2.plot([tmark, tmark], [-0.9, 0.1], color=tap_color_annot)

            for tmark, text, ha, va in [
                (tmarks[0], '$\,$ ' + str_duration(tmarks[0]), 'left',
                 'bottom'),
                (tmarks[1], '$\Delta$ ' + str_duration(tmarks[1] - tmarks[0]),
                 'right', 'bottom')
            ]:
                axes2.annotate(text,
                               xy=(tmark, -0.9),
                               xycoords='data',
                               xytext=(fontsize * 0.4 * [-1, 1][ha == 'left'],
                                       fontsize * 0.2),
                               textcoords='offset points',
                               ha=ha,
                               va=va,
                               color=tap_color_annot,
                               fontsize=fontsize,
                               zorder=10)

            if picks is not None:
                for stp in picks["phases"]:
                    phases_station = []
                    picks_station = []
                    if st.station == stp["station"]:
                        phases_station.append(str(stp["phase"]))
                        picks_station.append(event.time + float(stp["pick"]))
                        picks_station.append(event.time)

                    tmarks = picks_station

                    for tmark in tmarks:
                        axes2.plot([tmark, tmark], [-1, 1.], color="blue")

                    for tmark, text, ha, va in [(tmarks, phases_station,
                                                 'left', 'bottom')]:
                        try:
                            axes2.annotate(
                                text[0],
                                xy=(tmark[0], -1.2),
                                xycoords='data',
                                xytext=(8 * 0.4 * [-1, 1][ha == 'left'],
                                        8 * 0.2),
                                textcoords='offset points',
                                ha=ha,
                                va=va,
                                color=tap_color_annot,
                                fontsize=8,
                                zorder=10)
                        except:
                            pass
            infos = []

            infos.append(target.network + "." + target.station + "." +
                         dtrace.channel)
            dist = event.distance_to(target)
            azi = event.azibazi_to(target)[0]
            infos.append(str_dist(dist))
            infos.append(u'%.0f\u00B0' % azi)

            axes2.annotate('\n'.join(infos),
                           xy=(0., 1.),
                           xycoords='axes fraction',
                           xytext=(2., 2.),
                           textcoords='offset points',
                           ha='left',
                           va='top',
                           fontsize=fontsize,
                           fontstyle='normal')
            if i / nstations == 1 or i / nstations == 2 or i / nstations == 3:
                fig.savefig(savedir +
                            "waveforms_%s.png" % str(int(i / nstations)),
                            dpi=100)

                if show is True:
                    plt.show()
                else:
                    plt.close()
                fig = plt.figure(figsize=plot.mpl_papersize('a4', 'landscape'))
                k = 0
Ejemplo n.º 15
0
def plot_polarizations(stations,
                       trs,
                       event=None,
                       size_factor=0.05,
                       fontsize=10.,
                       output_filename=None,
                       output_format=None,
                       output_dpi=None):

    if event is None:
        slats = num.array([s.lat for s in stations], dtype=num.float)
        slons = num.array([s.lon for s in stations], dtype=num.float)
        clat, clon = od.geographic_midpoint(slats, slons)
        event = od.Loc(clat, clon)

    nsl_c_to_trs = defaultdict(dict)
    for tr in trs:
        nsl_c_to_trs[tr.nslc_id[:3]][tr.nslc_id[3]] = tr

    nsl_to_station = dict((s.nsl(), s) for s in stations)

    plot.mpl_init(fontsize=fontsize)
    fig = plt.figure(figsize=plot.mpl_papersize('a4', 'landscape'))
    plot.mpl_margins(fig, w=7., h=6., units=fontsize)

    grid = ImageGrid(fig,
                     111,
                     nrows_ncols=(2, 2),
                     axes_pad=0.5,
                     add_all=True,
                     label_mode='L',
                     aspect=True)

    axes_en = grid[0]
    axes_en.set_ylabel('Northing [km]')

    axes_dn = grid[1]
    axes_dn.locator_params(axis='x', nbins=4)
    axes_dn.set_xlabel('Depth [km]')

    axes_ed = grid[2]
    axes_ed.locator_params(axis='y', nbins=4)
    axes_ed.set_ylabel('Depth [km]')
    axes_ed.set_xlabel('Easting [km]')

    if isinstance(event, model.Event):
        axes_en.plot(0., 0., '*')
        axes_dn.plot(event.depth / km, 0., '*')
        axes_ed.plot(0., event.depth / km, '*')

    grid[3].set_axis_off()

    locations = []
    for nsl in sorted(nsl_c_to_trs.keys()):
        station = nsl_to_station[nsl]
        n, e = od.latlon_to_ne(event.lat, event.lon, station.lat, station.lon)

        locations.append((n, e))

    ns, es = num.array(locations, dtype=num.float).T

    n_min = num.min(ns)
    n_max = num.max(ns)
    e_min = num.min(es)
    e_max = num.max(es)

    factor = max((n_max - n_min) * size_factor, (e_max - e_min) * size_factor)

    fontsize_annot = fontsize * 0.7

    data = {}
    for insl, nsl in enumerate(sorted(nsl_c_to_trs.keys())):

        color = plot.mpl_graph_color(insl)

        try:
            tr_e = nsl_c_to_trs[nsl]['E']
            tr_n = nsl_c_to_trs[nsl]['N']
            tr_z = nsl_c_to_trs[nsl]['Z']

        except KeyError:
            continue

        station = nsl_to_station[nsl]

        n, e = od.latlon_to_ne(event.lat, event.lon, station.lat, station.lon)

        d = station.depth

        axes_en.annotate('.'.join(x for x in nsl if x),
                         xy=(e / km, n / km),
                         xycoords='data',
                         xytext=(fontsize_annot / 3., fontsize_annot / 3.),
                         textcoords='offset points',
                         verticalalignment='bottom',
                         horizontalalignment='left',
                         rotation=0.,
                         size=fontsize_annot)

        axes_en.plot(e / km, n / km, '^', mfc=color, mec=darken(color))
        axes_dn.plot(d / km, n / km, '^', mfc=color, mec=darken(color))
        axes_ed.plot(e / km, d / km, '^', mfc=color, mec=darken(color))

        arr_e = tr_e.ydata
        arr_n = tr_n.ydata
        arr_z = tr_z.ydata
        arr_t = tr_z.get_xdata()

        data[nsl] = (arr_e, arr_n, arr_z, arr_t, n, e, d, color)

    amaxs = []
    amax_hors = []
    for nsl in sorted(data.keys()):
        arr_e, arr_n, arr_z, arr_t, n, e, d, color = data[nsl]
        amaxs.append(num.max(num.abs(num.sqrt(arr_e**2 + arr_n**2 +
                                              arr_z**2))))
        amax_hors.append(num.max(num.abs(num.sqrt(arr_e**2 + arr_n**2))))

    amax = num.median(amaxs)
    amax_hor = num.median(amax_hors)

    for nsl in sorted(data.keys()):
        arr_e, arr_n, arr_z, arr_t, n, e, d, color = data[nsl]
        tmin = arr_t.min()
        tmax = arr_t.max()
        plot_color_line(axes_en, (e + arr_e / amax_hor * factor) / km,
                        (n + arr_n / amax_hor * factor) / km, arr_t, color,
                        tmin, tmax)
        plot_color_line(axes_dn, (d - arr_z / amax * factor) / km,
                        (n + arr_n / amax * factor) / km, arr_t, color, tmin,
                        tmax)
        plot_color_line(axes_ed, (e + arr_e / amax * factor) / km,
                        (d - arr_z / amax * factor) / km, arr_t, color, tmin,
                        tmax)

    axes_ed.invert_yaxis()

    for axes in (axes_dn, axes_ed, axes_en):
        axes.autoscale_view(tight=True)

    if output_filename is None:
        plt.show()
    else:
        fig.savefig(output_filename, format=output_format, dpi=output_dpi)
from matplotlib import pyplot as plt

from pyrocko.plot import mpl_init, mpl_margins, mpl_papersize
# from pyrocko.plot import mpl_labelspace

fontsize = 9.   # in points

# set some Pyrocko style defaults
mpl_init(fontsize=fontsize)

fig = plt.figure(figsize=mpl_papersize('a4', 'landscape'))

# let margins be proportional to selected font size, e.g. top and bottom
# margin are set to be 5*fontsize = 45 [points]
labelpos = mpl_margins(fig, w=7., h=5., units=fontsize)

axes = fig.add_subplot(1, 1, 1)

# positioning of axis labels
# mpl_labelspace(axes)    # either: relative to axis tick labels
labelpos(axes, 2., 1.5)   # or: relative to left/bottom paper edge

axes.plot([0, 1], [0, 9])

axes.set_xlabel('Time [s]')
axes.set_ylabel('Amplitude [m]')

fig.savefig('plot_skeleton.pdf')

plt.show()
Ejemplo n.º 17
0
from matplotlib import pyplot as plt

from pyrocko.plot import mpl_init, mpl_margins, mpl_papersize
# from pyrocko.plot import mpl_labelspace

fontsize = 9.  # in points

# set some Pyrocko style defaults
mpl_init(fontsize=fontsize)

fig = plt.figure(figsize=mpl_papersize('a4', 'landscape'))

# let margins be proportional to selected font size, e.g. top and bottom
# margin are set to be 5*fontsize = 45 [points]
labelpos = mpl_margins(fig, w=7., h=5., units=fontsize)

axes = fig.add_subplot(1, 1, 1)

# positioning of axis labels
# mpl_labelspace(axes)    # either: relative to axis tick labels
labelpos(axes, 2., 1.5)  # or: relative to left/bottom paper edge

axes.plot([0, 1], [0, 9])

axes.set_xlabel('Time [s]')
axes.set_ylabel('Amplitude [m]')

fig.savefig('plot_skeleton.pdf')

plt.show()
Ejemplo n.º 18
0
def plot(responses,
         filename=None,
         dpi=100,
         fmin=0.01,
         fmax=100.,
         nf=100,
         fontsize=10.,
         figsize=None,
         styles=None,
         labels=None):
    '''
    Draw instrument responses in Bode plot style.

    :param responses: instrument responses as
        :py:class:`pyrocko.trace.FrequencyResponse` objects
    :param fmin: minimum frequency [Hz]
    :param fmax: maximum frequency [Hz]
    :param nf: number of frequencies where to evaluate the response
    :param styles: :py:class:`list` of :py:class:`dict` objects  with keyword
        arguments to be passed to matplotlib's
        :py:meth:`matplotlib.axes.Axes.plot` function when drawing the response
        lines. Length must match number of responses.
    :param filename: file name to pass to matplotlib's ``savefig`` function. If
        ``None``, the plot is shown with :py:func:`matplotlib.pyplot.show`.
    :param fontsize: font size in points used in axis labels and legend
    :param figsize: :py:class:`tuple`, ``(width, height)`` in inches
    :param labels: :py:class:`list` of names to show in legend. Length must
        correspond to number of responses.
    '''

    from matplotlib import pyplot as plt
    from pyrocko.plot import mpl_init, mpl_margins, mpl_papersize
    from pyrocko.plot import graph_colors, to01

    mpl_init(fontsize=fontsize)

    if figsize is None:
        figsize = mpl_papersize('a4', 'portrait')

    fig = plt.figure(figsize=figsize)
    labelpos = mpl_margins(fig,
                           w=7.,
                           h=5.,
                           units=fontsize,
                           nw=1,
                           nh=2,
                           hspace=2.)
    axes_amplitude = fig.add_subplot(2, 1, 1)
    labelpos(axes_amplitude, 2., 1.5)
    axes_phase = fig.add_subplot(2, 1, 2)
    labelpos(axes_phase, 2., 1.5)

    setup_axes(axes_amplitude, axes_phase)

    if styles is None:
        styles = [
            dict(color=to01(graph_colors[i % len(graph_colors)]))
            for i in xrange(len(responses))
        ]
    else:
        assert len(styles) == len(responses)

    if labels is None:
        labels = [None] * len(responses)
    else:
        assert len(labels) == len(responses)

    a_ranges, p_ranges = [], []
    for style, resp, label in zip(styles, responses, labels):
        a_range, p_range = draw(response=resp,
                                axes_amplitude=axes_amplitude,
                                axes_phase=axes_phase,
                                fmin=fmin,
                                fmax=fmax,
                                nf=nf,
                                style=style,
                                label=label)

        a_ranges.append(a_range)
        p_ranges.append(p_range)

    axes_amplitude.legend(loc='lower right', prop=dict(size=fontsize))

    a_ranges = num.array(a_ranges)
    p_ranges = num.array(p_ranges)

    amin, amax = num.min(a_ranges), num.max(a_ranges)
    pmin, pmax = num.min(p_ranges), num.max(p_ranges)

    amin *= 0.5
    amax *= 2.0

    pmin -= 0.5
    pmax += 0.5

    axes_amplitude.set_ylim(amin, amax)
    axes_phase.set_ylim(pmin, pmax)
    axes_amplitude.set_xlim(fmin, fmax)
    axes_phase.set_xlim(fmin, fmax)

    if filename is not None:
        fig.savefig(filename, dpi=dpi)
    else:
        plt.show()
Ejemplo n.º 19
0
def plot_shakemap(sources,
                  norths,
                  easts,
                  values_list,
                  filename,
                  folder,
                  stations,
                  values_stations_list=None,
                  easts_stations=None,
                  norths_stations=None,
                  latlon=True,
                  show=False,
                  plot_background_map=True,
                  measured=None,
                  value_level=0.001,
                  quantity="velocity",
                  scale="mm",
                  plot_values=False,
                  vs30=True,
                  engine=None,
                  type_factors=None,
                  store_id=None,
                  plot_snr=False):
    plot.mpl_init()
    fig = plt.figure(figsize=plot.mpl_papersize('a5', 'landscape'))
    axes = fig.add_subplot(1, 1, 1, aspect=1.0)
    mts = []
    plot_kwargs = {'size': 4000, 'edgecolor': 'black'}

    for i, source in enumerate(sources):
        mts.append(source.pyrocko_moment_tensor())
        if i == 0:
            best_mt = source.pyrocko_moment_tensor()
    for i, values_pertubed in enumerate(values_list):
        if i == 0:
            values = values_pertubed
            values_cum = num.zeros(num.shape(values))
            values_cum = values_cum + values
        else:
            values_cum = values_cum + values_pertubed
    vales_cum = values_cum / float(len(values_list))
    if scale == "mm":
        values = values * 1000.
    if values_stations_list is not None:
        values_stations = values_stations_list[0]
        if scale == "mm":
            values_stations = values_stations * 1000.

    if latlon is False:
        axes.set_xlim(easts.min() / km, easts.max() / km)
        axes.set_ylim(norths.min() / km, norths.max() / km)

        axes.set_xlabel('Easting [km]')
        axes.set_ylabel('Northing [km]')

        im = axes.contourf(easts / km,
                           norths / km,
                           values,
                           vmin=0.,
                           vmax=vmax,
                           cmap=plt.get_cmap('YlOrBr'))

        if quantity == "velocity":
            if scale == "mm":
                fig.colorbar(im, label='Velocity [mm/s]')
            else:
                fig.colorbar(im, label='Velocity [m/s]')
        if quantity == "acceleration":
            if scale == "mm":
                fig.colorbar(im, label='Velocity [mm/s]')
            else:
                fig.colorbar(im, label='Velocity [m/s]')

        if source.base_key()[6] is not "ExplosionSource":
            beachball.plot_fuzzy_beachball_mpl_pixmap(mts,
                                                      axes,
                                                      best_mt,
                                                      position=(0, 0.),
                                                      color_t='black',
                                                      **plot_kwargs)
        if values_stations is not None:
            plt.scatter(easts_stations / km,
                        norths_stations / km,
                        c=values_stations,
                        s=36,
                        cmap=plt.get_cmap('YlOrBr'),
                        vmin=0.,
                        vmax=vmax,
                        edgecolor="k")
    else:
        lats = []
        lons = []
        for east, north in zip(easts, norths):
            lat, lon = orthodrome.ne_to_latlon(source.lat, source.lon, north,
                                               east)
            lats.append(lat)
            lons.append(lon)

        if vs30 is True:
            from silvertine.shakemap import vs30
            values_vs30 = vs30.extract_rectangle(num.min(lons), num.max(lons),
                                                 num.min(lats), num.max(lats))
            from scipy import ndimage
            factor_x = num.shape(values)[0] / num.shape(values_vs30)[0]
            factor_y = num.shape(values)[1] / num.shape(values_vs30)[1]
            values_vs30_resam = ndimage.zoom(values_vs30, (factor_x, factor_y))

            store = engine.get_store(store_id)
            if type_factors is None:
                layer0 = store.config.earthmodel_1d.layer(0)
                base_velocity = layer0.mtop.vs
                base_velocity = 400.
                type_factors = 1
                amp_factor = (base_velocity / values_vs30_resam)**type_factors
                values = values * amp_factor
                values = values / 15.87
                #values = values/10.

        if plot_background_map is True:
            map = Basemap(projection='merc',
                          llcrnrlon=num.min(lons),
                          llcrnrlat=num.min(lats),
                          urcrnrlon=num.max(lons),
                          urcrnrlat=num.max(lats),
                          resolution='h',
                          epsg=3395)
            ratio_lat = num.max(lats) / num.min(lats)
            ratio_lon = num.max(lons) / num.min(lons)

            map.drawmapscale(
                num.min(lons) + 0.05,
                num.min(lats) + 0.05, num.min(lons), num.min(lats), 10)
            parallels = num.arange(num.around(num.min(lats), decimals=2),
                                   num.around(num.max(lats), decimals=2), 0.1)
            meridians = num.arange(num.around(num.min(lons), decimals=2),
                                   num.around(num.max(lons), decimals=2), 0.2)
            map.drawparallels(parallels, labels=[1, 0, 0, 0], fontsize=22)
            map.drawmeridians(meridians, labels=[1, 1, 0, 1], fontsize=22)
            xpixels = 1000
            try:
                map.arcgisimage(service='World_Shaded_Relief',
                                xpixels=xpixels,
                                verbose=False,
                                zorder=1,
                                cmap="gray")
            except urllib.error.URLError:
                pass
    #    axes.set_xlim(lats.min()/km, lats.max()/km)
    #    axes.set_ylim(norths.min()/km, norths.max()/km)
        if plot_background_map is True:
            pos1, pos2 = map(source.lon, source.lat)
        else:
            pos1 = source.lat
            pos2 = source.lon
        if source.base_key()[6] is not "ExplosionSource":
            beachball.plot_fuzzy_beachball_mpl_pixmap(mts,
                                                      axes,
                                                      best_mt,
                                                      position=(pos1, pos2),
                                                      color_t='black',
                                                      zorder=2,
                                                      **plot_kwargs)

        if plot_background_map is True:
            lats_map, lons_map = map(lons, lats)
            values[values == 0] = 'nan'
            alpha = 0.5
        else:
            lats_map, lons_map = lats, lons
            alpha = 1.
        _, vmax = num.min(values), num.max(values)

        if values_stations_list is not None:
            st_lats, st_lons = [], []
            for st in stations:
                st_lats.append(st.lat)
                st_lons.append(st.lon)
            if plot_background_map is True:
                st_lats, st_lons = map(st_lons, st_lats)
            if plot_values is True and measured is not None:
                measured_values = []
            try:
                for k, st in enumerate(stations):
                    for data in measured:
                        if data[0].decode() == st.station:
                            if scale == "mm":
                                measured_values.append(data[1] * 1000.)
                _, vmax = num.min(measured_values), num.max(measured_values)

            except:
                measured_values = []
                if measured is not None:
                    for data in measured:
                        if scale == "mm":
                            #    measured_values.append(data*1000.*100)
                            measured_values.append(data * 1000.)

                    _, vmax = num.min(measured_values), num.max(
                        measured_values)

            if plot_values is True and measured is None:
                plt.scatter(st_lats,
                            st_lons,
                            c=num.asarray(values_stations),
                            s=36,
                            cmap=plt.get_cmap('YlOrBr'),
                            vmin=0.,
                            vmax=vmax,
                            edgecolor="k",
                            alpha=alpha)
                for k, st in enumerate(stations):
                    plt.text(st_lats[k], st_lons[k], str(st.station))
            if plot_values is True and measured is not None:
                plt.scatter(st_lats,
                            st_lons,
                            c=num.asarray(measured_values),
                            s=36,
                            cmap=plt.get_cmap('YlOrBr'),
                            vmin=0.,
                            vmax=vmax,
                            edgecolor="k",
                            alpha=alpha)
                for k, st in enumerate(stations):
                    plt.text(st_lats[k], st_lons[k], str(st.station))
            if measured is not None and plot_values is False:
                residuals = []
                stations_write = []
                try:
                    for k, st in enumerate(stations):
                        for data in measured:
                            # case for manual input
                            if data[0].decode() == st.station:
                                residuals.append(values_stations[k] - data[1])
                                stations_write.append(st.station)
                except:
                    if measured is not None:
                        for data in measured:
                            # case for measured input
                            residuals.append(values_stations[k] - data)
                            stations_write.append(st.station)
                fobj = open(os.path.join(folder, 'residuals.txt'), 'w')
                for i in range(0, len(residuals)):
                    fobj.write('%s %.20f\n' %
                               (stations_write[i], residuals[i]))
                fobj.close()

                fobj = open(os.path.join(folder, 'synthetic_pga.txt'), 'w')
                for i in range(0, len(residuals)):
                    fobj.write('%s %.20f\n' %
                               (stations_write[i], values_stations[i]))
                fobj.close()

                plt.scatter(st_lats,
                            st_lons,
                            c=residuals,
                            s=36,
                            cmap=plt.get_cmap('YlOrBr'),
                            vmin=0.,
                            vmax=vmax,
                            edgecolor="k",
                            alpha=alpha)
        #values = values*77.66
        im = axes.contourf(lats_map,
                           lons_map,
                           values.T,
                           vmin=0.,
                           vmax=vmax,
                           cmap=plt.get_cmap('YlOrBr'),
                           alpha=alpha)
        if quantity == "velocity":
            if scale == "mm":
                #fig.colorbar(im, label='Velocity [mm/s]')
                m = plt.cm.ScalarMappable(cmap=plt.get_cmap('YlOrBr'))
                m.set_array(values)
                m.set_clim(0., vmax)
                plt.colorbar(m, boundaries=num.linspace(0, vmax, 6))
            else:
                fig.colorbar(im, label='Velocity [m/s]')
        if quantity == "acceleration":
            if scale == "mm":
                fig.colorbar(im, label='Velocity [mm/s]')
            else:
                fig.colorbar(im, label='Velocity [m/s]')

        axes.contour(lats_map,
                     lons_map,
                     vales_cum.T,
                     cmap='brg',
                     levels=[value_level])

    fig.savefig(folder + filename)
    if show is True:
        plt.show()
    else:
        plt.close()
    if vs30 is not False:
        fig = plt.figure(figsize=plot.mpl_papersize('a5', 'landscape'))
        axes = fig.add_subplot(1, 1, 1, aspect=1.0)

        map = Basemap(projection='merc',
                      llcrnrlon=num.min(lons),
                      llcrnrlat=num.min(lats),
                      urcrnrlon=num.max(lons),
                      urcrnrlat=num.max(lats),
                      resolution='h',
                      epsg=3395)
        ratio_lat = num.max(lats) / num.min(lats)
        ratio_lon = num.max(lons) / num.min(lons)

        parallels = num.arange(num.around(num.min(lats), decimals=2),
                               num.around(num.max(lats), decimals=2), 0.1)
        meridians = num.arange(num.around(num.min(lons), decimals=2),
                               num.around(num.max(lons), decimals=2), 0.2)
        map.drawparallels(parallels, labels=[1, 0, 0, 0], fontsize=22)
        map.drawmeridians(meridians, labels=[1, 1, 0, 1], fontsize=22)
        im = map.imshow(num.rot90(values_vs30.T))
        fig.colorbar(im, label='Velocity [m/s]')
        fig.savefig(folder + "vs30.png")