grond 9.24 KB
Newer Older
Sebastian Heimann's avatar
Sebastian Heimann committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#!/usr/bin/env python

import math
import sys
import logging
from optparse import OptionParser

from pyrocko import util
from pyrocko.gf import Range

import grond
from grond import plot

logger = logging.getLogger('main')

km = 1000.


def d2u(d):
    if isinstance(d, dict):
        return dict((k.replace('-', '_'), v) for (k, v) in d.iteritems())
    else:
        return d.replace('-', '_')


subcommand_descriptions = {
    'init': 'print example configuration',
Sebastian Heimann's avatar
Sebastian Heimann committed
28
    'check': 'check data and configuration',
Sebastian Heimann's avatar
Sebastian Heimann committed
29
30
31
32
33
34
35
36
37
38
    'go': 'run Grond optimization',
    'forward': 'run forward modelling',
    'harvest': 'manually run harvesting',
    'map-geometry': 'make station map',
    'plot': 'plot optimization result',
    'export': 'export results',
}

subcommand_usages = {
    'init': 'init [options]',
Sebastian Heimann's avatar
Sebastian Heimann committed
39
    'check': 'check <configfile> [options]',
Sebastian Heimann's avatar
Sebastian Heimann committed
40
41
42
43
44
    'go': 'go <configfile> [options]',
    'forward': 'forward <rundir> [options]',
    'harvest': 'harvest <rundir> [options]',
    'map-geometry': 'map-geometry <configfile> [options]',
    'plot': 'plot <plotnames> <rundir> [options]',
Sebastian Heimann's avatar
Sebastian Heimann committed
45
    'export': 'export (best|mean|ensemble|stats) <rundirs> ... [options]',
Sebastian Heimann's avatar
Sebastian Heimann committed
46
47
48
49
50
51
52
53
54
55
56
57
58
59
}

subcommands = subcommand_descriptions.keys()

program_name = 'grond'

usage_tdata = d2u(subcommand_descriptions)
usage_tdata['program_name'] = program_name

usage = '''%(program_name)s <subcommand> [options] [--] <arguments> ...

Subcommands:

    init          %(init)s
Sebastian Heimann's avatar
Sebastian Heimann committed
60
    check         %(check)s
Sebastian Heimann's avatar
Sebastian Heimann committed
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
    go            %(go)s
    forward       %(forward)s
    harvest       %(harvest)s
    map-geometry  %(map_geometry)s
    plot          %(plot)s
    export        %(export)s

To get further help and a list of available options for any subcommand run:

    %(program_name)s <subcommand> --help

''' % usage_tdata


def add_common_options(parser):
    parser.add_option(
        '--loglevel',
        action='store',
        dest='loglevel',
        type='choice',
        choices=('critical', 'error', 'warning', 'info', 'debug'),
        default='info',
        help ='set logger level to '
              '"critical", "error", "warning", "info", or "debug". '
              'Default is "%default".')


def process_common_options(options):
    util.setup_logging(program_name, options.loglevel)


def cl_parse(command, args, setup=None):
    usage = subcommand_usages[command]
    descr = subcommand_descriptions[command]

    if isinstance(usage, basestring):
        usage = [usage]

    susage = '%s %s' % (program_name, usage[0])
    for s in usage[1:]:
        susage += '\n%s%s %s' % (' '*7, program_name, s)

    parser = OptionParser(
        usage=susage,
        description=descr[0].upper() + descr[1:] + '.')

    if setup:
        setup(parser)

    add_common_options(parser)
    (options, args) = parser.parse_args(args)
    process_common_options(options)
    return parser, options, args


def die(message, err=''):
    if err:
        sys.exit('%s: error: %s \n %s' % (program_name, message, err))
    else:
        sys.exit('%s: error: %s' % (program_name, message))


def help_and_die(parser, message):
    parser.print_help(sys.stderr)
    sys.stderr.write('\n')
    die(message)


def command_init(args):

    dataset_config = grond.DatasetConfig(
        stations_path='stations.txt',
        events_path='events.txt',
        waveform_paths=['data'])

    target_configs = [grond.TargetConfig(
        distance_min=10*km,
        distance_max=1000*km,
        channels=['Z', 'R', 'T'],
        interpolation='multilinear',
        store_id='global_2s',
        inner_misfit_config=grond.InnerMisfitConfig(
            fmin=0.01,
            fmax=0.1))]

    s2 = math.sqrt(2.0)

    problem_config = grond.CMTProblemConfig(
        name_template='cmt_%(event_name)s',
        distance_min=2.*km,
        nbootstrap=100,
        mt_type='deviatoric',
        ranges=dict(
            time=Range(0, 10.0, relative='add'),
            north_shift=Range(-16*km, 16*km),
            east_shift=Range(-16*km, 16*km),
            depth=Range(1*km, 11*km),
            magnitude=Range(4.0, 6.0),
            rmnn=Range(-s2, s2),
            rmee=Range(-s2, s2),
            rmdd=Range(-s2, s2),
            rmne=Range(-1.0, 1.0),
            rmnd=Range(-1.0, 1.0),
            rmed=Range(-1.0, 1.0),
            duration=Range(1.0, 15.0)))

    config = grond.Config(
        dataset_config=dataset_config,
        target_configs=target_configs,
        problem_config=problem_config)

    print config


