Ejemplo n.º 1
0
    def draw_figures(self, history, optimiser):

        color_parameter = self.color_parameter
        exclude = self.exclude
        include = self.include
        nsubplots = self.nsubplots
        figsize = self.size_inch
        ibootstrap = 0 if self.ibootstrap is None else self.ibootstrap
        misfit_cutoff = self.misfit_cutoff
        show_ellipses = self.show_ellipses
        msize = 1.5
        cmap = 'coolwarm'

        problem = history.problem
        if not problem:
            return []

        models = history.models

        exclude = list(exclude)
        bounds = problem.get_combined_bounds()
        for ipar in range(problem.ncombined):
            par = problem.combined[ipar]
            lo, hi = bounds[ipar]
            if lo == hi:
                exclude.append(par.name)

        xref = problem.get_reference_model()

        isort = history.get_sorted_misfits_idx(chain=ibootstrap)[::-1]
        models = history.get_sorted_models(chain=ibootstrap)[::-1]
        nmodels = history.nmodels

        gms = history.get_sorted_misfits(chain=ibootstrap)[::-1]
        if misfit_cutoff is not None:
            ibest = gms < misfit_cutoff
            gms = gms[ibest]
            models = models[ibest]

        kwargs = {}

        if color_parameter == 'dist':
            mx = num.mean(models, axis=0)
            cov = num.cov(models.T)
            mdists = core.mahalanobis_distance(models, mx, cov)
            icolor = meta.ordersort(mdists)

        elif color_parameter == 'misfit':
            iorder = num.arange(nmodels)
            icolor = iorder

        elif color_parameter in problem.parameter_names:
            ind = problem.name_to_index(color_parameter)
            icolor = problem.extract(models, ind)

        elif color_parameter in history.attribute_names:
            icolor = history.get_attribute(color_parameter)[isort]
            icolor_need = num.unique(icolor)

            colors = []
            for i in range(icolor_need[-1]+1):
                colors.append(mpl_graph_color(i))

            cmap = mcolors.ListedColormap(colors)
            cmap.set_under(mpl_color('aluminium3'))
            kwargs.update(dict(vmin=0, vmax=icolor_need[-1]))
        else:
            raise meta.GrondError(
                'Invalid color_parameter: %s' % color_parameter)

        smap = {}
        iselected = 0
        for ipar in range(problem.ncombined):
            par = problem.combined[ipar]
            if exclude and par.name in exclude or \
                    include and par.name not in include:
                continue

            smap[iselected] = ipar
            iselected += 1

        nselected = iselected

        if nselected < 2:
            logger.warn('Cannot draw joinpar figures with less than two '
                        'parameters selected.')
            return []

        nfig = (nselected - 2) // nsubplots + 1

        figs = []
        for ifig in range(nfig):
            figs_row = []
            for jfig in range(nfig):
                if ifig >= jfig:
                    item = PlotItem(name='fig_%i_%i' % (ifig, jfig))
                    item.attributes['parameters'] = []
                    figs_row.append((item, plt.figure(figsize=figsize)))
                else:
                    figs_row.append(None)

            figs.append(figs_row)

        for iselected in range(nselected):
            ipar = smap[iselected]
            ypar = problem.combined[ipar]
            for jselected in range(iselected):
                jpar = smap[jselected]
                xpar = problem.combined[jpar]

                ixg = (iselected - 1)
                iyg = jselected

                ix = ixg % nsubplots
                iy = iyg % nsubplots

                ifig = ixg // nsubplots
                jfig = iyg // nsubplots

                aind = (nsubplots, nsubplots, (ix * nsubplots) + iy + 1)

                item, fig = figs[ifig][jfig]

                tlist = item.attributes['parameters']
                if xpar.name not in tlist:
                    tlist.append(xpar.name)
                if ypar.name not in tlist:
                    tlist.append(ypar.name)

                axes = fig.add_subplot(*aind)

                axes.axvline(0., color=mpl_color('aluminium3'), lw=0.5)
                axes.axhline(0., color=mpl_color('aluminium3'), lw=0.5)
                for spine in axes.spines.values():
                    spine.set_edgecolor(mpl_color('aluminium5'))
                    spine.set_linewidth(0.5)

                xmin, xmax = fixlim(*xpar.scaled(bounds[jpar]))
                ymin, ymax = fixlim(*ypar.scaled(bounds[ipar]))

                if ix == 0 or jselected + 1 == iselected:
                    for (xpos, xoff, x) in [
                            (0.0, 10., xmin),
                            (1.0, -10., xmax)]:

                        axes.annotate(
                            '%.3g%s' % (x, xpar.get_unit_suffix()),
                            xy=(xpos, 1.05),
                            xycoords='axes fraction',
                            xytext=(xoff, 5.),
                            textcoords='offset points',
                            verticalalignment='bottom',
                            horizontalalignment='left',
                            rotation=45.)

                if iy == nsubplots - 1 or jselected + 1 == iselected:
                    for (ypos, yoff, y) in [
                            (0., 10., ymin),
                            (1.0, -10., ymax)]:

                        axes.annotate(
                            '%.3g%s' % (y, ypar.get_unit_suffix()),
                            xy=(1.0, ypos),
                            xycoords='axes fraction',
                            xytext=(5., yoff),
                            textcoords='offset points',
                            verticalalignment='bottom',
                            horizontalalignment='left',
                            rotation=45.)

                axes.set_xlim(xmin, xmax)
                axes.set_ylim(ymin, ymax)

                if not self.show_ticks:
                    axes.get_xaxis().set_ticks([])
                    axes.get_yaxis().set_ticks([])
                else:
                    axes.tick_params(length=4, which='both')
                    axes.get_yaxis().set_ticklabels([])
                    axes.get_xaxis().set_ticklabels([])

                if iselected == nselected - 1 or ix == nsubplots - 1:
                    axes.annotate(
                        xpar.get_label(with_unit=False),
                        xy=(0.5, -0.05),
                        xycoords='axes fraction',
                        verticalalignment='top',
                        horizontalalignment='right',
                        rotation=45.)

                if iy == 0:
                    axes.annotate(
                        ypar.get_label(with_unit=False),
                        xy=(-0.05, 0.5),
                        xycoords='axes fraction',
                        verticalalignment='top',
                        horizontalalignment='right',
                        rotation=45.)

                fx = problem.extract(models, jpar)
                fy = problem.extract(models, ipar)

                axes.scatter(
                    xpar.scaled(fx),
                    ypar.scaled(fy),
                    c=icolor,
                    s=msize, alpha=0.5, cmap=cmap, edgecolors='none', **kwargs)

                if show_ellipses:
                    cov = num.cov((xpar.scaled(fx), ypar.scaled(fy)))
                    evals, evecs = eigh_sorted(cov)
                    evals = num.sqrt(evals)
                    ell = patches.Ellipse(
                        xy=(
                            num.mean(xpar.scaled(fx)),
                            num.mean(ypar.scaled(fy))),
                        width=evals[0] * 2,
                        height=evals[1] * 2,
                        angle=num.rad2deg(
                            num.arctan2(evecs[1][0], evecs[0][0])))

                    ell.set_facecolor('none')
                    axes.add_artist(ell)

                if self.show_reference:
                    fx = problem.extract(xref, jpar)
                    fy = problem.extract(xref, ipar)

                    ref_color = mpl_color('aluminium6')
                    ref_color_light = 'none'
                    axes.plot(
                        xpar.scaled(fx), ypar.scaled(fy), 's',
                        mew=1.5, ms=5, mfc=ref_color_light, mec=ref_color)

        figs_flat = []
        for figs_row in figs:
            figs_flat.extend(
                item_fig for item_fig in figs_row if item_fig is not None)

        return figs_flat
