def plot_medians_meca(events, eventsclusters, clusters, conf, resdir, plotdir): nclusters = len(clusters) f = plt.figure(figsize=(10., 4.)) f.subplots_adjust(left=0., right=1., bottom=0., top=1.) axes = f.add_subplot(1, 1, 1) for icl, cl in enumerate(clusters): medians = model.load_events( os.path.join(resdir, 'median_cluster' + str(cl) + '.pf')) median = medians[0] if median.moment_tensor is not None: median_mt = median.moment_tensor beachball.plot_beachball_mpl(median_mt, axes, beachball_type='full', size=150., position=((10. * (icl + 0.5) / nclusters), 2.), color_t=cluster_to_color(cl), alpha=1.0, linewidth=1.0) axes.set_xlim(0., 10.) axes.set_ylim(0., 4.) axes.set_axis_off() figname = os.path.join(plotdir, 'medians_meca.' + conf.figure_format) f.savefig(figname)
def draw_figures(self, history): fontsize = self.font_size fig = plt.figure(figsize=self.size_inch) axes = fig.add_subplot(1, 1, 1, aspect=1.0) fig.subplots_adjust(left=0., right=1., bottom=0., top=1.) problem = history.problem models = history.models if models.size == 0: logger.warn('Empty models vector.') return [] # gms = problem.combine_misfits(history.misfits) # isort = num.argsort(gms) # iorder = num.empty_like(isort) # iorder[isort] = num.arange(iorder.size)[::-1] ref_source = problem.base_source mean_source = stats.get_mean_source( problem, history.models) best_source = history.get_best_source() nlines_max = int(round(self.size_cm[1] / 5. * 4. - 1.0)) if self.cluster_attribute: cluster_sources = history.mean_sources_by_cluster( self.cluster_attribute) else: cluster_sources = [] def get_deco(source): mt = source.pyrocko_moment_tensor() return mt.standard_decomposition() lines = [] lines.append( ('Ensemble best', get_deco(best_source), mpl_color('aluminium5'))) lines.append( ('Ensemble mean', get_deco(mean_source), mpl_color('aluminium5'))) for (icluster, perc, source) in cluster_sources: if len(lines) < nlines_max - int(self.show_reference): lines.append( (cluster_label(icluster, perc), get_deco(source), cluster_color(icluster))) else: logger.warn( 'Skipping display of cluster %i because figure height is ' 'too small. Figure height should be at least %g cm.' % ( icluster, (3 + len(cluster_sources) + int(self.show_reference)) * 5/4.)) if self.show_reference: lines.append( ('Reference', get_deco(ref_source), mpl_color('aluminium3'))) moment_full_max = max(deco[-1][0] for (_, deco, _) in lines) for xpos, label in [ (0., 'Full'), (2., 'Isotropic'), (4., 'Deviatoric'), (6., 'CLVD'), (8., 'DC')]: axes.annotate( label, xy=(1 + xpos, nlines_max), xycoords='data', xytext=(0., 0.), textcoords='offset points', ha='center', va='center', color='black', fontsize=fontsize) for i, (label, deco, color_t) in enumerate(lines): ypos = nlines_max - i - 1.0 [(moment_iso, ratio_iso, m_iso), (moment_dc, ratio_dc, m_dc), (moment_clvd, ratio_clvd, m_clvd), (moment_devi, ratio_devi, m_devi), (moment_full, ratio_full, m_full)] = deco size0 = moment_full / moment_full_max axes.annotate( label, xy=(-2., ypos), xycoords='data', xytext=(0., 0.), textcoords='offset points', ha='left', va='center', color='black', fontsize=fontsize) for xpos, mt_part, ratio, ops in [ (0., m_full, ratio_full, '-'), (2., m_iso, ratio_iso, '='), (4., m_devi, ratio_devi, '='), (6., m_clvd, ratio_clvd, '+'), (8., m_dc, ratio_dc, None)]: if ratio > 1e-4: try: beachball.plot_beachball_mpl( mt_part, axes, beachball_type='full', position=(1. + xpos, ypos), size=0.9 * size0 * math.sqrt(ratio), size_units='data', color_t=color_t, linewidth=1.0) except beachball.BeachballError as e: logger.warn(str(e)) axes.annotate( 'ERROR', xy=(1. + xpos, ypos), ha='center', va='center', color='red', fontsize=fontsize) else: axes.annotate( 'N/A', xy=(1. + xpos, ypos), ha='center', va='center', color='black', fontsize=fontsize) if ops is not None: axes.annotate( ops, xy=(2. + xpos, ypos), ha='center', va='center', color='black', fontsize=fontsize) axes.axison = False axes.set_xlim(-2.25, 9.75) axes.set_ylim(-0.5, nlines_max+0.5) item = PlotItem(name='main') return [[item, fig]]
mpl_init(fontsize=fontsize) width = 7. figsize = (width, width / (4. / 3.)) fig = plt.figure(figsize=figsize) axes = fig.add_subplot(1, 1, 1) fig.subplots_adjust(left=0.03, right=0.97, bottom=0.03, top=0.97) # draw focal sphere diagrams for the random MTs for mt in moment_tensors: u, v = hudson.project(mt) try: beachball.plot_beachball_mpl( mt, axes, beachball_type='full', position=(u, v), size=markersize, color_t=mpl_color('skyblue3'), color_p=mpl_color('skyblue1'), alpha=1.0, # < 1 for transparency zorder=1, linewidth=0.25) except beachball.BeachballError as e: print(str(e), file=sys.stderr) # draw the axes and annotations of the hudson plot hudson.draw_axes(axes) fig.savefig('hudson_diagram.png', dpi=150) # plt.show()
def plot_directivity(engine, source, store_id, distance=300 * km, azi_begin=0., azi_end=360., dazi=1., phase_begin='first{stored:any_P}-10%', phase_end='last{stored:any_S}+50', quantity='displacement', envelope=False, component='R', fmin=0.01, fmax=0.1, hillshade=True, cmap=None, plot_mt='full', show_phases=True, show_description=True, reverse_time=False, show_nucleations=True, axes=None, nthreads=0): '''Plot the directivity and radiation characteristics of source models Synthetic seismic traces (R, T or Z) are forward-modelled at a defined radius, covering the full or partial azimuthal range and projected on a polar plot. Difference in the amplitude are enhanced by hillshading the data. :param engine: Forward modelling engine :type engine: :py:class:`~pyrocko.gf.seismosizer.Engine` :param source: Parametrized source model :type source: :py:class:`~pyrocko.gf.seismosizer.Source` :param store_id: Store ID used for forward modelling :type store_id: str :param distance: Distance in [m] :type distance: float :param azi_begin: Begin azimuth in [deg] :type azi_begin: float :param azi_end: End azimuth in [deg] :type azi_end: float :param dazi: Delta azimuth, bin size [deg] :type dazi: float :param phase_begin: Start time of the window :type phase_begin: :py:class:`~pyrocko.gf.meta.Timing` :param phase_end: End time of the window :type phase_end: :py:class:`~pyrocko.gf.meta.Timing` :param quantity: Seismogram quantity, default ``displacement`` :type quantity: str :param envelope: Plot envelop instead of seismic trace :type envelope: bool :param component: Forward modelled component, default ``R``. Choose from `RTZ` :type component: str :param fmin: Bandpass lower frequency [Hz], default ``0.01`` :type fmin: float :param fmax: Bandpass upper frequency [Hz], default ``0.1`` :type fmax: float :param hillshade: Enable hillshading, default ``True`` :type hillshade: bool :param cmap: Matplotlit colormap to use, default ``seismic``. When ``envelope`` is ``True`` the default colormap will be ``Reds``. :type cmap: str :param plot_mt: Plot a centered moment tensor, default ``full``. Choose from ``full, deviatoric, dc or False`` :type plot_mt: str, bool :param show_phases: Show annotations, default ``True`` :type show_phases: bool :param show_description: Show desciption, default ``True`` :type show_description: bool :param reverse_time: Reverse time axis. First phases arrive at the center, default ``False`` :type reverse_time: bool :param show_nucleations: Show nucleation piercing points on the moment tensor, default ``True`` :type show_nucleations: bool :param axes: Give axes to plot into :type axes: :py:class:`matplotlib.axes.Axes` :param nthreads: Number of threads used for forward modelling, default ``0`` - all available cores :type nthreads: int ''' if axes is None: fig = plt.figure() ax = fig.add_subplot(111, polar=True) else: fig = axes.figure ax = axes if envelope and cmap is None: cmap = 'Reds' elif cmap is None: cmap = 'seismic' targets, azimuths = get_azimuthal_targets(store_id, source, distance, azi_begin, azi_end, dazi, components='R', quantity=quantity) store = engine.get_store(store_id) mt = source.pyrocko_moment_tensor(store=store, target=targets[0]) resp = engine.process(source, targets, nthreads=nthreads) data, times = get_seismogram_array(resp, fmin, fmax, component=component, envelope=envelope) timing_begin = Timing(phase_begin) timing_end = Timing(phase_end) nucl_depth = source.depth nucl_distance = distance if hasattr(source, 'nucleation_x') and hasattr(source, 'nucleation_y'): try: iter(source.nucleation_x) nx = float(source.nucleation_x[0]) ny = float(source.nucleation_y[0]) except TypeError: nx = source.nucleation_x ny = source.nucleation_y nucl_distance += nx * source.length / 2. nucl_depth += ny * num.sin(source.dip * d2r) * source.width / 2. if hasattr(source, 'anchor'): anch_x, anch_y = map_anchor[source.anchor] nucl_distance -= anch_x * source.length / 2. nucl_depth -= anch_y * num.sin(source.dip * d2r) * source.width / 2. tbegin = store.t(timing_begin, (nucl_depth, nucl_distance)) tend = store.t(timing_end, (nucl_depth, nucl_distance)) tsel = num.logical_and(times >= tbegin, times <= tend) data = data[:, tsel].T times = times[tsel] duration = times[-1] - times[0] vmax = num.abs(data).max() cmw = ScalarMappable(cmap=cmap) cmw.set_array(data) cmw.set_clim(-vmax, vmax) if envelope: cmw.set_clim(0., vmax) ax.set_theta_zero_location("N") ax.set_theta_direction(-1) strike_label = mt.strike1 if hasattr(source, 'strike'): strike_label = source.strike try: ax.set_rlabel_position(strike_label % 180.) except AttributeError: logger.warn('Old matplotlib version: cannot set label positions') def r_fmt(v, p): if v < tbegin or v > tend: return '' return '%g s' % v ax.yaxis.set_major_formatter(FuncFormatter(r_fmt)) if reverse_time: ax.set_rlim(times[0] - .3 * duration, times[-1]) else: ax.set_rlim(times[-1] + .3 * duration, times[0]) ax.grid(zorder=20) if isinstance(plot_mt, str): mt_size = .15 beachball.plot_beachball_mpl(mt, ax, beachball_type=plot_mt, size=mt_size, size_units='axes', color_t=(0.7, 0.4, 0.4), position=(.5, .5), linewidth=1.) if hasattr(source, 'nucleation_x') and hasattr(source, 'nucleation_y')\ and show_nucleations: try: iter(source.nucleation_x) nucleation_x = source.nucleation_x nucleation_y = source.nucleation_y except TypeError: nucleation_x = [source.nucleation_x] nucleation_y = [source.nucleation_y] for nx, ny in zip(nucleation_x, nucleation_y): angle = float(num.arctan2(ny, nx)) rtp = num.array([[1., angle, (90. - source.strike) * d2r]]) points = beachball.numpy_rtp2xyz(rtp) x, y = beachball.project(points, projection='lambert').T norm = num.sqrt(x**2 + y**2) x = x / norm * mt_size / 2. y = y / norm * mt_size / 2. ax.plot(x + .5, y + .5, 'x', ms=6, mew=2, mec='darkred', mfc='red', transform=ax.transAxes, zorder=10) mesh = ax.pcolormesh(azimuths * d2r, times, data, cmap=cmw.cmap, shading='gouraud', zorder=0) if hillshade: mesh.update_scalarmappable() color = mesh.get_facecolor() color = hillshade_seismogram_array(data, color, shad_lim=(.85, 1.), blend_mode='multiply') mesh.set_facecolor(color) if show_phases: _phase_begin = Timing(phase_begin) _phase_end = Timing(phase_end) for p in (_phase_begin, _phase_end): p.offset = 0. p.offset_is_slowness = False p.offset_is_percent = False tphase_first = store.t(_phase_begin, (nucl_depth, nucl_distance)) tphase_last = store.t(_phase_end, (nucl_depth, nucl_distance)) theta = num.linspace(0, 2 * num.pi, 360) tfirst = num_full_like(theta, tphase_first) tlast = num_full_like(theta, tphase_last) ax.plot(theta, tfirst, color='k', alpha=.3, lw=1.) ax.plot(theta, tlast, color='k', alpha=.3, lw=1.) ax.text(num.pi * 7 / 5, tphase_first, '|'.join(_phase_begin.phase_defs), ha='left', color='k', fontsize='small') ax.text(num.pi * 6 / 5, tphase_last, '|'.join(_phase_end.phase_defs), ha='left', color='k', fontsize='small') description = ('Component {component:s}\n' 'Distance {distance:g} km').format(component=component, distance=distance / km) if show_description: if fmin and fmax: description += '\nBandpass {fmin:g} - {fmax:g} Hz'.format( fmin=fmin, fmax=fmax) elif fmin: description += '\nHighpass {fmin:g} Hz'.format(fmin=fmin) elif fmax: description += '\nLowpass {fmax:g} Hz'.format(fmax=fmax) ax.text(-.05, -.05, description, fontsize='small', ha='left', va='bottom', transform=ax.transAxes) cbar_label = QUANTITY_LABEL[quantity] if envelope: cbar_label = 'Envelope ' + cbar_label cb = fig.colorbar(cmw, ax=ax, orientation='vertical', shrink=.8, pad=0.11) cb.set_label(cbar_label) if axes is None: plt.show() return resp
#!/usr/bin/env python3 from matplotlib import pyplot as plt from pyrocko import moment_tensor as pmt from pyrocko.plot import beachball mt = pmt.as_mt([0.424, -0.47, 0.33, 0.711, -0.09, 0.16]) axes = plt.gca() beachball.plot_beachball_mpl(mt, axes, size=50., position=(0., 0.), view='top') beachball.plot_beachball_mpl(mt, axes, size=50., position=(0, -1.), view='south') beachball.plot_beachball_mpl(mt, axes, size=50., position=(-1, 0.), view='east') beachball.plot_beachball_mpl(mt, axes, size=50., position=(0, 1.), view='north') beachball.plot_beachball_mpl(mt, axes, size=50., position=(1, 0.), view='west')
phases = cake.PhaseDef.classic('P') # setup figure with aspect=1.0/1.0, ranges=[-1.1, 1.1] fig = plt.figure(figsize=(2., 2.)) # size in inch fig.subplots_adjust(left=0., right=1., bottom=0., top=1.) axes = fig.add_subplot(1, 1, 1, aspect=1.0) axes.set_axis_off() axes.set_xlim(-1.1, 1.1) axes.set_ylim(-1.1, 1.1) projection = 'lambert' beachball.plot_beachball_mpl( mt, axes, position=(0., 0.), size=2.0, color_t=(0.7, 0.4, 0.4), projection=projection, size_units='data') for rlat, rlon in rlatlons: distance = orthodrome.distance_accurate50m(slat, slon, rlat, rlon) rays = mod.arrivals( phases=cake.PhaseDef('P'), zstart=sdepth, zstop=rdepth, distances=[distance*cake.m2d]) if not rays: continue takeoff = rays[0].takeoff_angle() azi = orthodrome.azimuth(slat, slon, rlat, rlon)
def draw_figures(self, history): from matplotlib import colors color = 'black' fontsize = self.font_size markersize = fontsize * 1.5 beachballsize_small = markersize * 0.5 beachball_type = self.beachball_type problem = history.problem sp = SectionPlot(config=self) self._to_be_closed.append(sp) fig = sp.fig axes_en = sp.axes_xy axes_dn = sp.axes_zy axes_ed = sp.axes_xz bounds = problem.get_combined_bounds() gms = problem.combine_misfits(history.misfits) isort = num.argsort(gms)[::-1] gms = gms[isort] models = history.models[isort, :] iorder = num.arange(history.nmodels) for parname, set_label, set_lim in [[ 'east_shift', sp.set_xlabel, sp.set_xlim ], ['north_shift', sp.set_ylabel, sp.set_ylim], ['depth', sp.set_zlabel, sp.set_zlim]]: ipar = problem.name_to_index(parname) par = problem.combined[ipar] set_label(par.get_label()) xmin, xmax = fixlim(*par.scaled(bounds[ipar])) set_lim(xmin, xmax) for axes, xparname, yparname in [(axes_en, 'east_shift', 'north_shift'), (axes_dn, 'depth', 'north_shift'), (axes_ed, 'east_shift', 'depth')]: ixpar = problem.name_to_index(xparname) iypar = problem.name_to_index(yparname) xpar = problem.combined[ixpar] ypar = problem.combined[iypar] xmin, xmax = fixlim(*xpar.scaled(bounds[ixpar])) ymin, ymax = fixlim(*ypar.scaled(bounds[iypar])) try: axes.set_facecolor(mpl_color('aluminium1')) except AttributeError: axes.patch.set_facecolor(mpl_color('aluminium1')) rect = patches.Rectangle((xmin, ymin), xmax - xmin, ymax - ymin, facecolor=mpl_color('white'), edgecolor=mpl_color('aluminium2')) axes.add_patch(rect) # fxs = xpar.scaled(problem.extract(models, ixpar)) # fys = ypar.scaled(problem.extract(models, iypar)) # axes.set_xlim(*fixlim(num.min(fxs), num.max(fxs))) # axes.set_ylim(*fixlim(num.min(fys), num.max(fys))) cmap = cm.ScalarMappable(norm=colors.Normalize( vmin=num.min(iorder), vmax=num.max(iorder)), cmap=plt.get_cmap('coolwarm')) for ix, x in enumerate(models): source = problem.get_source(x) mt = source.pyrocko_moment_tensor(store=problem.get_gf_store( problem.targets[0]), target=problem.targets[0]) fx = problem.extract(x, ixpar) fy = problem.extract(x, iypar) sx, sy = xpar.scaled(fx), ypar.scaled(fy) color = cmap.to_rgba(iorder[ix]) alpha = (iorder[ix] - num.min(iorder)) / \ float(num.max(iorder) - num.min(iorder)) try: beachball.plot_beachball_mpl(mt, axes, beachball_type=beachball_type, position=(sx, sy), size=beachballsize_small, color_t=color, alpha=alpha, zorder=1, linewidth=0.25) except beachball.BeachballError as e: logger.warn(str(e)) item = PlotItem(name='main') return [[item, fig]]
figsize = (width, width / (4. / 3.)) fig = plt.figure(figsize=figsize) axes = fig.add_subplot(1, 1, 1) fig.subplots_adjust(left=0.03, right=0.97, bottom=0.03, top=0.97) # draw focal sphere diagrams for the random MT u, v = hudson.project(m) print(u, v) try: beachball.plot_beachball_mpl( m, axes, beachball_type='full', position=(u, v), size=30, color_t=mpl_color('skyblue3'), color_p=mpl_color('skyblue1'), alpha=1.0, # < 1 for transparency zorder=1, linewidth=0.25) except beachball.BeachballError as e: print(str(e), file=sys.stderr) # draw the axes and annotations of the hudson plot hudson.draw_axes(axes) #fig.savefig('hudson_diagram.png', dpi=250) plt.show()
# create a translation matrix, based on the final figure size and # beachball location move_trans = transforms.ScaledTranslation(szpt, -szpt, fig.dpi_scale_trans) # get the inverse matrix for the axis where the beachball will be plotted inv_trans = ax.transData.inverted() # set the bouding point relative to the plotted axis of the beachball x0, y1 = inv_trans.transform( move_trans.transform(ax.transData.transform((x0, y1)))) # plot beachball beachball.plot_beachball_mpl(source1.pyrocko_moment_tensor(), ax, beachball_type='full', size=sz, position=(x0, y1), linewidth=1.) # create source object source2 = gf.RectangularExplosionSource(depth=35e3, strike=0., dip=90.) # set size of beachball sz = 30. # set beachball offset in points (one point from each axis) szpt = (sz / 2.) / 72. + 1. / 72. # get the bounding point (right-upper) x1 = ax.get_xlim()[1] y1 = ax.get_ylim()[1]
y1 = ax.get_ylim()[1] # create a translation matrix, based on the final figure size and # beachball location move_trans = transforms.ScaledTranslation(szpt, -szpt, fig.dpi_scale_trans) # get the inverse matrix for the axis where the beachball will be plotted inv_trans = ax.transData.inverted() # set the bouding point relative to the plotted axis of the beachball x0, y1 = inv_trans.transform(move_trans.transform( ax.transData.transform((x0, y1)))) # plot beachball beachball.plot_beachball_mpl(source1.pyrocko_moment_tensor(), ax, beachball_type='full', size=sz, position=(x0, y1), linewidth=1.) # create source object source2 = gf.RectangularExplosionSource(depth=35e3, strike=0., dip=90.) # set size of beachball sz = 30. # set beachball offset in points (one point from each axis) szpt = (sz / 2.) / 72. + 1. / 72. # get the bounding point (right-upper) x1 = ax.get_xlim()[1] y1 = ax.get_ylim()[1]
def draw_figures(self, history): from matplotlib import colors color = 'black' fontsize = self.font_size markersize = fontsize * 1.5 beachballsize_small = markersize * 0.5 beachball_type = self.beachball_type problem = history.problem fig = plt.figure(figsize=self.size_inch) axes_en = fig.add_subplot(2, 2, 1) axes_dn = fig.add_subplot(2, 2, 2) axes_ed = fig.add_subplot(2, 2, 3) bounds = problem.get_combined_bounds() gms = problem.combine_misfits(history.misfits) isort = num.argsort(gms)[::-1] gms = gms[isort] models = history.models[isort, :] iorder = num.arange(history.nmodels) for axes, xparname, yparname in [(axes_en, 'east_shift', 'north_shift'), (axes_dn, 'depth', 'north_shift'), (axes_ed, 'east_shift', 'depth')]: ixpar = problem.name_to_index(xparname) iypar = problem.name_to_index(yparname) xpar = problem.combined[ixpar] ypar = problem.combined[iypar] axes.set_xlabel(xpar.get_label()) axes.set_ylabel(ypar.get_label()) xmin, xmax = fixlim(*xpar.scaled(bounds[ixpar])) ymin, ymax = fixlim(*ypar.scaled(bounds[iypar])) axes.set_aspect(1.0) axes.set_xlim(xmin, xmax) axes.set_ylim(ymin, ymax) # fxs = xpar.scaled(problem.extract(models, ixpar)) # fys = ypar.scaled(problem.extract(models, iypar)) # axes.set_xlim(*fixlim(num.min(fxs), num.max(fxs))) # axes.set_ylim(*fixlim(num.min(fys), num.max(fys))) cmap = cm.ScalarMappable(norm=colors.Normalize( vmin=num.min(iorder), vmax=num.max(iorder)), cmap=plt.get_cmap('coolwarm')) for ix, x in enumerate(models): source = problem.get_source(x) mt = source.pyrocko_moment_tensor() fx = problem.extract(x, ixpar) fy = problem.extract(x, iypar) sx, sy = xpar.scaled(fx), ypar.scaled(fy) color = cmap.to_rgba(iorder[ix]) alpha = (iorder[ix] - num.min(iorder)) / \ float(num.max(iorder) - num.min(iorder)) try: beachball.plot_beachball_mpl(mt, axes, beachball_type=beachball_type, position=(sx, sy), size=beachballsize_small, color_t=color, alpha=alpha, zorder=1, linewidth=0.25) except beachball.BeachballError as e: logger.warn(str(e)) item = PlotItem(name='main', title='Moment Tensor Location') return [[item, fig]]
def draw_figures(self, history): fontsize = self.font_size fig = plt.figure(figsize=self.size_inch) axes = fig.add_subplot(1, 1, 1, aspect=1.0) fig.subplots_adjust(left=0., right=1., bottom=0., top=1.) problem = history.problem models = history.models if models.size == 0: logger.warn('empty models vector') return [] gms = problem.combine_misfits(history.misfits) isort = num.argsort(gms) iorder = num.empty_like(isort) iorder[isort] = num.arange(iorder.size)[::-1] mean_source = core.get_mean_source(problem, history.models) best_source = core.get_best_source(problem, history.models, history.misfits) ref_source = problem.base_source for xpos, label in [(0., 'Full'), (2., 'Isotropic'), (4., 'Deviatoric'), (6., 'CLVD'), (8., 'DC')]: axes.annotate(label, xy=(1 + xpos, 3), xycoords='data', xytext=(0., 0.), textcoords='offset points', ha='center', va='center', color='black', fontsize=fontsize) decos = [] for source in [best_source, mean_source, ref_source]: mt = source.pyrocko_moment_tensor() deco = mt.standard_decomposition() decos.append(deco) moment_full_max = max(deco[-1][0] for deco in decos) for ypos, label, deco, color_t in [ (2., 'Ensemble best', decos[0], mpl_color('aluminium5')), (1., 'Ensemble mean', decos[1], mpl_color('scarletred1')), (0., 'Reference', decos[2], mpl_color('aluminium3')) ]: [(moment_iso, ratio_iso, m_iso), (moment_dc, ratio_dc, m_dc), (moment_clvd, ratio_clvd, m_clvd), (moment_devi, ratio_devi, m_devi), (moment_full, ratio_full, m_full)] = deco size0 = moment_full / moment_full_max axes.annotate(label, xy=(-2., ypos), xycoords='data', xytext=(0., 0.), textcoords='offset points', ha='left', va='center', color='black', fontsize=fontsize) for xpos, mt_part, ratio, ops in [(0., m_full, ratio_full, '-'), (2., m_iso, ratio_iso, '='), (4., m_devi, ratio_devi, '='), (6., m_clvd, ratio_clvd, '+'), (8., m_dc, ratio_dc, None)]: if ratio > 1e-4: try: beachball.plot_beachball_mpl( mt_part, axes, beachball_type='full', position=(1. + xpos, ypos), size=0.9 * size0 * math.sqrt(ratio), size_units='data', color_t=color_t, linewidth=1.0) except beachball.BeachballError as e: logger.warn(str(e)) axes.annotate('ERROR', xy=(1. + xpos, ypos), ha='center', va='center', color='red', fontsize=fontsize) else: axes.annotate('N/A', xy=(1. + xpos, ypos), ha='center', va='center', color='black', fontsize=fontsize) if ops is not None: axes.annotate(ops, xy=(2. + xpos, ypos), ha='center', va='center', color='black', fontsize=fontsize) axes.axison = False axes.set_xlim(-2.25, 9.75) axes.set_ylim(-0.5, 3.5) item = PlotItem(name='main') return [[item, fig]]
def show_comparison(self, nx=10): import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # noqa if nx > 1: plt.ion() plt.show() fig = plt.figure() axes1 = fig.add_subplot(2, 3, 1, aspect=1.) axes2 = fig.add_subplot(2, 3, 2, aspect=1.) axes3 = fig.add_subplot(2, 3, 3, aspect=1.) axes4 = fig.add_subplot(2, 3, 4, projection='3d', aspect=1.) axes5 = fig.add_subplot(2, 3, 5, projection='3d', aspect=1.) try: import mopad except ImportError: mopad = None for x in range(nx): mt = mtm.MomentTensor.random_mt() mt = mt.deviatoric() for axes in (axes1, axes2, axes3): axes.cla() axes.axison = False axes.set_xlim(-1.05, 1.05) axes.set_ylim(-1.05, 1.05) for axes in (axes4, axes5): axes.cla() axes1.set_title('Copacabana') axes2.set_title('Contour') axes3.set_title('MoPaD') axes4.set_title('Patches') axes5.set_title('Lines') beachball.plot_beachball_mpl(mt, axes1, size_units='data') beachball.plot_beachball_mpl_pixmap(mt, axes2, size_units='data') beachball.plot_beachball_mpl_construction( mt, axes4, show='patches') beachball.plot_beachball_mpl_construction( mt, axes5, show='lines') if mopad: try: mop_mt = mopad.MomentTensor(M=mt.m6()) mop_beach = mopad.BeachBall(mop_mt) kwargs = dict( plot_projection='lambert', plot_nodalline_width=2, plot_faultplane_width=2, plot_outerline_width=2) mop_beach.ploBB(kwargs, ax=axes3) except Exception: print( 'mopad failed (maybe patched mopad version is needed') fig.canvas.draw() if nx == 1: plt.show()
def draw_figures(self, history, color_p_axis=False): from matplotlib import colors color = 'black' fontsize = self.font_size markersize = fontsize * 1.5 beachballsize_small = markersize * 0.5 beachball_type = self.beachball_type problem = history.problem sp = SectionPlot(config=self) self._to_be_closed.append(sp) fig = sp.fig axes_en = sp.axes_xy axes_dn = sp.axes_zy axes_ed = sp.axes_xz bounds = problem.get_combined_bounds() models = history.get_sorted_primary_models()[::-1] iorder = num.arange(history.nmodels) for parname, set_label, set_lim in [ ['east_shift', sp.set_xlabel, sp.set_xlim], ['north_shift', sp.set_ylabel, sp.set_ylim], ['depth', sp.set_zlabel, sp.set_zlim]]: ipar = problem.name_to_index(parname) par = problem.combined[ipar] set_label(par.get_label()) xmin, xmax = fixlim(*par.scaled(bounds[ipar])) set_lim(xmin, xmax) if 'volume_change' in problem.parameter_names: volumes = models[:, problem.name_to_index('volume_change')] volume_max = volumes.max() volume_min = volumes.min() def scale_size(source): if not hasattr(source, 'volume_change'): return beachballsize_small volume_change = source.volume_change fac = (volume_change - volume_min) / (volume_max - volume_min) return markersize * .25 + markersize * .5 * fac for axes, xparname, yparname in [ (axes_en, 'east_shift', 'north_shift'), (axes_dn, 'depth', 'north_shift'), (axes_ed, 'east_shift', 'depth')]: ixpar = problem.name_to_index(xparname) iypar = problem.name_to_index(yparname) xpar = problem.combined[ixpar] ypar = problem.combined[iypar] xmin, xmax = fixlim(*xpar.scaled(bounds[ixpar])) ymin, ymax = fixlim(*ypar.scaled(bounds[iypar])) try: axes.set_facecolor(mpl_color('aluminium1')) except AttributeError: axes.patch.set_facecolor(mpl_color('aluminium1')) rect = patches.Rectangle( (xmin, ymin), xmax-xmin, ymax-ymin, facecolor=mpl_color('white'), edgecolor=mpl_color('aluminium2')) axes.add_patch(rect) # fxs = xpar.scaled(problem.extract(models, ixpar)) # fys = ypar.scaled(problem.extract(models, iypar)) # axes.set_xlim(*fixlim(num.min(fxs), num.max(fxs))) # axes.set_ylim(*fixlim(num.min(fys), num.max(fys))) cmap = cm.ScalarMappable( norm=colors.PowerNorm( gamma=self.normalisation_gamma, vmin=iorder.min(), vmax=iorder.max()), cmap=plt.get_cmap('coolwarm')) for ix, x in enumerate(models): source = problem.get_source(x) mt = source.pyrocko_moment_tensor( store=problem.get_gf_store(problem.targets[0]), target=problem.targets[0]) fx = problem.extract(x, ixpar) fy = problem.extract(x, iypar) sx, sy = xpar.scaled(fx), ypar.scaled(fy) # TODO: Add rotation in cross-sections color = cmap.to_rgba(iorder[ix]) alpha = (iorder[ix] - iorder.min()) / \ float(iorder.max() - iorder.min()) alpha = alpha**self.normalisation_gamma try: beachball.plot_beachball_mpl( mt, axes, beachball_type=beachball_type, position=(sx, sy), size=scale_size(source), color_t=color, color_p=color if color_p_axis else 'white', alpha=alpha, zorder=1, linewidth=0.25) except beachball.BeachballError as e: logger.warn(str(e)) item = PlotItem(name='main') return [[item, fig]]
def plot_map_basemap(stations=None, east_min=-119.2, east_max=-116, north_min=34.5, north_max=37.501, events=None, savename=None, preds=None, best_mts=None, pred_events=None, rect_lats=None, rect_lons=None, ticks=0.01, kmscale=5, add_grid=True, overview=False): try: from mpl_toolkits.basemap import Basemap use_basemap = True except: import cartopy.crs as ccrs import cartopy import cartopy.geodesic as cgeo from cartopy.io import srtm from cartopy.io import PostprocessedRasterSource, LocatedImage from cartopy.io.srtm import SRTM3Source, SRTM1Source use_basemap = False from matplotlib import pyplot as plt from pyrocko.plot import beachball from pyrocko import plot from obspy.imaging.beachball import beach fig, ax = plt.subplots(figsize=(12, 12)) map = Basemap(projection='merc', llcrnrlon=east_min, llcrnrlat=north_min, urcrnrlon=east_max, urcrnrlat=north_max, resolution='h', epsg=3395, ax=ax) xpixels = 1000 map.arcgisimage(service='World_Shaded_Relief', xpixels=xpixels, verbose=False, zorder=-3, colormap="gray", cmap="gray") if overview is True: map.drawmapscale(east_min + 0.35, north_min + 0.31, east_min + 0.65, north_min + 0.5, kmscale) else: map.drawmapscale(east_min + 0.05, north_min + 0.01, east_min + 0.55, north_min + 0.2, kmscale) parallels = np.arange(north_min, north_max, ticks) meridians = np.arange(east_min, east_max, ticks) if overview is True: map.drawparallels(np.round(parallels, 1), labels=[1, 0, 0, 0], fontsize=12) map.drawmeridians(np.round(meridians, 1), labels=[1, 1, 0, 1], fontsize=12, rotation=45) else: map.drawparallels(parallels, labels=[1, 0, 0, 0], fontsize=12) map.drawmeridians(meridians, labels=[1, 1, 0, 1], fontsize=12, rotation=45) if events is not None: for event in events: mt = event.moment_tensor if overview is False: if event.lat > 35.845: x, y = map(event.lon, event.lat) else: x, y = map(event.lon, event.lat) if overview is True: size = 12 else: size = 20 beachball.plot_beachball_mpl(mt, ax, beachball_type='full', size=size, position=(x, y), color_t=plot.mpl_color('scarletred2'), linewidth=1.0, zorder=1) if stations is not None: lats = [s.lat for s in stations] lons = [s.lon for s in stations] labels = ['.'.join(s.nsl()) for s in stations] x_station, y_station = map(lons, lats) map.scatter(x_station, y_station, marker="^", s=36, c="g", zorder=8) for k, label in enumerate(labels): plt.text(x_station[k], y_station[k], str(label), fontsize=12) if rect_lats is not None: import matplotlib.patches as patches if add_grid is True: for lat in rect_lats: for lon in rect_lons: x, y = map(lon, lat) rect = patches.Rectangle((x, y), 1800, 2200, linewidth=1, edgecolor='r', facecolor='none') # Add the patch to the Axes ax.add_patch(rect) max_lat_rect = np.max(rect_lats) min_lat_rect = np.min(rect_lats) max_lon_rect = np.max(rect_lons) min_lon_rect = np.min(rect_lons) xmin, ymin = map(min_lon_rect, max_lat_rect) xmax, ymax = map(max_lon_rect, min_lat_rect) width = xmax - xmin length = ymin - ymax if overview is True: rect = patches.Rectangle( (xmin, ymax), width, length, linewidth=5, edgecolor='k', facecolor='none', zorder=7, ) # Add the patch to the Axes ax.add_patch(rect) if preds is None and best_mts is not None: k = 1 for best_mt, ev in zip(best_mts, pred_events): mt = ev.moment_tensor x, y = map(ev.lon, ev.lat) plt.text(x, y + 0.02, str(k), fontsize=42, zorder=9, color="k") k = k + 1 beachball.plot_beachball_mpl(mt, ax, beachball_type='full', size=22., position=(x, y), color_t=plot.mpl_color('blue'), linewidth=1.0, zorder=3) if preds is not None: for pred_mts, best_mt, ev in zip(preds, best_mts, pred_events): x, y = map(ev.lon, ev.lat) plot_kwargs = { 'beachball_type': 'full', 'size': 500, 'position': (x, y), 'color_t': 'black', 'edgecolor': 'black', 'zorder': 3, } beachball.plot_fuzzy_beachball_mpl_pixmap(pred_mts, ax, best_mt, **plot_kwargs) plt.show()
def draw_figures(self, history): color = 'black' fontsize = self.font_size markersize = fontsize * 1.5 markersize_small = markersize * 0.2 beachballsize = markersize beachballsize_small = beachballsize * 0.5 beachball_type = self.beachball_type problem = history.problem best_source = history.get_best_source() mean_source = history.get_mean_source() fig = plt.figure(figsize=self.size_inch) axes = fig.add_subplot(1, 1, 1) data = [] for ix, x in enumerate(history.models): source = problem.get_source(x) mt = source.pyrocko_moment_tensor() u, v = hudson.project(mt) if random.random() < 0.1: try: beachball.plot_beachball_mpl( mt, axes, beachball_type=beachball_type, position=(u, v), size=beachballsize_small, color_t=color, alpha=0.5, zorder=1, linewidth=0.25) except beachball.BeachballError as e: logger.warn(str(e)) else: data.append((u, v)) if data: u, v = num.array(data).T axes.plot( u, v, 'o', color=color, ms=markersize_small, mec='none', mew=0, alpha=0.25, zorder=0) hudson.draw_axes(axes) mt = mean_source.pyrocko_moment_tensor() u, v = hudson.project(mt) try: beachball.plot_beachball_mpl( mt, axes, beachball_type=beachball_type, position=(u, v), size=beachballsize, color_t=color, zorder=2, linewidth=0.5) except beachball.BeachballError as e: logger.warn(str(e)) mt = best_source.pyrocko_moment_tensor() u, v = hudson.project(mt) axes.plot( u, v, 's', markersize=markersize, mew=1, mec='black', mfc='none', zorder=-2) if self.show_reference: mt = problem.base_source.pyrocko_moment_tensor() u, v = hudson.project(mt) try: beachball.plot_beachball_mpl( mt, axes, beachball_type=beachball_type, position=(u, v), size=beachballsize, color_t='red', zorder=2, linewidth=0.5) except beachball.BeachballError as e: logger.warn(str(e)) item = PlotItem( name='main') return [[item, fig]]
phases = cake.PhaseDef.classic('p') # setup figure with aspect=1.0/1.0, ranges=[-1.1, 1.1] fig = plt.figure(figsize=(4., 4.)) # size in inch fig.subplots_adjust(left=0., right=1., bottom=0., top=1.) axes = fig.add_subplot(1, 1, 1, aspect=1.0) axes.set_axis_off() axes.set_xlim(-1.1, 1.1) axes.set_ylim(-1.1, 1.1) projection = 'lambert' beachball.plot_beachball_mpl(mt, axes, position=(0., 0.), size=2.0, color_t=(0.3, 0.3, 0.8), projection=projection, size_units='data') for rlat, rlon in rlatlons: distance = orthodrome.distance_accurate50m(slat, slon, rlat, rlon) rays = mod.arrivals(phases=cake.PhaseDef('P'), zstart=sdepth, zstop=rdepth, distances=[distance * cake.m2d]) if not rays: continue takeoff = rays[0].takeoff_angle()
from matplotlib import pyplot as plt from pyrocko import moment_tensor as pmt from pyrocko import plot from pyrocko.plot import beachball fig = plt.figure(figsize=(4., 2.)) fig.subplots_adjust(left=0., right=1., bottom=0., top=1.) axes = fig.add_subplot(1, 1, 1) axes.set_xlim(0., 4.) axes.set_ylim(0., 2.) axes.set_axis_off() for i, beachball_type in enumerate(['full', 'deviatoric', 'dc']): beachball.plot_beachball_mpl(pmt.as_mt( (124654616., 370943136., -6965434.0, 553316224., -307467264., 84703760.0)), axes, beachball_type=beachball_type, size=60., position=(i + 1, 1), color_t=plot.mpl_color('scarletred2'), linewidth=1.0) fig.savefig('beachball-example03.pdf') plt.show()
fig = plt.figure(figsize=(10., 4.)) fig.subplots_adjust(left=0., right=1., bottom=0., top=1.) axes = fig.add_subplot(1, 1, 1) for i in range(200): # create random moment tensor mt = pmt.MomentTensor.random_mt() try: # create beachball from moment tensor beachball.plot_beachball_mpl( mt, axes, # type of beachball: deviatoric, full or double couple (dc) beachball_type='full', size=random.random()*120., position=(random.random()*10., random.random()*10.), alpha=random.random(), linewidth=1.0) except beachball.BeachballError as e: logger.error('%s for MT:\n%s' % (e, mt)) axes.set_xlim(0., 10.) axes.set_ylim(0., 10.) axes.set_axis_off() fig.savefig('beachball-example01.pdf') plt.show()
def show_comparison(self, nx=10): import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # noqa if nx > 1: plt.ion() plt.show() fig = plt.figure() axes1 = fig.add_subplot(2, 3, 1, aspect=1.) axes2 = fig.add_subplot(2, 3, 2, aspect=1.) axes3 = fig.add_subplot(2, 3, 3, aspect=1.) axes4 = fig.add_subplot(2, 3, 4, projection='3d', aspect=1.) axes5 = fig.add_subplot(2, 3, 5, projection='3d', aspect=1.) try: import mopad except ImportError: mopad = None for x in range(nx): mt = mtm.MomentTensor.random_mt() mt = mt.deviatoric() for axes in (axes1, axes2, axes3): axes.cla() axes.axison = False axes.set_xlim(-1.05, 1.05) axes.set_ylim(-1.05, 1.05) for axes in (axes4, axes5): axes.cla() axes1.set_title('Copacabana') axes2.set_title('Contour') axes3.set_title('MoPaD') axes4.set_title('Patches') axes5.set_title('Lines') beachball.plot_beachball_mpl(mt, axes1, size_units='data') beachball.plot_beachball_mpl_pixmap(mt, axes2, size_units='data') beachball.plot_beachball_mpl_construction(mt, axes4, show='patches') beachball.plot_beachball_mpl_construction(mt, axes5, show='lines') if mopad: try: mop_mt = mopad.MomentTensor(M=mt.m6()) mop_beach = mopad.BeachBall(mop_mt) kwargs = dict(plot_projection='lambert', plot_nodalline_width=2, plot_faultplane_width=2, plot_outerline_width=2) mop_beach.ploBB(kwargs, ax=axes3) except Exception: print( 'mopad failed (maybe patched mopad version is needed') fig.canvas.draw() if nx == 1: plt.show()
fig = plt.figure(figsize=(10., 4.)) fig.subplots_adjust(left=0., right=1., bottom=0., top=1.) axes = fig.add_subplot(1, 1, 1) for i in range(200): # create random moment tensor mt = pmt.MomentTensor.random_mt() try: # create beachball from moment tensor beachball.plot_beachball_mpl( mt, axes, # type of beachball: deviatoric, full or double couple (dc) beachball_type='full', size=random.random() * 120., position=(random.random() * 10., random.random() * 10.), alpha=random.random(), linewidth=1.0) except beachball.BeachballError as e: logger.error('%s for MT:\n%s' % (e, mt)) axes.set_xlim(0., 10.) axes.set_ylim(0., 10.) axes.set_axis_off() fig.savefig('beachball-example01.pdf') plt.show()