Commit d19a7742 authored by Sebastian Heimann's avatar Sebastian Heimann

continued...

parent aacba13a
......@@ -25,6 +25,7 @@ def d2u(d):
subcommand_descriptions = {
'init': 'print example configuration',
'check': 'check data and configuration',
'go': 'run Grond optimization',
'forward': 'run forward modelling',
'harvest': 'manually run harvesting',
......@@ -35,12 +36,13 @@ subcommand_descriptions = {
subcommand_usages = {
'init': 'init [options]',
'check': 'check <configfile> [options]',
'go': 'go <configfile> [options]',
'forward': 'forward <rundir> [options]',
'harvest': 'harvest <rundir> [options]',
'map-geometry': 'map-geometry <configfile> [options]',
'plot': 'plot <plotnames> <rundir> [options]',
'export': 'export <rundir> <outputfile> [options]',
'export': 'export (best|mean|ensemble|stats) <rundirs> ... [options]',
}
subcommands = subcommand_descriptions.keys()
......@@ -55,6 +57,7 @@ usage = '''%(program_name)s <subcommand> [options] [--] <arguments> ...
Subcommands:
init %(init)s
check %(check)s
go %(go)s
forward %(forward)s
harvest %(harvest)s
......@@ -169,6 +172,20 @@ def command_init(args):
print config
def command_check(args):
def setup(parser):
pass
parser, options, args = cl_parse('check', args, setup)
if len(args) != 1:
help_and_die(parser, 'no config file given')
config_path = args[0]
config = grond.read_config(config_path)
grond.check(config)
def command_go(args):
def setup(parser):
parser.add_option(
......@@ -254,17 +271,58 @@ def command_plot(args):
def command_export(args):
parser, options, args = cl_parse('export', args)
if len(args) not in (1, 2):
help_and_die(parser, 'one or two arguments required')
dirname = args[0]
if len(args) == 2:
filename = args[1]
def setup(parser):
parser.add_option(
'--type', dest='type', metavar='TYPE',
choices=('event', 'source', 'vector'),
help='select type of objects to be exported. Choices: '
'"event" (default), "source", "vector".')
parser.add_option(
'--parameters', dest='parameters', metavar='PLIST',
help='select parameters to be exported. PLIST is a '
'comma-separated list where each entry has the form '
'"<parameter>[.<measure>]". Available measures: "best", '
'"mean", "std", "minimum", "percentile16", "median", '
'"percentile84", "maximum".')
parser.add_option(
'--output', dest='filename', metavar='FILE',
help='write output to FILE')
parser, options, args = cl_parse('export', args, setup)
if len(args) < 2:
help_and_die(parser, 'arguments required')
what = args[0]
dirnames = args[1:]
what_choices = ('best', 'mean', 'ensemble', 'stats')
if what not in what_choices:
help_and_die(
parser,
'invalid choice: %s (choose from %s)' % (
repr(what), ', '.join(repr(x) for x in what_choices)))
if options.parameters:
pnames = options.parameters.split(',')
else:
filename = None
pnames = None
try:
grond.export(
what,
dirnames,
filename=options.filename,
type=options.type,
pnames=pnames)
except grond.GrondError, e:
die(str(e))
grond.export(dirname, filename)
if __name__ == '__main__':
......
......@@ -166,7 +166,7 @@ class CMTProblem(core.Problem):
def evaluate(self, x, return_traces=False):
source = self.unpack(x)
engine = gf.get_engine()
engine = self.get_engine()
for target in self.targets:
target.set_return_traces(return_traces)
......@@ -194,7 +194,7 @@ class CMTProblem(core.Problem):
def forward(self, x):
source = self.unpack(x)
engine = gf.get_engine()
engine = self.get_engine()
plain_targets = [target.get_plain_target() for target in self.targets]
resp = engine.process(source, plain_targets)
......
This diff is collapsed.
......@@ -2,7 +2,7 @@
import logging
from collections import defaultdict
import numpy as num
from pyrocko import util, pile, model, config, trace, snuffling
from pyrocko import util, pile, model, config, trace, snuffling, gui_util
from pyrocko.fdsn import enhanced_sacpz, station as fs
from pyrocko.guts import Object, Tuple, String, Float, dump_all, load_all
......@@ -51,6 +51,7 @@ class Dataset(object):
self.whitelist_nsl = None
self.station_corrections = {}
self.station_factors = {}
self.pick_markers = []
self.apply_correction_delays = True
self.apply_correction_factors = True
self.clip_handling = 'by_nsl'
......@@ -63,15 +64,26 @@ class Dataset(object):
def set_synthetic_test(self, synthetic_test):
self.synthetic_test = synthetic_test
def add_stations(self, stations=None, filename=None):
def add_stations(
self,
stations=None,
pyrocko_stations_filename=None,
stationxml_filenames=None):
if stations is not None:
for station in stations:
self.stations[station.nsl()] = station
if filename is not None:
for station in model.load_stations(filename):
if pyrocko_stations_filename is not None:
for station in model.load_stations(pyrocko_stations_filename):
self.stations[station.nsl()] = station
if stationxml_filenames is not None:
for stationxml_filename in stationxml_filenames:
sx = fs.load_xml(filename=stationxml_filename)
for station in sx.get_pyrocko_stations():
self.stations[station.nsl()] = station
def add_events(self, events=None, filename=None):
if events is not None:
self.events.extend(events)
......@@ -147,6 +159,10 @@ class Dataset(object):
self.station_corrections.update(
(sc.codes, sc) for sc in load_station_corrections(filename))
def add_picks(self, filename):
self.pick_markers.extend(
gui_util.load_markers(filename))
def is_blacklisted(self, obj):
try:
nslc = self.get_nslc(obj)
......@@ -335,6 +351,7 @@ class Dataset(object):
if deltat is not None:
tr.downsample_to(deltat, snap=True)
tr.deltat = deltat
resp = self.get_response(tr)
return tr.transfer(tfade=tfade, freqlimits=freqlimits,
......@@ -465,6 +482,34 @@ class Dataset(object):
return ev_x
def get_pick(self, eventname, obj, phasename):
nsl = self.get_nsl(obj)
hash_to_name = {}
for marker in self.pick_markers:
if isinstance(marker, gui_util.EventMarker):
hash_to_name[marker.get_event_hash()] = marker.get_event().name
candidates = []
for marker in self.pick_markers:
if (isinstance(marker, gui_util.PhaseMarker) and
marker.one_nslc()[:3] == nsl and
marker.get_phasename() == phasename and
hash_to_name[marker.get_event_hash()] == eventname):
candidates.append(marker)
candidates.sort(key=lambda marker: marker.tmin)
if len(candidates) == 1:
return candidates[0]
elif len(candidates) == 0:
return None
else:
logger.warn('multiple picks match %s.%s.%s, %s, %s' % (
nsl + (phasename, event.name or util.time_to_str(event.time))))
return candidates[0]
__all__ = '''
InvalidObject
......
......@@ -4,7 +4,7 @@ import logging
import os.path as op
import numpy as num
from scipy import signal
from pyrocko import automap, moment_tensor as mtm, beachball, guts, trace, util
from pyrocko import automap, beachball, guts, trace, util
from pyrocko import hudson
from grond import core
from matplotlib import pyplot as plt
......@@ -28,21 +28,6 @@ def nextpow2(i):
return 2**int(math.ceil(math.log(i)/math.log(2.)))
def get_mean_source(problem, xs):
x_mean = num.mean(xs, axis=0)
source = problem.unpack(x_mean)
return source
def get_best_source(problem, xs, misfits):
gms = problem.global_misfits(misfits)
print gms.min(), gms.mean()
ibest = num.argmin(gms)
x_best = xs[ibest, :]
source = problem.unpack(x_best)
return source
def fixlim(lo, hi):
if lo == hi:
return lo - 1.0, hi + 1.0
......@@ -334,11 +319,11 @@ def draw_jointpar_figures(
exclude=None):
color = 'magnitude'
#exclude = ['duration']
# exclude = ['duration']
neach = 6
figsize = (8, 8)
#cmap = cm.YlOrRd
#cmap = cm.jet
# cmap = cm.YlOrRd
# cmap = cm.jet
cmap = cm.coolwarm
problem = model.problem
......@@ -397,7 +382,6 @@ def draw_jointpar_figures(
if nselected == 0:
return
nfig = (nselected-2) / neach + 1
figs = []
......@@ -529,7 +513,11 @@ def draw_jointpar_figures(
def draw_solution_figure(
model, plt, misfit_cutoff=None, beachball_type='full'):
fig = plt.figure()
fontsize = 10.
fig = plt.figure(figsize=(6, 2))
axes = fig.add_subplot(1, 1, 1, aspect=1.0)
fig.subplots_adjust(left=0., right=1., bottom=0., top=1.)
problem = model.problem
if not problem:
......@@ -540,50 +528,104 @@ def draw_solution_figure(
if xs.size == 0:
return
def get_mt_part(x):
source = problem.unpack(x)
mt = source.pyrocko_moment_tensor()
res = mt.standard_decomposition()
m = dict(
dc=res[1][2],
deviatoric=res[3][2],
full=res[4][2])[beachball_type]
return mtm.MomentTensor(m=m)
gms = problem.global_misfits(model.misfits)
isort = num.argsort(gms)
iorder = num.empty_like(isort)
iorder[isort] = num.arange(iorder.size)[::-1]
if misfit_cutoff is None:
iibest = num.where(iorder > iorder.size - 100)[0]
else:
iibest = num.where(gms < misfit_cutoff)[0]
nsamp = 10
for isamp in xrange(nsamp):
ichoice = iibest[random.randint(0, iibest.size-1)]
axes = fig.add_subplot(1, nsamp+1, isamp+1, aspect=1.)
axes.axison = False
axes.set_xlim(-1.05, 1.05)
axes.set_ylim(-1.05, 1.05)
axes.set_title('#%i' % (iorder.size - iorder[ichoice] + 1))
mean_source = core.get_mean_source(problem, model.xs)
best_source = core.get_best_source(problem, model.xs, model.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], scolor('aluminium5')),
(1., 'Ensemble mean', decos[1], scolor('scarletred1')),
(0., 'Reference', decos[2], scolor('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 != 0.0:
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)
x = xs[ichoice, :]
mt = get_mt_part(x)
beachball.plot_beachball_mpl(mt, axes)
else:
axes.annotate(
'N/A',
position=(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 = fig.add_subplot(1, nsamp+1, nsamp+1, aspect=1.)
axes.axison = False
axes.set_xlim(-1.05, 1.05)
axes.set_ylim(-1.05, 1.05)
axes.set_title('Ref')
xref = problem.pack(problem.base_source)
mt = get_mt_part(xref)
beachball.plot_beachball_mpl(mt, axes)
axes.set_xlim(-2.25, 9.75)
axes.set_ylim(-0.5, 3.5)
fig.savefig('test.pdf')
def draw_contributions_figure(model, plt):
......@@ -1082,8 +1124,8 @@ def draw_hudson_figure(model, plt):
figsize = (width, width / (4./3.))
problem = model.problem
mean_source = get_mean_source(problem, model.xs)
best_source = get_best_source(problem, model.xs, model.misfits)
mean_source = core.get_mean_source(problem, model.xs)
best_source = core.get_best_source(problem, model.xs, model.misfits)
fig = plt.figure(figsize=figsize)
axes = fig.add_subplot(1, 1, 1)
......@@ -1147,7 +1189,6 @@ def draw_hudson_figure(model, plt):
color='none',
zorder=1)
fig.savefig('hudson.pdf')
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment