-
Notifications
You must be signed in to change notification settings - Fork 42
/
beat.py
2465 lines (2031 loc) · 85.1 KB
/
beat.py
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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
175
176
177
178
179
180
181
182
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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
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
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
312
313
314
315
316
317
318
319
320
321
322
323
324
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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
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
546
547
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
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
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
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
import os
from glob import glob
from os.path import basename
from os.path import join as pjoin
# disable internal blas parallelisation as we parallelise over chains
nthreads = os.environ.get("NUM_THREADS", "1")
os.environ["OMP_NUM_THREADS"] = nthreads
os.environ["NUMEXPR_NUM_THREADS"] = nthreads
os.environ["OPENBLAS_NUM_THREADS"] = nthreads
os.environ["MKL_NUM_THREADS"] = nthreads
os.environ["VECLIB_MAXIMUM_THREADS"] = nthreads
import copy
import logging
import shutil
import sys
from collections import OrderedDict
from optparse import OptionParser
from numpy import array, atleast_2d, floor, zeros, cumsum
from pyrocko import model, util
from pyrocko.gf import LocalEngine
from pyrocko.guts import Dict, dump, load
from pyrocko.trace import snuffle
from tqdm import tqdm
from beat import config as bconfig
from beat import heart, inputf, plotting, utility
from beat.backend import backend_catalog, extract_bounds_from_summary, thin_buffer
from beat.config import dist_vars, ffi_mode_str, geometry_mode_str, bem_mode_str
from beat.info import version
from beat.models import Stage, estimate_hypers, load_model, sample
from beat.sampler.pt import SamplingHistory
from beat.sampler.smc import sample_factor_final_stage
from beat.sources import MTQTSource, MTSourceWithMagnitude
from beat.utility import list2string, string2slice
logger = logging.getLogger("beat")
km = 1000.0
def d2u(d):
return {k.replace("-", "_"): v for (k, v) in d.items()}
subcommand_descriptions = {
"init": "create a new EQ model project, use only event"
" name to skip catalog search",
"import": "import data or results, from external format or "
"modeling results, respectively",
"update": "update configuration file",
"sample": "sample the solution space of the problem",
"build_gfs": "build GF stores",
"clone": "clone EQ model project into new directory",
"plot": "plot specified setups or results",
"check": "check setup specific requirements",
"summarize": "collect results and create statistics",
"export": "export waveforms and displacement maps of" " specific solution(s)",
}
subcommand_usages = {
"init": 'init <event_name> <event_date "YYYY-MM-DD"> ' "[options]",
"import": "import <event_name> [options]",
"update": "update <event_name> [options]",
"sample": "sample <event_name> [options]",
"build_gfs": "build_gfs <event_name> [options]",
"clone": "clone <event_name> <cloned_event_name> [options]",
"plot": "plot <event_name> <plot_type> [options]",
"check": "check <event_name> [options]",
"summarize": "summarize <event_name> [options]",
"export": "export <event_name> [options]",
}
subcommands = list(subcommand_descriptions.keys())
subcommand_descriptions["version"] = version
program_name = "beat"
usage = (
program_name
+ """ <subcommand> <arguments> ... [options]
BEAT: Bayesian earthquake analysis tool
Version %(version)s
author: Hannes Vasyura-Bathke
email: [email protected]
Subcommands:
init %(init)s
clone %(clone)s
import %(import)s
update %(update)s
build_gfs %(build_gfs)s
sample %(sample)s
summarize %(summarize)s
export %(export)s
plot %(plot)s
check %(check)s
To get further help and a list of available options for any subcommand run:
beat <subcommand> --help
"""
% d2u(subcommand_descriptions)
)
nargs_dict = {
"init": 2,
"clone": 2,
"plot": 2,
"import": 1,
"update": 1,
"build_gfs": 1,
"sample": 1,
"check": 1,
"summarize": 1,
"export": 1,
}
mode_choices = [geometry_mode_str, ffi_mode_str, bem_mode_str]
supported_geodetic_formats = ["matlab", "ascii", "kite"]
supported_geodetic_types = ["SAR", "GNSS"]
supported_samplers = ["SMC", "Metropolis", "PT"]
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 get_project_directory(args, options, nargs=1, popflag=False):
largs = len(args)
if largs == nargs - 1 or largs != nargs:
return os.getcwd()
name = args.pop(0) if popflag else args[0]
return pjoin(os.path.abspath(options.main_path), name)
def process_common_options(options, project_dir):
utility.setup_logging(project_dir, options.loglevel, logfilename="BEAT_log.txt")
def die(message, err=""):
sys.exit("%s: error: %s \n %s" % (program_name, message, err))
def cl_parse(command, args, setup=None, details=None):
usage = subcommand_usages[command]
descr = subcommand_descriptions[command]
if isinstance(usage, str):
usage = [usage]
susage = f"{program_name} {usage[0]}"
for s in usage[1:]:
susage += "\n%s%s %s" % (" " * 7, program_name, s)
description = descr[0].upper() + descr[1:] + "."
if details:
description = f"{description} {details}"
parser = OptionParser(usage=susage, description=description)
if setup:
setup(parser)
add_common_options(parser)
(options, args) = parser.parse_args(args)
project_dir = get_project_directory(args, options, nargs_dict[command])
if command != "init":
process_common_options(options, project_dir)
return parser, options, args
def list_callback(option, opt, value, parser):
out = [ival.lstrip() for ival in value.split(",")]
if out == [""]:
out = []
setattr(parser.values, option.dest, out)
def list_callback_int(option, opt, value, parser):
out = [int(ival.lstrip()) for ival in value.split(",")]
setattr(parser.values, option.dest, out)
def get_sampled_slip_variables(config):
slip_varnames = config.problem_config.get_slip_variables()
rvs, fixed_rvs = config.problem_config.get_random_variables()
varnames = list(set(slip_varnames).intersection(set(list(rvs.keys()))))
return varnames
def command_init(args):
command_str = "init"
def setup(parser):
parser.add_option(
"--min_mag",
dest="min_mag",
type=float,
default=6.0,
help="Minimum Mw for event, for catalog search." ' Default: "6.0"',
)
parser.add_option(
"--main_path",
dest="main_path",
type="string",
default="./",
help="Main path (absolute) for creating directory structure."
" Default: current directory ./",
)
parser.add_option(
"--datatypes",
default=["geodetic"],
type="string",
action="callback",
callback=list_callback,
help='Datatypes to include in the setup; "geodetic, seismic".',
)
parser.add_option(
"--mode",
dest="mode",
choices=mode_choices,
default=geometry_mode_str,
help='Inversion problem to solve; %s Default: "%s"'
% (list2string(mode_choices), geometry_mode_str),
)
parser.add_option(
"--source_types",
dest="source_types",
type="string",
action="callback",
callback=list_callback,
default=["RectangularSource"],
help="List of source types to solve for. Can be any combination of the "
"following for mode: geometry - %s; bem - %s; "
"Default: 'RectangularSource'"
% (
list2string(bconfig.source_catalog.keys()),
list2string(bconfig.bem_source_catalog.keys()),
),
)
parser.add_option(
"--n_sources",
dest="n_sources",
type="string",
default=1,
action="callback",
callback=list_callback_int,
help="List of integer numbers of sources per source type to invert for. Default: [1]",
)
parser.add_option(
"--waveforms",
type="string",
action="callback",
callback=list_callback,
default=["any_P", "any_S"],
help='Waveforms to include in the setup; "any_P, any_S, slowest".',
)
parser.add_option(
"--sampler",
dest="sampler",
choices=supported_samplers,
default="SMC",
help="Sampling algorithm to sample the solution space of the"
" general problem; %s. "
'Default: "SMC"' % list2string(supported_samplers),
)
parser.add_option(
"--hyper_sampler",
dest="hyper_sampler",
type="string",
default="Metropolis",
help="Sampling algorithm to sample the solution space of the"
' hyperparameters only; So far only "Metropolis" supported.'
'Default: "Metropolis"',
)
parser.add_option(
"--use_custom",
dest="use_custom",
action="store_true",
help="If set, a slot for a custom velocity model is being created"
" in the configuration file.",
)
parser.add_option(
"--individual_gfs",
dest="individual_gfs",
action="store_true",
help="If set, Green's Function stores will be created individually"
" for each station!",
)
parser, options, args = cl_parse("init", args, setup=setup)
la = len(args)
if la > 2 or la < 1:
logger.error("Wrong number of input arguments!")
parser.print_help()
sys.exit(1)
if la == 2:
name, date = args
elif la == 1:
logger.info("Doing no catalog search for event information!")
name = args[0]
date = None
project_dir = pjoin(os.path.abspath(options.main_path), name)
util.ensuredir(project_dir)
process_common_options(options, project_dir)
return bconfig.init_config(
name,
date,
main_path=options.main_path,
min_magnitude=options.min_mag,
datatypes=options.datatypes,
mode=options.mode,
source_types=options.source_types,
n_sources=options.n_sources,
waveforms=options.waveforms,
sampler=options.sampler,
hyper_sampler=options.hyper_sampler,
use_custom=options.use_custom,
individual_gfs=options.individual_gfs,
)
def command_import(args):
from pyrocko import io
command_str = "import"
data_formats = io.allowed_formats("load")[2::]
def setup(parser):
parser.add_option(
"--main_path",
dest="main_path",
type="string",
default="./",
help="Main path (absolute) leading to folders of events that"
' have been created by "init".'
" Default: current directory: ./",
)
parser.add_option(
"--results",
dest="results",
type="string",
default="",
help="Import results from previous modeling step" " of given project path",
)
parser.add_option(
"--datatypes",
default=["geodetic"],
type="string",
action="callback",
callback=list_callback,
help='Datatypes to import; "geodetic, seismic".',
)
parser.add_option(
"--geodetic_format",
dest="geodetic_format",
type="string",
default=["kite"],
action="callback",
callback=list_callback,
help='Data format to be imported; %s Default: "kite"'
% list2string(supported_geodetic_formats),
)
parser.add_option(
"--seismic_format",
dest="seismic_format",
default="mseed",
choices=data_formats,
help="Data format to be imported;"
'Default: "mseed"; Available: %s' % list2string(data_formats),
)
parser.add_option(
"--mode",
dest="mode",
choices=mode_choices,
default=geometry_mode_str,
help='Inversion problem results to import; %s Default: "%s"'
% (list2string(mode_choices), geometry_mode_str),
)
parser.add_option(
"--import_from_mode",
dest="import_from_mode",
choices=mode_choices,
default=ffi_mode_str,
help="The mode to import estimation results"
' from; %s Default: "%s"' % (list2string(mode_choices), ffi_mode_str),
)
parser.add_option(
"--force",
dest="force",
action="store_true",
help="Overwrite existing files",
)
parser, options, args = cl_parse(command_str, args, setup=setup)
project_dir = get_project_directory(args, options, nargs_dict[command_str])
if not options.results:
c = bconfig.load_config(project_dir, options.mode)
if "seismic" in options.datatypes:
sc = c.seismic_config
logger.info("Attempting to import seismic data from %s" % sc.datadir)
seismic_outpath = pjoin(c.project_dir, bconfig.seismic_data_name)
if not os.path.exists(seismic_outpath) or options.force:
# TODO datahandling multi event based ...
stations = model.load_stations(pjoin(sc.datadir, "stations.txt"))
if options.seismic_format == "autokiwi":
data_traces = inputf.load_data_traces(
datadir=sc.datadir, stations=stations, divider="-"
)
elif options.seismic_format in data_formats:
data_traces = inputf.load_data_traces(
datadir=sc.datadir,
stations=stations,
divider=".",
data_format=options.seismic_format,
)
else:
raise TypeError(
"Format: %s not implemented yet." % options.seismic_format
)
logger.info("Rotating traces to RTZ wrt. event!")
data_traces = inputf.rotate_traces_and_stations(
data_traces, stations, c.event
)
logger.info("Pickle seismic data to %s" % seismic_outpath)
utility.dump_objects(seismic_outpath, outlist=[stations, data_traces])
logger.info(
"Successfully imported traces for" " %i stations!" % len(stations)
)
else:
logger.info("%s exists! Use --force to overwrite!" % seismic_outpath)
if "geodetic" in options.datatypes:
gc = c.geodetic_config
geodetic_outpath = pjoin(c.project_dir, bconfig.geodetic_data_name)
if not os.path.exists(geodetic_outpath) or options.force:
gtargets = []
for typ, config in gc.types.items():
logger.info(
"Attempting to import geodetic data for typ %s from %s"
% (typ, config.datadir)
)
if typ == "SAR":
if "matlab" in options.geodetic_format:
gtargets.extend(
inputf.load_SAR_data(config.datadir, config.names)
)
elif "kite" in options.geodetic_format:
gtargets.extend(config.load_data())
else:
raise ImportError(
"Format %s not implemented yet for SAR data."
% options.geodetic_format
)
elif typ == "GNSS":
if "ascii" in options.geodetic_format:
targets = config.load_data(campaign=False)
gtargets.extend(targets)
else:
raise ImportError(
"Format %s not implemented yet for GNSS data."
% options.geodetic_format
)
else:
raise TypeError(
'Geodetic datatype "%s" is not supported! '
"Supported types are: %s "
% (typ, list2string(supported_geodetic_types))
)
if len(gtargets) > 0:
logger.info("Pickleing geodetic data to %s" % geodetic_outpath)
utility.dump_objects(geodetic_outpath, outlist=gtargets)
else:
raise ImportError(
"Data import failed-found no data! " "Please check filepaths!"
)
else:
logger.info("%s exists! Use --force to overwrite!" % geodetic_outpath)
else: # import results
from pandas import read_csv
logger.info(
"Attempting to load results with mode %s to config_%s.yaml"
" from directory: %s"
% (options.import_from_mode, options.mode, options.results)
)
c = bconfig.load_config(project_dir, options.mode)
_, ending = os.path.splitext(options.results)
if not ending:
# load results from mode optimization
problem = load_model(
options.results, options.import_from_mode, hypers=False, build=False
)
priors = set(list(problem.config.problem_config.priors.keys()))
rvs = set(problem.varnames)
source_params = list(priors.intersection(rvs))
logger.info(
"Importing priors for variables:" " %s" % list2string(source_params)
)
stage = Stage(
homepath=problem.outfolder,
backend=problem.config.sampler_config.backend,
)
stage.load_results(
varnames=problem.varnames,
model=problem.model,
stage_number=-1,
load="trace",
chains=[-1],
)
point = plotting.get_result_point(stage.mtrace, "max")
summarydf = read_csv(pjoin(problem.outfolder, "summary.txt"), sep="\s+")
else:
# load kite model
from kite import sandbox_scene
kite_model = load(filename=options.results)
n_sources = len(kite_model.sources)
reference_sources = bconfig.init_reference_sources(
kite_model.sources,
n_sources,
c.problem_config.source_type,
c.problem_config.stf_type,
event=c.event,
)
if "geodetic" in options.datatypes:
c.geodetic_config.gf_config.reference_sources = reference_sources
if "seismic" in options.datatypes:
c.seismic_config.gf_config.reference_sources = reference_sources
bconfig.dump_config(c)
logger.info("Successfully imported kite model to ffi source geometry!")
sys.exit(1)
# import geodetic hierarchicals
logger.info(
"Importing hierarchicals for "
"datatypes: %s " % list2string(options.datatypes)
)
logger.info("---------------------------------------------\n")
if "geodetic" in options.datatypes:
logger.info("Geodetic datatype listed-importing ...")
gc = problem.composites["geodetic"]
if c.geodetic_config.corrections_config.has_enabled_corrections:
logger.info("Importing correction parameters ...")
new_bounds = OrderedDict()
for var in c.geodetic_config.get_hierarchical_names(
datasets=gc.datasets
):
if var in point:
logger.info("Importing correction for %s" % var)
new_bounds[var] = (point[var], point[var])
else:
logger.warning(
"Correction %s was fixed in previous run!"
" Importing fixed values!" % var
)
tpoint = problem.config.problem_config.get_test_point()
new_bounds[var] = (tpoint[var], tpoint[var])
c.problem_config.set_vars(new_bounds, attribute="hierarchicals")
else:
logger.info("No geodetic corrections enabled, nothing to import!")
else:
logger.info("geodetic datatype not listed-not importing ...")
if "seismic" in options.datatypes:
logger.info("seismic datatype listed-importing ...")
sc = problem.composites["seismic"]
if c.seismic_config.station_corrections:
logger.info("Importing station corrections ...")
new_bounds = OrderedDict()
for wmap in sc.wavemaps:
param = wmap.time_shifts_id
new_bounds[param] = extract_bounds_from_summary(
summarydf, varname=param, shape=(wmap.hypersize,), roundto=0
)
new_bounds[param].append(point[param])
c.problem_config.set_vars(
new_bounds, attribute="hierarchicals", init=True
)
else:
logger.info("No station_corrections enabled, nothing to import.")
else:
logger.info("seismic datatype not listed-not importing ...")
if options.mode == ffi_mode_str:
n_sources = problem.config.problem_config.n_sources
if len(n_sources) != 1:
raise TypeError(
"FFI with more than one source type is not implemented!"
)
if options.import_from_mode == geometry_mode_str:
logger.info("Importing non-linear source geometry results!")
for param in list(point.keys()):
if param not in source_params:
point.pop(param)
point = utility.adjust_point_units(point)
source_points = utility.split_point(point, n_sources_total=n_sources[0])
reference_sources = bconfig.init_reference_sources(
source_points,
n_sources,
c.problem_config.source_types[0],
c.problem_config.stf_type,
event=c.event,
)
if "geodetic" in options.datatypes:
c.geodetic_config.gf_config.reference_sources = reference_sources
if "seismic" in options.datatypes:
c.seismic_config.gf_config.reference_sources = reference_sources
if "seismic" in problem.config.problem_config.datatypes:
new_bounds = {}
for param in ["time"]:
new_bounds[param] = extract_bounds_from_summary(
summarydf, varname=param, shape=(n_sources,), roundto=0
)
new_bounds[param].append(point[param])
c.problem_config.set_vars(new_bounds, attribute="priors")
elif options.import_from_mode == ffi_mode_str:
n_patches = problem.config.problem_config.mode_config.npatches
logger.info("Importing distributed slip results!")
new_bounds = {}
for param in source_params:
if param in dist_vars:
shape = (n_patches,)
else:
shape = (n_sources,)
new_bounds[param] = extract_bounds_from_summary(
summarydf, varname=param, shape=shape, roundto=1
)
new_bounds[param].append(point[param])
c.problem_config.set_vars(new_bounds, attribute="priors")
elif options.mode == geometry_mode_str:
if options.import_from_mode == geometry_mode_str:
# TODO update for n_sources refactoring
n_sources = problem.config.problem_config.n_sources
logger.info("Importing non-linear source geometry results!")
new_source_params = set(list(c.problem_config.priors.keys()))
old_source_params = set(source_params)
common_source_params = list(
new_source_params.intersection(old_source_params)
)
new_bounds = {}
for param in common_source_params:
try:
new_bounds[param] = extract_bounds_from_summary(
summarydf, varname=param, shape=(n_sources,), roundto=0
)
new_bounds[param].append(point[param])
except KeyError:
logger.info(
"Parameter {} was fixed, not importing " "...".format(param)
)
c.problem_config.set_vars(new_bounds, attribute="priors")
elif options.import_from_mode == ffi_mode_str:
err_str = "Cannot import results from %s mode to %s mode!" % (
options.import_from_mode,
options.mode,
)
logger.error(err_str)
raise TypeError(err_str)
bconfig.dump_config(c)
logger.info("Successfully updated config file!")
def command_update(args):
command_str = "update"
def setup(parser):
parser.add_option(
"--main_path",
dest="main_path",
type="string",
default="./",
help="Main path (absolute) leading to folders of events that"
' have been created by "init".'
" Default: current directory: ./",
)
parser.add_option(
"--parameters",
default=["structure"],
type="string",
action="callback",
callback=list_callback,
help='Parameters to update; "structure, hypers, hierarchicals". '
'Default: ["structure"] (config file-structure only)',
)
parser.add_option(
"--mode",
dest="mode",
choices=mode_choices,
default=geometry_mode_str,
help='Inversion problem to solve; %s Default: "%s"'
% (list2string(mode_choices), geometry_mode_str),
)
parser.add_option(
"--diff",
dest="diff",
action="store_true",
help="create diff between normalized old and new versions",
)
parser, options, args = cl_parse(command_str, args, setup=setup)
project_dir = get_project_directory(args, options, nargs_dict[command_str])
config_file_name = "config_" + options.mode + ".yaml"
config_fn = os.path.join(project_dir, config_file_name)
from beat import upgrade
upgrade.upgrade_config_file(config_fn, diff=options.diff, update=options.parameters)
def command_clone(args):
command_str = "clone"
from beat.config import _datatype_choices as datatype_choices
def setup(parser):
parser.add_option(
"--main_path",
dest="main_path",
type="string",
default="./",
help="Main path (absolute) leading to folders of events that"
' have been created by "init".'
" Default: current directory: ./",
)
parser.add_option(
"--datatypes",
default=["geodetic", "seismic"],
type="string",
action="callback",
callback=list_callback,
help='Datatypes to clone; "geodetic, seismic".',
)
parser.add_option(
"--source_types",
dest="source_types",
type="string",
action="callback",
callback=list_callback,
default=[],
help="Source types to replace sources with. Can be any combination of the "
"following for mode: geometry - %s; bem - %s; "
"Default: No replacement!"
% (
list2string(bconfig.source_catalog.keys()),
list2string(bconfig.bem_source_catalog.keys()),
),
)
parser.add_option(
"--mode",
dest="mode",
choices=mode_choices,
default=geometry_mode_str,
help='Inversion problem to solve; %s Default: "%s"'
% (list2string(mode_choices), geometry_mode_str),
)
parser.add_option(
"--copy_data",
dest="copy_data",
action="store_true",
help="If set, the imported data will be copied into the cloned"
" directory.",
)
parser.add_option(
"--sampler",
dest="sampler",
choices=supported_samplers,
default=None,
help="Replace sampling algorithm in config to sample "
"the solution space of the general problem; %s."
' Default: "dont change"' % list2string(supported_samplers),
)
parser, options, args = cl_parse(command_str, args, setup=setup)
if len(args) != 2:
parser.print_help()
sys.exit(1)
name, cloned_name = args
project_dir = get_project_directory(args, options, nargs_dict[command_str])
cloned_dir = pjoin(os.path.dirname(project_dir), cloned_name)
util.ensuredir(cloned_dir)
mode = options.mode
config_fn = pjoin(project_dir, "config_" + mode + ".yaml")
if os.path.exists(config_fn):
logger.info("Cloning %s problem config." % mode)
c = bconfig.load_config(project_dir, mode)
c.name = cloned_name
c.project_dir = cloned_dir
new_datatypes = []
for datatype in datatype_choices:
if datatype in options.datatypes:
if datatype not in c.problem_config.datatypes:
logger.warn(
"Datatype %s to be cloned is not"
" in config! Adding to new config!" % datatype
)
c[datatype + "_config"] = bconfig.datatype_catalog[datatype](
mode=options.mode
)
re_init = True
else:
re_init = False
new_datatypes.append(datatype)
if datatype != "polarity":
files = [datatype + "_data.pkl"]
else:
marker_files = [
basename(fname) for fname in glob(pjoin(project_dir, "*.pf"))
]
files = ["stations.txt"] + marker_files
for file in files:
data_path = pjoin(project_dir, file)
if os.path.exists(data_path) and options.copy_data:
logger.info("Cloning data ... %s " % data_path)
cloned_data_path = pjoin(cloned_dir, file)
logger.info("Cloned data path: %s", cloned_data_path)
shutil.copyfile(data_path, cloned_data_path)
else:
if datatype in c.problem_config.datatypes:
logger.warning(
'Removing datatype "%s" ' "from cloned config!" % datatype
)
c[datatype + "_config"] = None
c.problem_config.datatypes = new_datatypes
if options.copy_data and mode == ffi_mode_str:
ffi_dir_name = pjoin(project_dir, mode)
linear_gf_dir_name = pjoin(ffi_dir_name, bconfig.linear_gf_dir_name)
cloned_ffi_dir_name = pjoin(cloned_dir, mode)
util.ensuredir(cloned_ffi_dir_name)
if os.path.exists(linear_gf_dir_name):
logger.info("FFI mode - attempting to clone linear GF libraries ...")
cloned_linear_gf_dir_name = pjoin(
cloned_ffi_dir_name, bconfig.linear_gf_dir_name
)
if os.path.exists(cloned_linear_gf_dir_name):
logger.warning("Linear GFs exist already! Removing ...")
shutil.rmtree(cloned_linear_gf_dir_name)
shutil.copytree(linear_gf_dir_name, cloned_linear_gf_dir_name)
logger.info("Successfully cloned linear GF libraries.")
if len(options.source_types) == 0:
old_priors = copy.deepcopy(c.problem_config.priors)
new_prior_names = (
c.problem_config.get_variables_mapping().unique_variables_sizes().keys()
)
for prior in new_prior_names:
if prior in list(old_priors.keys()):
c.problem_config.priors[prior] = old_priors[prior]
else:
logger.info('Replacing sources with "%s"' % options.source_types)
c.problem_config.source_types = options.source_types
c.problem_config.init_vars()
c.problem_config.set_decimation_factor()
re_init = False
if re_init:
logger.info(
"Re-initialized priors because of new datatype!"
" Please check prior bounds!"
)
c.problem_config.init_vars()
old_hypers = copy.deepcopy(c.problem_config.hyperparameters)
c.update_hypers()
for hyper in old_hypers.keys():
c.problem_config.hyperparameters[hyper] = old_hypers[hyper]
if options.sampler: