grond 22.1 KB
Newer Older
Sebastian Heimann's avatar
Sebastian Heimann committed
1
2
3
4
5
#!/usr/bin/env python

import math
import sys
import logging
6
import os
Marius Isken's avatar
Marius Isken committed
7
import os.path as op
Sebastian Heimann's avatar
Sebastian Heimann committed
8
9
from optparse import OptionParser

10
from pyrocko import util, marker
Sebastian Heimann's avatar
Sebastian Heimann committed
11
12
13
14
15
from pyrocko.gf import Range

import grond

logger = logging.getLogger('main')
16
km = 1e3
Sebastian Heimann's avatar
Sebastian Heimann committed
17
18
19
20
21
22
23
24
25
26


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


subcommand_descriptions = {
marius's avatar
wip    
marius committed
27
    'init': 'create project structure or print example configuration',
Sebastian Heimann's avatar
Sebastian Heimann committed
28
    'events': 'print available event names for given configuration',
Sebastian Heimann's avatar
Sebastian Heimann committed
29
    'check': 'check data and configuration',
Sebastian Heimann's avatar
Sebastian Heimann committed
30
31
32
33
    'go': 'run Grond optimization',
    'forward': 'run forward modelling',
    'harvest': 'manually run harvesting',
    'plot': 'plot optimization result',
Marius Isken's avatar
Marius Isken committed
34
    'baraddur': 'start Barad-dur plotting, watching this directory',
Sebastian Heimann's avatar
Sebastian Heimann committed
35
    'export': 'export results',
36
    'qc-polarization': 'check sensor orientations with polarization analysis',
Sebastian Heimann's avatar
Sebastian Heimann committed
37
38
39
}

subcommand_usages = {
marius's avatar
wip    
marius committed
40
    'init': 'init [options] <project_dir>',
Sebastian Heimann's avatar
Sebastian Heimann committed
41
    'events': 'events <configfile>',
42
43
44
45
46
    'check': 'check <configfile> <eventnames> ... [options]',
    'go': 'go <configfile> <eventnames> ... [options]',
    'forward': (
        'forward <rundir> [options]',
        'forward <configfile> <eventnames> ... [options]'),
Sebastian Heimann's avatar
Sebastian Heimann committed
47
48
    'harvest': 'harvest <rundir> [options]',
    'plot': 'plot <plotnames> <rundir> [options]',
Marius Isken's avatar
Marius Isken committed
49
    'baraddur': 'plot-server',
Sebastian Heimann's avatar
Sebastian Heimann committed
50
    'export': 'export (best|mean|ensemble|stats) <rundirs> ... [options]',
51
52
    'qc-polarization': 'qc-polarization <configfile> <eventname> '
                       '<targetconfigname> [options]',
Sebastian Heimann's avatar
Sebastian Heimann committed
53
54
55
56
57
58
59
60
61
62
63
64
65
}

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:

66
67
68
69
70
71
72
73
74
    init            %(init)s
    events          %(events)s
    check           %(check)s
    go              %(go)s
    forward         %(forward)s
    harvest         %(harvest)s
    plot            %(plot)s
    export          %(export)s
    qc-polarization %(qc_polarization)s
75
    baraddur        %(baraddur)s
Sebastian Heimann's avatar
Sebastian Heimann committed
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91

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',
Sebastian Heimann's avatar
Sebastian Heimann committed
92
93
94
        help='set logger level to '
             '"critical", "error", "warning", "info", or "debug". '
             'Default is "%default".')
Sebastian Heimann's avatar
Sebastian Heimann committed
95
96
97
98
99
100


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


101
def cl_parse(command, args, setup=None, details=None):
Sebastian Heimann's avatar
Sebastian Heimann committed
102
103
104
105
106
107
108
109
110
111
    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)

112
113
114
115
116
117
    description = descr[0].upper() + descr[1:] + '.'

    if details:
        description = description + '\n\n%s' % details

    parser = OptionParser(usage=susage, description=description)
Sebastian Heimann's avatar
Sebastian Heimann committed
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

    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):

Marius Isken's avatar
Marius Isken committed
143
144
145
    def setup(parser):
        parser.add_option(
            '--waveform', dest='waveform', action='store_true', default=True,
146
147
            help='Create an example configuration for waveform inversion. '
                 '(default)')
Marius Isken's avatar
Marius Isken committed
148
149
        parser.add_option(
            '--static', dest='static', action='store_true',
150
151
            help='Create an example configuration for static displacements'
                 ' using kite scene containers.')
Marius Isken's avatar
Marius Isken committed
152
153
154

    parser, options, args = cl_parse('init', args, setup)