Sebastian Heimann's avatar
Sebastian Heimann committed
175
176
177
178
179
180
181
182
183
184
185
186
187
188
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)


Sebastian Heimann's avatar
Sebastian Heimann committed
189
190
191
192
193
194
195
196
def command_go(args):
    def setup(parser):
        parser.add_option(
            '--force', dest='force', action='store_true',
            help='overwrite existing run directory')
        parser.add_option(
            '--status', dest='status', default='state',
            help='status output selection (choices: state, matrix)')
Sebastian Heimann's avatar
Sebastian Heimann committed
197
198
199
        parser.add_option(
            '--parallel', dest='nparallel', type='int', default=1,
            help='set number of events to process in parallel')
Sebastian Heimann's avatar
Sebastian Heimann committed
200
201
202
203
204
205
206
207
208
209
210
211

    parser, options, args = cl_parse('go', args, setup)
    if len(args) != 1:
        help_and_die(parser, 'no config file given')

    config_path = args[0]
    config = grond.read_config(config_path)
    if options.status == 'quiet':
        status = ()
    else:
        status = tuple(options.status.split(','))

Sebastian Heimann's avatar
Sebastian Heimann committed
212
213
214
215
216
    grond.go(
        config,
        force=options.force,
        status=status,
        nparallel=options.nparallel)
Sebastian Heimann's avatar
Sebastian Heimann committed
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235


def command_forward(args):
    parser, options, args = cl_parse('forward', args)
    if len(args) != 1:
        help_and_die(parser, 'incorrect number of arguments')

    run_path, = args
    grond.forward(run_path)


def command_harvest(args):
    def setup(parser):
        parser.add_option(
            '--force', dest='force', action='store_true',
            help='overwrite existing harvest directory')
        parser.add_option(
            '--neach', dest='neach', type=int, default=10,
            help='take NEACH best samples from each chain (default: 10)')
Sebastian Heimann's avatar
Sebastian Heimann committed
236
237
238
        parser.add_option(
            '--weed', dest='weed', type=int, default=0,
            help='weed out bootstrap samples with bad global performance')
Sebastian Heimann's avatar
Sebastian Heimann committed
239
240
241
242
243
244

    parser, options, args = cl_parse('harvest', args, setup)
    if len(args) != 1:
        help_and_die(parser, 'no rundir')

    run_path, = args
Sebastian Heimann's avatar
Sebastian Heimann committed
245
246
247
248
249
    grond.harvest(
        run_path,
        force=options.force,
        nbest=options.neach,
        weed=options.weed)
Sebastian Heimann's avatar
Sebastian Heimann committed
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274


def command_map_geometry(args):
    parser, options, args = cl_parse('map-geometry', args)
    if len(args) != 2:
        help_and_die(parser, 'two arguments required')

    config_path = args[0]
    output_path = args[1]
    config = grond.read_config(config_path)
    plot.map_geometry(config, output_path)


def command_plot(args):
    parser, options, args = cl_parse('plot', args)
    if len(args) != 2:
        help_and_die(parser, 'two arguments required')

    plotnames = args[0].split(',')
    dirname = args[1]
    plot.plot_result(dirname, plotnames)


def command_export(args):

Sebastian Heimann's avatar
Sebastian Heimann committed
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
    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(',')
Sebastian Heimann's avatar
Sebastian Heimann committed
312
    else:
Sebastian Heimann's avatar
Sebastian Heimann committed
313
314
315
316
317
318
319
320
321
322
323
324
        pnames = None

    try:
        grond.export(
            what,
            dirnames,
            filename=options.filename,
            type=options.type,
            pnames=pnames)

    except grond.GrondError, e:
        die(str(e))
Sebastian Heimann's avatar
Sebastian Heimann committed
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349



if __name__ == '__main__':

    if len(sys.argv) < 2:
        sys.exit('Usage: %s' % usage)

    args = list(sys.argv)
    args.pop(0)
    command = args.pop(0)

    if command in subcommands:
        globals()['command_' + d2u(command)](args)

    elif command in ('--help', '-h', 'help'):
        if command == 'help' and args:
            acommand = args[0]
            if acommand in subcommands:
                globals()['command_' + acommand](['--help'])

        sys.exit('Usage: %s' % usage)

    else:
        die('no such subcommand: %s' % command)