Ejemplo n.º 2
0
    def draw_figure(self, sources, target, results):
        t0_mean = num.mean([s.time for s in sources])

        # distances = [
        #    s.distance_to(target) for s in sources]

        # distance_min = num.min(distances)
        # distance_max = num.max(distances)

        yabsmaxs = []

        for result in results:
            if isinstance(result, WaveformMisfitResult):
                yabsmaxs.append(
                    num.max(num.abs(
                        result.filtered_obs.get_ydata())))

        if yabsmaxs:
            yabsmax = max(yabsmaxs) or 1.0
        else:
            yabsmax = None

        fontsize = self.font_size

        fig = plt.figure(figsize=self.size_inch)

        labelpos = plot.mpl_margins(
            fig, nw=1, nh=1, w=1., h=5.,
            units=fontsize)

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

        labelpos(axes, 2.5, 2.0)
        axes.set_frame_on(False)
        axes.set_ylim(1., 4.)
        axes.get_yaxis().set_visible(False)
        axes.set_title('%s' % target.string_id())
        axes.set_xlabel('Time [s]')
        ii = 0

        for source, result in zip(sources, results):
            if not isinstance(result, WaveformMisfitResult):
                continue

            if result.tobs_shift != 0.0:
                t0 = result.tsyn_pick
            else:
                t0 = t0_mean

            t = result.filtered_obs.get_xdata()
            ydata = result.filtered_obs.get_ydata() / yabsmax
            axes.plot(
                t-t0, ydata*0.40 + 3.5, color='black', lw=1.0)

            color = plot.mpl_graph_color(ii)

            t = result.filtered_syn.get_xdata()
            ydata = result.filtered_syn.get_ydata()
            ydata = ydata / (num.max(num.abs(ydata)) or 1.0)

            axes.plot(t-t0, ydata*0.47 + 2.5, color=color, alpha=0.5, lw=1.0)

            t = result.processed_syn.get_xdata()
            ydata = result.processed_syn.get_ydata()
            ydata = ydata / (num.max(num.abs(ydata)) or 1.0)

            axes.plot(t-t0, ydata*0.47 + 1.5, color=color, alpha=0.5, lw=1.0)
            if result.tobs_shift != 0.0:
                axes.axvline(
                    result.tsyn_pick - t0,
                    color=(0.7, 0.7, 0.7),
                    zorder=2)

            t = result.processed_syn.get_xdata()
            taper = result.taper

            y = num.ones(t.size) * 0.9
            taper(y, t[0], t[1] - t[0])
            y2 = num.concatenate((y, -y[::-1]))
            t2 = num.concatenate((t, t[::-1]))
            axes.plot(t2-t0, y2 * 0.47 + 3.5, color=color, alpha=0.2, lw=1.0)
            ii += 1

        return fig