marius's avatar
wip    
marius committed
155
156
157
158
159
160
161
162
    project_dir = None
    if len(args) == 1:
        project_dir = op.join(op.curdir, args[0])
        if op.exists(project_dir):
            raise EnvironmentError('Directory %s already exists' % args[0])

    sub_dirs = ['gf_store']
    empty_files = []
163

Marius Isken's avatar
Marius Isken committed
164
    if options.waveform and not options.static:
marius's avatar
wip    
marius committed
165
166
167
168
        config_type = 'waveform'

        sub_dirs += ['data']
        empty_files += ['stations.xml']
Marius Isken's avatar
Marius Isken committed
169
170
171
172
173
        dataset_config = grond.DatasetConfig(
            stations_path='stations.txt',
            events_path='events.txt',
            waveform_paths=['data'])

174
175
176
        target_groups = [grond.WaveformTargetGroup(
            normalisation_family='time_domain',
            path='all',
Marius Isken's avatar
Marius Isken committed
177
178
179
180
            distance_min=10*km,
            distance_max=1000*km,
            channels=['Z', 'R', 'T'],
            interpolation='multilinear',
181
            store_id='gf_store',
182
            misfit_config=grond.WaveformMisfitConfig(
Marius Isken's avatar
Marius Isken committed
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
                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))
            )

    elif options.static:
marius's avatar
wip    
marius committed
208
209
210
        config_type = 'static'

        sub_dirs += ['scenes']
Marius Isken's avatar
Marius Isken committed
211
        dataset_config = grond.DatasetConfig(
212
213
            events_path='events.txt',
            kite_scene_paths=['scenes'],
Marius Isken's avatar
Marius Isken committed
214
215
            )

216
217
218
        target_groups = [grond.SatelliteTargetGroup(
            normalisation_family='insar_target',
            path='all',
Marius Isken's avatar
Marius Isken committed
219
            interpolation='multilinear',
220
            store_id='gf_store',
221
            kite_scenes=['*all'],
222
223
224
225
226
227
228
229
230
            misfit_config=grond.SatelliteMisfitConfig(
                use_weight_focal=False,
                optimize_orbital_ramp=True,
                ranges={
                    'offset': '-0.5 .. 0.5',
                    'ramp_north': '-1e-4 .. 1e4',
                    'ramp_east': '-1e-4 .. 1e4'
                    }
                ))]
Marius Isken's avatar
Marius Isken committed
231
232
233
234
235
236
237
238
239
240
241
242
243
244

        problem_config = grond.RectangularProblemConfig(
            name_template='rect_source',
            ranges=dict(
                north_shift=Range(-20*km, 20*km),
                east_shift=Range(-20*km, 20*km),
                depth=Range(0*km, 10*km),
                length=Range(20*km, 40*km),
                width=Range(5*km, 12*km),
                dip=Range(20, 70),
                strike=Range(0, 180),
                rake=Range(0, 90),
                slip=Range(1, 3))
            )
Sebastian Heimann's avatar
Sebastian Heimann committed
245

246
247
    engine_config = grond.EngineConfig(
        gf_store_superdirs=['.'])
Sebastian Heimann's avatar
Sebastian Heimann committed
248
249

    config = grond.Config(
250
        rundir_template=op.join(op.abspath(op.curdir), 'rundir'),
Sebastian Heimann's avatar
Sebastian Heimann committed
251
        dataset_config=dataset_config,
252
        target_groups=target_groups,
253
254
255
256
257
258
259
260
261
262
263
264
265
        problem_config=problem_config,
        engine_config=engine_config)

    events = '''name = 2011-myanmar
time = 2011-03-24 13:55:12.010
latitude = 20.687
longitude = 99.822
magnitude = 6.9
moment = 1.9228e+19
depth = 8000
region = Myanmar
--------------------------------------------'''

marius's avatar
wip    
marius committed
266
267
268
    if project_dir is not None:
        logger.info('Creating empty %s project in folder %s'
                    % (config_type, args[0]))
269
270

        def p(fn):
marius's avatar
wip    
marius committed
271
            return op.join(project_dir, fn)
272

marius's avatar
wip    
marius committed
273
274
275
        os.mkdir(op.abspath(project_dir))
        for d in sub_dirs:
            os.mkdir(p(d))
276
277
278
279
280

        with open(p('config.yml'), 'w') as cf:
            cf.write(str(config))
        with open(p('events.txt'), 'w') as ef:
            ef.write(events)
Sebastian Heimann's avatar
Sebastian Heimann committed
281

