1# http://pyrocko.org - GPLv3
2#
3# The Pyrocko Developers, 21st Century
4# ---|P------/S----------~Lg----------
5from __future__ import absolute_import, division, print_function
7import os.path as op
9from pyrocko import moment_tensor
10from pyrocko.guts import Timestamp, Float, Int, Bool, String, load_all
12from ..base import LocationGenerator
13from ..error import ScenarioError
15km = 1e3
16guts_prefix = 'pf.scenario'
19class SourceGenerator(LocationGenerator):
21 nevents = Int.T(default=2)
22 avoid_water = Bool.T(
23 default=False,
24 help='Avoid sources offshore under the ocean / lakes.')
26 time_min = Timestamp.T(default=Timestamp.D('2017-01-01 00:00:00'))
27 time_max = Timestamp.T(default=Timestamp.D('2017-01-03 00:00:00'))
29 magnitude_min = Float.T(
30 default=4.0,
31 help='minimum moment magnitude')
32 magnitude_max = Float.T(
33 optional=True,
34 help='if set, maximum moment magnitude for a uniform distribution. '
35 'If set to ``None``, magnitudes are drawn using a '
36 'Gutenberg-Richter distribution, see :gattr:`b_value`.')
37 b_value = Float.T(
38 optional=True,
39 help='b-value for Gutenberg-Richter magnitude distribution. If unset, '
40 'a value of 1 is assumed.')
42 source_file = String.T(
43 optional=True,
44 help='Path to source file. Sources are used as scenario events')
46 def __init__(self, *args, **kwargs):
47 super(SourceGenerator, self).__init__(*args, **kwargs)
48 if self.b_value is not None and self.magnitude_max is not None:
49 raise ScenarioError(
50 '%s: b_value and magnitude_max are mutually exclusive.'
51 % self.__class__.__name__)
53 def draw_magnitude(self, rstate):
54 if self.b_value is None and self.magnitude_max is None:
55 b_value = 1.0
56 else:
57 b_value = self.b_value
59 if b_value is None:
60 return rstate.uniform(self.magnitude_min, self.magnitude_max)
61 else:
62 return moment_tensor.rand_to_gutenberg_richter(
63 rstate.rand(), b_value, magnitude_min=self.magnitude_min)
65 def get_sources(self):
66 sources = []
68 if self.source_file is not None:
69 sources = load_all(filename=self.source_file)
70 self.nevents = len(sources)
72 for ievent in range(self.nevents):
73 sources[ievent].name = 'scenario_ev%03d' % (ievent + 1)
75 for ievent in range(self.nevents):
76 src = self.get_source(ievent)
77 src.name = 'scenario_ev%03d' % (ievent + 1)
78 sources.append(src)
80 return sources
82 def ensure_data(self, path):
83 fn_sources = op.join(path, 'sources.yml')
84 if not op.exists(fn_sources):
85 with open(fn_sources, 'w') as f:
86 for src in self.get_sources():
87 f.write(src.dump())
89 fn_events = op.join(path, 'events.txt')
90 if not op.exists(fn_events):
91 with open(fn_events, 'w') as f:
92 for isrc, src in enumerate(self.get_sources()):
93 f.write(src.pyrocko_event().dump())
95 def add_map_artists(self, automap):
96 pass