Ejemplo n.º 3
0
    def test_point_in_polygon(self):
        if plot:
            from pyrocko.plot import mpl_graph_color

            import matplotlib.pyplot as plt
            from matplotlib.patches import Polygon

            axes = plt.gca()

        nip = 100

        for i in range(1):
            np = 3
            points = num.zeros((np, 2))
            points[:, 0] = random_lat(size=3)
            points[:, 1] = random_lon(size=3)

            points_ip = num.zeros((nip*points.shape[0], 2))
            for ip in range(points.shape[0]):
                n, e = orthodrome.latlon_to_ne_numpy(
                    points[ip % np, 0], points[ip % np, 1],
                    points[(ip+1) % np, 0], points[(ip+1) % np, 1])

                ns = num.arange(nip) * n / nip
                es = num.arange(nip) * e / nip
                lats, lons = orthodrome.ne_to_latlon(
                    points[ip % np, 0], points[ip % np, 1], ns, es)

                points_ip[ip*nip:(ip+1)*nip, 0] = lats
                points_ip[ip*nip:(ip+1)*nip, 1] = lons

            if plot:
                color = mpl_graph_color(i)
                axes.add_patch(
                    Polygon(
                        num.fliplr(points_ip),
                        facecolor=light(color),
                        edgecolor=color,
                        alpha=0.5))

            points_xyz = orthodrome.latlon_to_xyz(points_ip.T)
            center_xyz = num.mean(points_xyz, axis=0)

            assert num.all(
                orthodrome.distances3d(
                    points_xyz, center_xyz[num.newaxis, :]) < 1.0)

            lat, lon = orthodrome.xyz_to_latlon(center_xyz)
            rot = orthodrome.rot_to_00(lat, lon)

            points_rot_xyz = num.dot(rot, points_xyz.T).T
            points_rot_pro = orthodrome.stereographic(points_rot_xyz)  # noqa

            poly_xyz = orthodrome.latlon_to_xyz(points_ip)
            poly_rot_xyz = num.dot(rot, poly_xyz.T).T
            groups = orthodrome.spoly_cut([poly_rot_xyz], axis=0)
            num.zeros(points.shape[0], dtype=num.int)

            if plot:
                for group in groups:
                    for poly_rot_group_xyz in group:

                        axes.set_xlim(-180., 180.)
                        axes.set_ylim(-90., 90.)

                    plt.show()