marius's avatar
wip    
marius committed
282
283
284
285
        for fn in empty_files:
            open(p(fn), 'w').close()
    else:
        print config
Sebastian Heimann's avatar
Sebastian Heimann committed
286
287


Sebastian Heimann's avatar
Sebastian Heimann committed
288
289
290
291
292
293
294
295
296
297
298
def command_events(args):
    def setup(parser):
        pass

    parser, options, args = cl_parse('events', args, setup)
    if len(args) != 1:
        help_and_die(parser, 'missing arguments')

    config_path = args[0]
    config = grond.read_config(config_path)

299
    print 'Available Events:'
Sebastian Heimann's avatar
Sebastian Heimann committed
300
    for event_name in grond.get_event_names(config):
301
        print '* %s' % event_name
Sebastian Heimann's avatar
Sebastian Heimann committed
302
303


Sebastian Heimann's avatar
Sebastian Heimann committed
304
305
def command_check(args):
    def setup(parser):
306
307
308
309
310
        parser.add_option(
            '--target-ids', dest='target_string_ids', metavar='TARGET_IDS',
            help='process only selected targets. TARGET_IDS is a '
                 'comma-separated list of target IDs. Target IDs have the '
                 'form SUPERGROUP.GROUP.NETWORK.STATION.LOCATION.CHANNEL.')
Sebastian Heimann's avatar
Sebastian Heimann committed
311

Sebastian Heimann's avatar
Sebastian Heimann committed
312
313
        parser.add_option(
            '--plot', dest='show_plot', action='store_true',
314
315
            help='plot sample synthetics and data.')

316
317
318
319
        parser.add_option(
            '--waveforms', dest='show_waveforms', action='store_true',
            help='show raw, restituted, projected, and processed waveforms')

320
321
322
323
324
325
        parser.add_option(
            '--nrandom', dest='n_random_synthetics', metavar='N', type='int',
            default=10,
            help='set number of random synthetics to forward model (default: '
                 '10). If set to zero, create synthetics for the reference '
                 'solution.')
Sebastian Heimann's avatar
Sebastian Heimann committed
326

Sebastian Heimann's avatar
Sebastian Heimann committed
327
    parser, options, args = cl_parse('check', args, setup)
328
329
    if len(args) < 2:
        help_and_die(parser, 'missing arguments')
Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
330

Sebastian Heimann's avatar
Sebastian Heimann committed
331
    config_path = args[0]
332
333
    event_names = args[1:]

Sebastian Heimann's avatar
Sebastian Heimann committed
334
335
    config = grond.read_config(config_path)

336
337
338
339
    target_string_ids = None
    if options.target_string_ids:
        target_string_ids = options.target_string_ids.split(',')

Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
340
341
    grond.check(
        config,
342
        event_names=event_names,
Sebastian Heimann's avatar
Sebastian Heimann committed
343
        target_string_ids=target_string_ids,
344
        show_plot=options.show_plot,
345
        show_waveforms=options.show_waveforms,
346
        n_random_synthetics=options.n_random_synthetics)
Sebastian Heimann's avatar
Sebastian Heimann committed
347
348


Sebastian Heimann's avatar
Sebastian Heimann committed
349
350
351
352
353
354
355
356
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
357
358
359
        parser.add_option(
            '--parallel', dest='nparallel', type='int', default=1,
            help='set number of events to process in parallel')
Marius Isken's avatar
Marius Isken committed
360
361
362
363
        parser.add_option(
            '--baraddur', dest='baraddur', default=False,
            action='store_true',
            help='start the Barad-dur plotting server')
Sebastian Heimann's avatar
Sebastian Heimann committed
364
365

    parser, options, args = cl_parse('go', args, setup)
366
367
368
369
370
371
372
373
374
375
376
377

    if len(args) == 1:
        config_path = args[0]
        config = grond.read_config(config_path)

        print 'Available Events:'
        for event_name in grond.get_event_names(config):
            print '* %s' % event_name
        print '\n'

        help_and_die(parser, 'missing arguments')

378
379
    if len(args) < 2:
        help_and_die(parser, 'missing arguments')
Sebastian Heimann's avatar
Sebastian Heimann committed
380
381

    config_path = args[0]
382
383
    event_names = args[1:]

Sebastian Heimann's avatar
Sebastian Heimann committed
384
385
386
387
388
389
    config = grond.read_config(config_path)
    if options.status == 'quiet':
        status = ()
    else:
        status = tuple(options.status.split(','))

Marius Isken's avatar
Marius Isken committed
390
391
392
393
394
    if options.baraddur:
        from grond.baraddur import BaraddurProcess
        baraddur = BaraddurProcess(project_dir=op.abspath(op.curdir))
        baraddur.start()

