if icluster == -1: return 'Unclust. (%.0f%%)' % perc else: return 'Cluster %i (%.0f%%)' % (icluster, perc)
if icluster == -1: return mpl_color('aluminium3') else: return mpl_graph_color(icluster)
return lo - 1.0, hi + 1.0 else:
evals, evecs = num.linalg.eigh(mat) iorder = num.argsort(evals) return evals[iorder], evecs[:, iorder]
''' Source problem parameter's tradeoff plots. '''
if self.show_reference else ''
self, self.draw_figures(history, optimiser), title=u'Jointpar Plot', section='solution', feather_icon='crosshair', description=u''' Source problem parameter's scatter plots, to evaluate the resolution of source parameters and possible trade-offs between pairs of model parameters.
A subset of model solutions (from harvest) is shown in two dimensions for all possible parameter pairs as points. The point color indicates the misfit for the model solution with cold colors (blue) for high misfit models and warm colors (red) for low misfit models. The plot ranges are defined by the given parameter bounds and shows the model space of the optimsation. %s''' % sref)
return []
exclude.append(par.name)
ibest = gms < misfit_cutoff gms = gms[ibest] models = models[ibest]
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 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)
include and par.name not in include: continue
logger.warn('Cannot draw joinpar figures with less than two ' 'parameters selected.') return []
else:
(0.0, 10., xmin), (1.0, -10., xmax)]:
'%.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.)
(0., 10., ymin), (1.0, -10., ymax)]:
'%.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.)
else: axes.tick_params(length=4, which='both') axes.get_yaxis().set_ticklabels([]) axes.get_xaxis().set_ticklabels([])
xpar.get_label(with_unit=False), xy=(0.5, -0.05), xycoords='axes fraction', verticalalignment='top', horizontalalignment='right', rotation=45.)
ypar.get_label(with_unit=False), xy=(-0.05, 0.5), xycoords='axes fraction', verticalalignment='top', horizontalalignment='right', rotation=45.)
xpar.scaled(fx), ypar.scaled(fy), c=icolor, s=msize, alpha=0.5, cmap=cmap, edgecolors='none', **kwargs)
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)
xpar.scaled(fx), ypar.scaled(fy), 's', mew=1.5, ms=5, mfc=ref_color_light, mec=ref_color)
item_fig for item_fig in figs_row if item_fig is not None)
''' Histograms or Gaussian kernel densities (default) of all parameters (marginal distributions of model parameters).
The histograms (by default shown as Gaussian kernel densities) show (red curved solid line) the distributions of the parameters (marginals) along with some characteristics: The red solid vertical line gives the median of the distribution and the dashed red vertical line the mean value. Dark gray vertical lines show reference values (given in the event.txt file). The overlapping red-shaded areas show the 68% confidence intervals (innermost area), the 90% confidence intervals (middle area) and the minimum and maximum values (widest area). The plot ranges are defined by the given parameter bounds and show the model space. Well resolved model parameters show peaked distributions. '''
choices=['gaussian_kde', 'histogram'], default='gaussian_kde')
self, self.draw_figures(history), title=u'Histogram', section='solution', feather_icon='bar-chart-2', description=u''' Distribution of the problem's parameters.
The histograms are shown either as Gaussian kernel densities (red curved solid line) or as bar plots the distributions of the parameters (marginals) along with some characteristics:
The red solid vertical line gives the median of the distribution and the dashed red vertical line the mean value. Dark gray vertical lines show reference parameter values if given in the event.txt file. The overlapping red-shaded areas show the 68% confidence intervals (innermost area), the 90% confidence intervals (middle area) and the minimum and maximum values (widest area). The plot ranges are defined by the given parameter bounds and show the model space. ''')
exclude.append(par.name)
include and par.name not in include: continue
problem.combined[smap[iselected]].name for iselected in range(nselected)]
history.get_primary_chain_misfits(), pnames=pnames)
fig, nw=1, nh=1, w=7., bottom=5., top=1, units=fontsize)
except Exception: logger.warn( 'Cannot create plot histogram with gaussian_kde: ' 'possibly all samples have the same value.') continue
par.scaled(vps), par.inv_scaled(pps), color=stats_color)
elif method == 'histogram': pps, edges = num.histogram( vs, bins=num.linspace(vmin, vmax, num=40), density=True) vps = 0.5 * (edges[:-1] + edges[1:])
axes.bar(par.scaled(vps), par.inv_scaled(pps), par.scaled(2.*(vps - edges[:-1])), color=bar_color)
par.scaled(pstats.minimum), par.scaled(pstats.maximum), color=stats_color, alpha=0.1) par.scaled(pstats.percentile16), par.scaled(pstats.percentile84), color=stats_color, alpha=0.1) par.scaled(pstats.percentile5), par.scaled(pstats.percentile95), color=stats_color, alpha=0.1)
par.scaled(pstats.median), color=stats_color3, alpha=0.5) par.scaled(pstats.mean), color=stats_color3, ls=':', alpha=0.5)
par.scaled(problem.extract(xref, ipar)), color=ref_color)
''' Moment tensor decomposition plot. '''
optional=True, help='name of attribute to use as cluster IDs')
self, self.draw_figures(history), title=u'MT Decomposition', section='solution', feather_icon='sun', description=u''' Moment tensor decomposition of the best-fitting solution into isotropic, deviatoric and best double couple components.
Shown are the ensemble best, the ensemble mean%s and, if available, a reference mechanism. The symbol size indicates the relative strength of the components. The inversion result is consistent and stable if ensemble mean and ensemble best have similar symbol size and patterns. ''' % (', cluster results' if self.cluster_attribute else ''))
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]
problem, history.models)
cluster_sources = history.mean_sources_by_cluster( self.cluster_attribute) else:
('Ensemble best', get_deco(best_source), mpl_color('aluminium5')))
('Ensemble mean', get_deco(mean_source), mpl_color('aluminium5')))
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.))
('Reference', get_deco(ref_source), mpl_color('aluminium3')))
(0., 'Full'), (2., 'Isotropic'), (4., 'Deviatoric'), (6., 'CLVD'), (8., 'DC')]:
label, xy=(1 + xpos, nlines_max), xycoords='data', xytext=(0., 0.), textcoords='offset points', ha='center', va='center', color='black', fontsize=fontsize)
(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
label, xy=(-2., ypos), xycoords='data', xytext=(0., 0.), textcoords='offset points', ha='left', va='center', color='black', fontsize=fontsize)
(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)]:
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: 'N/A', xy=(1. + xpos, ypos), ha='center', va='center', color='black', fontsize=fontsize)
ops, xy=(2. + xpos, ypos), ha='center', va='center', color='black', fontsize=fontsize)
''' MT location plot of the best solutions in three cross-sections. ''' choices=['full', 'deviatoric', 'dc'], default='dc') default=3., help='Normalisation of colors and alpha as :math:`x^\\gamma`.' 'A linear colormap/alpha with :math:`\\gamma=1`.')
self, self.draw_figures(history), title=u'MT Location', section='solution', feather_icon='target', description=u''' Location plot of the ensemble of best solutions in three cross-sections.
The coordinate range is defined by the search space given in the config file. Symbols show best double-couple mechanisms, and colors indicate low (red) and high (blue) misfit. ''')
['east_shift', sp.set_xlabel, sp.set_xlim], ['north_shift', sp.set_ylabel, sp.set_ylim], ['depth', sp.set_zlabel, sp.set_zlim]]:
volumes = models[:, problem.name_to_index('volume_change')] volume_max = volumes.max() volume_min = volumes.min()
volume_change = source.volume_change fac = (volume_change - volume_min) / (volume_max - volume_min) return markersize * .25 + markersize * .5 * fac
(axes_en, 'east_shift', 'north_shift'), (axes_dn, 'depth', 'north_shift'), (axes_ed, 'east_shift', 'depth')]:
except AttributeError: axes.patch.set_facecolor(mpl_color('aluminium1'))
(xmin, ymin), xmax-xmin, ymax-ymin, facecolor=mpl_color('white'), edgecolor=mpl_color('aluminium2'))
# 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)))
norm=colors.PowerNorm( gamma=self.normalisation_gamma, vmin=iorder.min(), vmax=iorder.max()),
cmap=plt.get_cmap('coolwarm'))
store=problem.get_gf_store(problem.targets[0]), target=problem.targets[0])
# TODO: Add rotation in cross-sections
float(iorder.max() - iorder.min())
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))
'''Fuzzy, propabalistic moment tensor plot '''
optional=True, help='name of attribute to use as cluster IDs')
self, self.draw_figures(history), title=u'Fuzzy MT', section='solution', feather_icon='wind', description=u''' A fuzzy moment tensor, illustrating the solution's uncertainty.
The P wave radiation pattern strength of every ensemble solution is stacked for all ray spokes. The projection shows the stacked radiation pattern. If the variability of the ensemble solutions is small, the fuzzy plot has clearly separated black and white fields, consistent with the nodal lines of the %s best solution (indicated in red). ''' % ('cluster' if self.cluster_attribute is not None else 'global'))
self.cluster_attribute)
problem, models, misfits).pyrocko_moment_tensor()
color = cluster_color(icluster) else:
mts, axes, best_mt, beachball_type='full', size=8.*math.sqrt(percentage/100.), position=(5., 5.), color_t=color, edgecolor='black', best_color=mpl_color('scarletred2'))
axes.annotate( cluster_label(icluster, percentage), xy=(5., 0.), xycoords='data', xytext=(0., self.font_size/2.), textcoords='offset points', ha='center', va='bottom', color='black', fontsize=self.font_size)
name=( 'cluster_%i' % icluster if icluster >= 0 else 'unclustered'))
''' Illustration of the solution distribution of decomposed moment tensor. '''
choices=['full', 'deviatoric', 'dc'], default='dc')
self, self.draw_figures(history), title=u'Hudson Plot', section='solution', feather_icon='box', description=u''' Hudson's source type plot with the ensemble of bootstrap solutions.
For about 10% of the solutions (randomly chosen), the focal mechanism is depicted, others are represented as dots. The square marks the global best fitting solution. ''')
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:
u, v, 'o', color=color, ms=markersize_small, mec='none', mew=0, alpha=0.25, zorder=0)
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))
u, v, 's', markersize=markersize, mew=1, mec='black', mfc='none', zorder=-2)
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))
name='main')
JointparPlot, HistogramPlot, ] |