Ejemplo n.º 4
0
def cluster_color(icluster):
    if icluster == -1:
        return mpl_color('aluminium3')
    else:
        return mpl_graph_color(icluster)
Ejemplo n.º 5
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)
Ejemplo n.º 6
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.º 7
0
    def draw_figures(self, dataset, history, optimiser):

        fontsize = self.font_size

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

        problem = history.problem
        if not problem:
            logger.warn('Problem not set.')
            return []

        models = history.models

        if models.size == 0:
            logger.warn('Empty models vector.')
            return []

        for target in problem.targets:
            target.set_dataset(dataset)

        imodels = num.arange(history.nmodels)

        gms = history.get_sorted_primary_misfits()[::-1]
        isort = history.get_sorted_misfits_idx(chain=0)[::-1]

        gms **= problem.norm_exponent
        gms_softclip = num.where(gms > 1.0, 0.1 * num.log10(gms) + 1.0, gms)

        gcms = problem.combine_misfits(
            history.misfits,
            extra_correlated_weights=optimiser.get_correlated_weights(problem),
            get_contributions=True)

        gcms = gcms[isort, :]
        nmisfits = gcms.shape[1]  # noqa

        ncontributions = sum([
            1 if t.plot_misfits_cumulative else t.nmisfits
            for t in problem.targets
        ])
        cum_gcms = num.zeros((history.nmodels, ncontributions))

        # Squash matrix and sum large targets.nmisifts, eg SatelliteTarget
        plot_target_labels = []
        idx = 0
        idx_cum = 0
        for itarget, target in enumerate(problem.targets):
            target_gcms = gcms[:, idx:idx + target.nmisfits]
            if target.plot_misfits_cumulative:
                cum_gcms[:, idx_cum] = target_gcms.sum(axis=1)
                plot_target_labels.append(target.string_id())
                idx_cum += 1
            else:
                cum_gcms[:, idx_cum:idx_cum + target.nmisfits] = target_gcms
                plot_target_labels.extend(target.misfits_string_ids())
                idx_cum += target.nmisfits
            idx += target.nmisfits

        jsort = num.argsort(cum_gcms[-1, :])[::-1]

        # ncols = 4
        # nrows = ((problem.ntargets + 1) - 1) / ncols + 1

        axes = fig.add_subplot(2, 2, 1)
        labelpos(axes, 2.5, 2.0)

        axes.set_ylabel('Relative contribution (smoothed)')
        axes.set_ylim(0.0, 1.0)

        axes2 = fig.add_subplot(2, 2, 3, sharex=axes)
        labelpos(axes2, 2.5, 2.0)

        axes2.set_xlabel(
            'Tested model, sorted descending by global misfit value')

        axes2.set_ylabel('Square of misfit')

        axes2.set_ylim(0., 1.5)
        axes2.axhspan(1.0, 1.5, color=(0.8, 0.8, 0.8))
        axes2.set_yticks(
            [0., 0.2, 0.4, 0.6, 0.8, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5])
        axes2.set_yticklabels([
            '0.0', '0.2', '0.4', '0.6', '0.8', '1', '10', '100', '1000',
            '10000', '100000'
        ])

        axes2.set_xlim(imodels[0], imodels[-1])

        rel_ms_sum = num.zeros(history.nmodels)
        rel_ms_smooth_sum = num.zeros(history.nmodels)
        ms_smooth_sum = num.zeros(history.nmodels)
        b = num.hanning(min(100, history.nmodels // 5))
        b /= num.sum(b)
        a = [1]
        ii = 0

        for idx in jsort:
            target_label = plot_target_labels[idx]
            ms = cum_gcms[:, idx]

            ms = num.where(num.isfinite(ms), ms, 0.0)
            if num.all(ms == 0.0):
                continue

            rel_ms = ms / gms

            if b.shape[0] > 5:
                rel_ms_smooth = signal.filtfilt(b, a, rel_ms)
            else:
                rel_ms_smooth = rel_ms

            ms_smooth = rel_ms_smooth * gms_softclip

            rel_poly_y = num.concatenate(
                [rel_ms_smooth_sum[::-1], rel_ms_smooth_sum + rel_ms_smooth])
            poly_x = num.concatenate([imodels[::-1], imodels])

            add_args = {}
            if ii < 20:
                add_args['label'] = '%s (%.2g)' % (target_label,
                                                   num.mean(rel_ms[-1]))

            axes.fill(poly_x,
                      rel_poly_y,
                      alpha=0.5,
                      color=mpl_graph_color(ii),
                      **add_args)

            poly_y = num.concatenate(
                [ms_smooth_sum[::-1], ms_smooth_sum + ms_smooth])

            axes2.fill(poly_x, poly_y, alpha=0.5, color=mpl_graph_color(ii))

            rel_ms_sum += rel_ms

            # axes.plot(
            #    imodels, rel_ms_sum, color='black', alpha=0.1, zorder=-1)

            ms_smooth_sum += ms_smooth
            rel_ms_smooth_sum += rel_ms_smooth
            ii += 1

        axes.legend(title='Contributions (top twenty)',
                    bbox_to_anchor=(1.05, 0.0, 1.0, 1.0),
                    loc='upper left',
                    ncol=1,
                    borderaxespad=0.,
                    prop={'size': 9})

        axes2.plot(imodels, gms_softclip, color='black')
        axes2.axhline(1.0, color=(0.5, 0.5, 0.5))

        return [[PlotItem(name='main'), fig]]
    def test_point_in_polygon(self):
        if plot:
            from pyrocko.plot import mpl_graph_color

            import matplotlib.pyplot as plt
            from matplotlib.patches import Polygon

            axes = plt.gca()

        nip = 100

        for i in range(1):
            np = 3
            points = num.zeros((np, 2))
            points[:, 0] = random_lat(size=3)
            points[:, 1] = random_lon(size=3)

            points_ip = num.zeros((nip*points.shape[0], 2))
            for ip in range(points.shape[0]):
                n, e = orthodrome.latlon_to_ne_numpy(
                    points[ip % np, 0], points[ip % np, 1],
                    points[(ip+1) % np, 0], points[(ip+1) % np, 1])

                ns = num.arange(nip) * n / nip
                es = num.arange(nip) * e / nip
                lats, lons = orthodrome.ne_to_latlon(
                    points[ip % np, 0], points[ip % np, 1], ns, es)

                points_ip[ip*nip:(ip+1)*nip, 0] = lats
                points_ip[ip*nip:(ip+1)*nip, 1] = lons

            if plot:
                color = mpl_graph_color(i)
                axes.add_patch(
                    Polygon(
                        num.fliplr(points_ip),
                        facecolor=light(color),
                        edgecolor=color,
                        alpha=0.5))

            points_xyz = orthodrome.latlon_to_xyz(points_ip.T)
            center_xyz = num.mean(points_xyz, axis=0)

            assert num.all(
                orthodrome.distances3d(
                    points_xyz, center_xyz[num.newaxis, :]) < 1.0)

            lat, lon = orthodrome.xyz_to_latlon(center_xyz)
            rot = orthodrome.rot_to_00(lat, lon)

            points_rot_xyz = num.dot(rot, points_xyz.T).T
            points_rot_pro = orthodrome.stereographic(points_rot_xyz)  # noqa

            poly_xyz = orthodrome.latlon_to_xyz(points_ip)
            poly_rot_xyz = num.dot(rot, poly_xyz.T).T
            groups = orthodrome.spoly_cut([poly_rot_xyz], axis=0)
            num.zeros(points.shape[0], dtype=num.int)

            if plot:
                for group in groups:
                    for poly_rot_group_xyz in group:

                        axes.set_xlim(-180., 180.)
                        axes.set_ylim(-90., 90.)

                    plt.show()
Ejemplo n.º 9
0
    def draw_figures(self, history):

        fontsize = self.font_size

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

        problem = history.problem
        if not problem:
            logger.warn('problem not set')
            return []

        models = history.models

        if models.size == 0:
            logger.warn('empty models vector')
            return []

        imodels = num.arange(history.nmodels)

        gms = problem.combine_misfits(history.misfits)**problem.norm_exponent

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

        gms = gms[isort]

        gms_softclip = num.where(gms > 1.0, 0.1 * num.log10(gms) + 1.0, gms)

        gcms = problem.combine_misfits(history.misfits, get_contributions=True)

        gcms = gcms[isort, :]

        jsort = num.argsort(gcms[-1, :])[::-1]

        # ncols = 4
        # nrows = ((problem.ntargets + 1) - 1) / ncols + 1

        axes = fig.add_subplot(2, 2, 1)
        labelpos(axes, 2.5, 2.0)

        axes.set_ylabel('Relative contribution (smoothed)')
        axes.set_ylim(0.0, 1.0)

        axes2 = fig.add_subplot(2, 2, 3, sharex=axes)
        labelpos(axes2, 2.5, 2.0)

        axes2.set_xlabel(
            'Tested model, sorted descending by global misfit value')

        axes2.set_ylabel('Square of misfit')

        axes2.set_ylim(0., 1.5)
        axes2.axhspan(1.0, 1.5, color=(0.8, 0.8, 0.8))
        axes2.set_yticks(
            [0., 0.2, 0.4, 0.6, 0.8, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5])
        axes2.set_yticklabels([
            '0.0', '0.2', '0.4', '0.6', '0.8', '1', '10', '100', '1000',
            '10000', '100000'
        ])

        axes2.set_xlim(imodels[0], imodels[-1])

        rel_ms_sum = num.zeros(history.nmodels)
        rel_ms_smooth_sum = num.zeros(history.nmodels)
        ms_smooth_sum = num.zeros(history.nmodels)
        b = num.hanning(min(100, history.nmodels // 3))
        b /= num.sum(b)
        a = [1]
        ii = 0

        target_idx = [
            str(it) * t.nmisfits for it, t in enumerate(problem.targets)
        ]
        target_idx = num.fromiter(map(float, ''.join(target_idx)), dtype=int)

        for idx in jsort:
            target = problem.targets[target_idx[idx]]
            ms = gcms[:, idx]

            ms = num.where(num.isfinite(ms), ms, 0.0)
            if num.all(ms == 0.0):
                continue

            rel_ms = ms / gms

            rel_ms_smooth = signal.filtfilt(b, a, rel_ms)

            ms_smooth = rel_ms_smooth * gms_softclip

            rel_poly_y = num.concatenate(
                [rel_ms_smooth_sum[::-1], rel_ms_smooth_sum + rel_ms_smooth])
            poly_x = num.concatenate([imodels[::-1], imodels])

            add_args = {}
            if ii < 20:
                add_args['label'] = '%s (%.2g)' % (target.string_id(),
                                                   num.mean(rel_ms[-1]))

            axes.fill(poly_x,
                      rel_poly_y,
                      alpha=0.5,
                      color=mpl_graph_color(ii),
                      **add_args)

            poly_y = num.concatenate(
                [ms_smooth_sum[::-1], ms_smooth_sum + ms_smooth])

            axes2.fill(poly_x, poly_y, alpha=0.5, color=mpl_graph_color(ii))

            rel_ms_sum += rel_ms

            # axes.plot(
            #    imodels, rel_ms_sum, color='black', alpha=0.1, zorder=-1)

            ms_smooth_sum += ms_smooth
            rel_ms_smooth_sum += rel_ms_smooth
            ii += 1

        axes.legend(title='Contributions (top twenty)',
                    bbox_to_anchor=(1.05, 0.0, 1.0, 1.0),
                    loc='upper left',
                    ncol=1,
                    borderaxespad=0.,
                    prop={'size': 9})

        axes2.plot(imodels, gms_softclip, color='black')
        axes2.axhline(1.0, color=(0.5, 0.5, 0.5))

        return [[PlotItem(name='main'), fig]]