Sebastian Heimann's avatar
Sebastian Heimann committed
395
396
    grond.go(
        config,
Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
397
        event_names=event_names,
Sebastian Heimann's avatar
Sebastian Heimann committed
398
399
400
        force=options.force,
        status=status,
        nparallel=options.nparallel)
Sebastian Heimann's avatar
Sebastian Heimann committed
401

Marius Isken's avatar
Marius Isken committed
402
403
404
405
406
    if options.baraddur:
        logger.info('Grond finished processing %d events. '
                    'Ctrl+C to kill Barad-dur')
        baraddur.join()

Sebastian Heimann's avatar
Sebastian Heimann committed
407
408

def command_forward(args):
Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
409
    def setup(parser):
410
        pass
Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
411
412

    parser, options, args = cl_parse('forward', args, setup)
413
414
    if len(args) < 1:
        help_and_die(parser, 'missing arguments')
Sebastian Heimann's avatar
Sebastian Heimann committed
415

416
    event_names = args[1:]
Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
417

Sebastian Heimann's avatar
Sebastian Heimann committed
418
419
420
    if not event_names:
        help_and_die(parser, 'no event names given')

421
    run_path = args[0]
Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
422
423
424
    grond.forward(
        run_path,
        event_names=event_names)
Sebastian Heimann's avatar
Sebastian Heimann committed
425
426
427
428
429
430
431
432
433
434


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
435
436
        parser.add_option(
            '--weed', dest='weed', type=int, default=0,
437
438
439
440
441
442
443
444
445
446
447
            help='weed out bootstrap samples with bad global performance. '
                 '0: no weeding (default), '
                 '1: only bootstrap chains where all NEACH best samples '
                 'global misfit is less than the global average misfit of all '
                 'NEACH best in all chains plus one standard deviation are '
                 'included in the harvest ensemble, '
                 '2: same as 1 but additionally individual samples are '
                 'removed if their global misfit is greater than the global '
                 'average misfit of all NEACH best in all chains, '
                 '3: harvesting is done on the global chain only, bootstrap '
                 'chains are excluded')
Sebastian Heimann's avatar
Sebastian Heimann committed
448
449
450
451
452
453

    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
454
455
456
457
458
    grond.harvest(
        run_path,
        force=options.force,
        nbest=options.neach,
        weed=options.weed)
Sebastian Heimann's avatar
Sebastian Heimann committed
459
460
461


def command_plot(args):
462
463
464
465
466
467
468
469
470
471
472

    def setup(parser):
        parser.add_option(
            '--save', dest='save', action='store_true', default=False,
            help='save figures to files')

        parser.add_option(
            '--format', '--formats', dest='formats', default='pdf',
            help='comma-separated list of ouptut formats (default: pdf)')

        parser.add_option(
473
474
            '--dpi', '--dpi', dest='dpi', type=float, default=120.,
            help='DPI setting for raster formats (default=120)')
475

476
477
478
479
480
481
482
483
484
    # plotnames_avail = plot.available_plotnames()
    # made explicit to avoid import of pyplot before backend can be chosen
    plotnames_avail = [
        'bootstrap',
        'sequence',
        'contributions',
        'jointpar',
        'hudson',
        'fits',
485
        'fits_statics',
486
487
        'solution',
        'location']
488
489
490
491
492
493
494

    details = '''Available <plotnames> are: %s, or "all". Multiple plots are
selected by specifying a comma-separated list.''' % (
        ', '.join('"%s"' % x for x in plotnames_avail))

    parser, options, args = cl_parse('plot', args, setup, details)

Sebastian Heimann's avatar
Sebastian Heimann committed
495
496
497
    if len(args) != 2:
        help_and_die(parser, 'two arguments required')

498
499
500
501
502
503
    if args[0] == 'all':
        plotnames = plotnames_avail
    else:
        plotnames = args[0].split(',')

    formats = options.formats.split(',')
Sebastian Heimann's avatar
Sebastian Heimann committed
504
    dirname = args[1]
505

506
507
508
509
510
511
    if options.save:
        import matplotlib
        matplotlib.use('Agg')

    from grond import plot

512
513
514
515
516
517
518
    try:
        plot.plot_result(
            dirname, plotnames,
            save=options.save, formats=formats, dpi=options.dpi)

    except grond.GrondError, e:
        die(str(e))
Sebastian Heimann's avatar
Sebastian Heimann committed
519
520


Marius Isken's avatar
Marius Isken committed
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
def command_baraddur(args):
    from grond.baraddur import Baraddur, BaraddurConfig
    import signal

    def setup(parser):
        parser.add_option(
            '--address', dest='address', default='*',
            help='Address listening on, default all \'*\'')
        parser.add_option(
            '--port', dest='port', type='int', default=8080,
            help='Port to listen on, default 8080')

    parser, options, args = cl_parse('baraddur', args, setup)

    config = BaraddurConfig(
        project_dir=op.abspath(op.curdir),
        hosts=options.address,
        port=options.port)

    baraddur = Baraddur(config=config)
    signal.signal(signal.SIGINT, baraddur.stop)

    baraddur.start()


Sebastian Heimann's avatar
Sebastian Heimann committed
546
547
def command_export(args):

Sebastian Heimann's avatar
Sebastian Heimann committed
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
    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
585
    else:
Sebastian Heimann's avatar
Sebastian Heimann committed
586
587
588
589
590
591
592
593
594
595
596
597
        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
598
599


600
601
602
def command_qc_polarization(args):

    def setup(parser):
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
        parser.add_option(
            '--time-factor', dest='time_factor', type=float,
            metavar='NUMBER',
            default=0.5,
            help='set duration to extract before and after synthetic P phase '
                 'arrival, relative to 1/fmin. fmin is taken from the '
                 'selected target group in the config file (default=%default)')
        parser.add_option(
            '--distance-min', dest='distance_min', type=float,
            metavar='NUMBER',
            help='minimum event-station distance [m]')
        parser.add_option(
            '--distance-max', dest='distance_max', type=float,
            metavar='NUMBER',
            help='maximum event-station distance [m]')
        parser.add_option(
            '--depth-min', dest='depth_min', type=float,
            metavar='NUMBER',
            help='minimum station depth [m]')
        parser.add_option(
            '--depth-max', dest='depth_max', type=float,
            metavar='NUMBER',
            help='maximum station depth [m]')
        parser.add_option(
            '--picks', dest='picks_filename',
            metavar='FILENAME',
            help='add file with P picks in Snuffler marker format')
        parser.add_option(
            '--save', dest='output_filename',
            metavar='FILENAME.FORMAT',
            help='save output to file FILENAME.FORMAT')
        parser.add_option(
            '--dpi', dest='output_dpi', type=float, default=120.,
            metavar='NUMBER',
            help='DPI setting for raster formats (default=120)')
638
639
640
641
642

    parser, options, args = cl_parse('qc-polarization', args, setup)
    if len(args) != 3:
        help_and_die(parser, 'missing arguments')

643
644
645
646
647
648
    if options.output_filename:
        import matplotlib
        matplotlib.use('Agg')

    import grond.qc

649
650
651
652
653
654
655
656
    config_path, event_name, target_config_name = args

    config = grond.read_config(config_path)

    ds = config.get_dataset(event_name)

    engine = config.engine_config.get_engine()

657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
    nsl_to_time = None
    if options.picks_filename:
        markers = marker.load_markers(options.picks_filename)
        marker.associate_phases_to_events(markers)

        nsl_to_time = {}
        for m in markers:
            if isinstance(m, marker.PhaseMarker):
                ev = m.get_event()
                if ev is not None and ev.name == event_name:
                    nsl_to_time[m.one_nslc()[:3]] = m.tmin

        if not nsl_to_time:
            help_and_die(
                parser,
                'no markers associated with event "%s" found in file "%s"' % (
                    event_name, options.picks_filename))

675
676
677
678
679
680
681
682
683
684
685
686
687
    target_config_names_avail = []
    for target_config in config.target_configs:
        name = '%s.%s' % (target_config.super_group, target_config.group or '')
        if name == target_config_name:
            imc = target_config.inner_misfit_config
            fmin = imc.fmin
            fmax = imc.fmax
            ffactor = imc.ffactor

            store = engine.get_store(target_config.store_id)
            timing = '{cake:P|cake:p|cake:P\\|cake:p\\}'

            grond.qc.polarization(
688
689
690
691
692
693
694
695
696
                ds, store, timing, fmin=fmin, fmax=fmax, ffactor=ffactor,
                time_factor=options.time_factor,
                distance_min=options.distance_min,
                distance_max=options.distance_max,
                depth_min=options.depth_min,
                depth_max=options.depth_max,
                nsl_to_time=nsl_to_time,
                output_filename=options.output_filename,
                output_dpi=options.output_dpi)
697
698
699
700
701
702
703
704
705

            return

        target_config_names_avail.append(name)

        die('no target_config named "%s" found. Available: %s' % (
            target_config_name, ', '.join(target_config_names_avail)))


Sebastian Heimann's avatar
Sebastian Heimann committed
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
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)