def oldloadf(file): d = {} try: for line in file: if line.lstrip().startswith('#'): continue toks = line.split(' = ', 1) if len(toks) == 2: k, v = toks[0].strip(), toks[1].strip() if k in ('name', 'region', 'catalog', 'magnitude_type'): d[k] = v if k in (('latitude longitude magnitude depth duration ' 'north_shift east_shift ' 'mnn mee mdd mne mnd med strike1 dip1 rake1 ' 'strike2 dip2 rake2 duration').split()): d[k] = float(v) if k == 'time': d[k] = util.str_to_time(v) if k == 'tags': d[k] = [x.strip() for x in v.split(',')] if line.startswith('---'): d['have_separator'] = True break except Exception as e: raise FileParseError(e) if not d: raise EOF() if 'have_separator' in d and len(d) == 1: raise EmptyEvent() mt = None m6 = [d[x] for x in 'mnn mee mdd mne mnd med'.split() if x in d] if len(m6) == 6: mt = moment_tensor.MomentTensor(m=moment_tensor.symmat6(*m6)) else: sdr = [d[x] for x in 'strike1 dip1 rake1'.split() if x in d] if len(sdr) == 3: moment = 1.0 if 'moment' in d: moment = d['moment'] elif 'magnitude' in d: moment = moment_tensor.magnitude_to_moment(d['magnitude']) mt = moment_tensor.MomentTensor(strike=sdr[0], dip=sdr[1], rake=sdr[2], scalar_moment=moment) return (d.get('latitude', 0.0), d.get('longitude', 0.0), d.get('north_shift', 0.0), d.get('east_shift', 0.0), d.get('time', 0.0), d.get('name', ''), d.get('depth', None), d.get('magnitude', None), d.get('magnitude_type', None), d.get('region', None), d.get('catalog', None), mt, d.get('duration', None), d.get('tags', []))
def olddumpf(self, file): file.write('name = %s\n' % self.name) file.write('time = %s\n' % util.time_to_str(self.time)) if self.lat is not None: file.write('latitude = %.12g\n' % self.lat) if self.lon is not None: file.write('longitude = %.12g\n' % self.lon) if self.magnitude is not None: file.write('magnitude = %g\n' % self.magnitude) file.write('moment = %g\n' % moment_tensor.magnitude_to_moment(self.magnitude)) if self.magnitude_type is not None: file.write('magnitude_type = %s\n' % self.magnitude_type) if self.depth is not None: file.write('depth = %.10g\n' % self.depth) if self.region is not None: file.write('region = %s\n' % self.region) if self.catalog is not None: file.write('catalog = %s\n' % self.catalog) if self.moment_tensor is not None: m = self.moment_tensor.m() sdr1, sdr2 = self.moment_tensor.both_strike_dip_rake() file.write(( 'mnn = %g\nmee = %g\nmdd = %g\nmne = %g\nmnd = %g\nmed = %g\n' 'strike1 = %g\ndip1 = %g\nrake1 = %g\n' 'strike2 = %g\ndip2 = %g\nrake2 = %g\n') % ( (m[0, 0], m[1, 1], m[2, 2], m[0, 1], m[0, 2], m[1, 2]) + sdr1 + sdr2)) if self.duration is not None: file.write('duration = %g\n' % self.duration)
def createMT_CLVD(mag): exp = mtm.magnitude_to_moment(mag) # init pyrocko moment tensor cvld_matrix = np.array([[1, 0, 0], [0, 1, 0], [0, 0, -2]]) * exp rotated_matrix = mtm.random_rotation() * cvld_matrix return mtm.MomentTensor(rotated_matrix)
def olddumpf(self, file): file.write('name = %s\n' % self.name) file.write('time = %s\n' % util.time_to_str(self.time)) if self.lat is not None: file.write('latitude = %.12g\n' % self.lat) if self.lon is not None: file.write('longitude = %.12g\n' % self.lon) if self.magnitude is not None: file.write('magnitude = %g\n' % self.magnitude) file.write('moment = %g\n' % moment_tensor.magnitude_to_moment(self.magnitude)) if self.magnitude_type is not None: file.write('magnitude_type = %s\n' % self.magnitude_type) if self.depth is not None: file.write('depth = %.10g\n' % self.depth) if self.region is not None: file.write('region = %s\n' % self.region) if self.catalog is not None: file.write('catalog = %s\n' % self.catalog) if self.moment_tensor is not None: m = self.moment_tensor.m() sdr1, sdr2 = self.moment_tensor.both_strike_dip_rake() file.write( ('mnn = %g\nmee = %g\nmdd = %g\nmne = %g\nmnd = %g\nmed = %g\n' 'strike1 = %g\ndip1 = %g\nrake1 = %g\n' 'strike2 = %g\ndip2 = %g\nrake2 = %g\n') % ((m[0, 0], m[1, 1], m[2, 2], m[0, 1], m[0, 2], m[1, 2]) + sdr1 + sdr2)) if self.duration is not None: file.write('duration = %g\n' % self.duration)
def discretize_basesource(self, store, target=None): times, amplitudes = self.effective_stf_pre().discretize_t( store.config.deltat, self.time) m0 = mtm.magnitude_to_moment(self.magnitude) m6s = self.m6 * m0 return meta.DiscretizedMTSource(m6s=m6s[num.newaxis, :] * amplitudes[:, num.newaxis], **self._dparams_base_repeated(times))
def testMomentGetterSetter(self): m1 = MomentTensor() want_mom = 2E7 m1.moment = want_mom sm2 = m1.scalar_moment() assert(sm2 == m1.moment) assert(abs(sm2 - want_mom) < 1E-8) mag = moment_to_magnitude(want_mom) assert(m1.magnitude == mag) want_mag = 3.5 m1.magnitude = want_mag mom = magnitude_to_moment(want_mag) assert(m1.moment == mom)
def testMomentGetterSetter(self): m1 = MomentTensor() want_mom = 2E7 m1.moment = want_mom sm2 = m1.scalar_moment() assert (sm2 == m1.moment) assert (abs(sm2 - want_mom) < 1E-8) mag = moment_to_magnitude(want_mom) assert (m1.magnitude == mag) want_mag = 3.5 m1.magnitude = want_mag mom = magnitude_to_moment(want_mag) assert (m1.moment == mom)
def testMomentGetterSetter(self): m1 = MomentTensor() want_mom = 2e7 m1.moment = want_mom sm2 = m1.scalar_moment() assert sm2 == m1.moment assert abs(sm2 - want_mom) < 1e-8 mag = moment_to_magnitude(want_mom) assert m1.magnitude == mag want_mag = 3.5 m1.magnitude = want_mag mom = magnitude_to_moment(want_mag) assert m1.moment == mom
def get_source(self, x): d = self.get_parameter_dict(x) rm6 = num.array([d.rmnn, d.rmee, d.rmdd, d.rmne, d.rmnd, d.rmed], dtype=num.float) m0 = mtm.magnitude_to_moment(d.magnitude) m6 = rm6 * m0 p = {} for k in self.base_source.keys(): if k in d: p[k] = float(self.ranges[k].make_relative( self.base_source[k], d[k])) source = self.base_source.clone(m6=m6, stf=self.get_stf(d), **p) return source
def olddumpf(self, file): if self.extras: raise EventExtrasDumpError( 'Event user-defined extras attributes cannot be dumped in the ' '"basic" event file format. Use ' 'dump_events(..., format="yaml").') file.write('name = %s\n' % self.name) file.write('time = %s\n' % util.time_to_str(self.time)) if self.lat != 0.0: file.write('latitude = %.12g\n' % self.lat) if self.lon != 0.0: file.write('longitude = %.12g\n' % self.lon) if self.north_shift != 0.0: file.write('north_shift = %.12g\n' % self.north_shift) if self.east_shift != 0.0: file.write('east_shift = %.12g\n' % self.east_shift) if self.magnitude is not None: file.write('magnitude = %g\n' % self.magnitude) file.write('moment = %g\n' % moment_tensor.magnitude_to_moment(self.magnitude)) if self.magnitude_type is not None: file.write('magnitude_type = %s\n' % self.magnitude_type) if self.depth is not None: file.write('depth = %.10g\n' % self.depth) if self.region is not None: file.write('region = %s\n' % self.region) if self.catalog is not None: file.write('catalog = %s\n' % self.catalog) if self.moment_tensor is not None: m = self.moment_tensor.m() sdr1, sdr2 = self.moment_tensor.both_strike_dip_rake() file.write( ('mnn = %g\nmee = %g\nmdd = %g\nmne = %g\nmnd = %g\nmed = %g\n' 'strike1 = %g\ndip1 = %g\nrake1 = %g\n' 'strike2 = %g\ndip2 = %g\nrake2 = %g\n') % ((m[0, 0], m[1, 1], m[2, 2], m[0, 1], m[0, 2], m[1, 2]) + sdr1 + sdr2)) if self.duration is not None: file.write('duration = %g\n' % self.duration) if self.tags: file.write('tags = %s\n' % ', '.join(self.tags))
def get_source(self, ievent): rstate = self.get_rstate(ievent) time = rstate.uniform(self.time_min, self.time_max) lat, lon = self.get_latlon(ievent) depth = rstate.uniform(self.depth_min, self.depth_max) magnitude = self.draw_magnitude(rstate) moment = moment_tensor.magnitude_to_moment(magnitude) # After Mai and Beroza (2000) length = num.exp(-6.27 + 0.4*num.log(moment)) width = num.exp(-4.24 + 0.32*num.log(moment)) length = length if not self.length else self.length width = width if not self.width else self.width depth = depth if not self.depth else self.depth if self.strike is None and self.dip is None and self.rake is None: strike, rake = rstate.uniform(-180., 180., 2) dip = rstate.uniform(0., 90.) else: if None in (self.strike, self.dip, self.rake): raise ScenarioError( 'RectangularFaultGenerator: ' 'strike, dip, rake' ' must be used in combination') strike = self.strike dip = self.dip rake = self.rake source = gf.RectangularSource( time=float(time), lat=float(lat), lon=float(lon), anchor='top', depth=float(depth), length=float(length), width=float(width), strike=float(strike), dip=float(dip), rake=float(rake), magnitude=magnitude, decimation_factor=self.decimation_factor) return source
def add_map_artists(self, automap): from pyrocko import gmtpy for source in self.get_sources(): event = source.pyrocko_event() mt = event.moment_tensor.m_up_south_east() xx = num.trace(mt) / 3. mc = num.matrix([[xx, 0., 0.], [0., xx, 0.], [0., 0., xx]]) mc = mt - mc mc = mc / event.moment_tensor.scalar_moment() * \ moment_tensor.magnitude_to_moment(5.0) m6 = tuple(moment_tensor.to6(mc)) symbol_size = 20. automap.gmt.psmeca( S='%s%g' % ('d', symbol_size / gmtpy.cm), in_rows=[(source.lon, source.lat, 10) + m6 + (1, 0, 0)], M=True, *automap.jxyr)
def add_map_artists(self, automap): from pyrocko import gmtpy for source in self.get_sources(): event = source.pyrocko_event() mt = event.moment_tensor.m_up_south_east() xx = num.trace(mt) / 3. mc = num.matrix([[xx, 0., 0.], [0., xx, 0.], [0., 0., xx]]) mc = mt - mc mc = mc / event.moment_tensor.scalar_moment() * \ moment_tensor.magnitude_to_moment(5.0) m6 = tuple(moment_tensor.to6(mc)) symbol_size = 20. automap.gmt.psmeca(S='%s%g' % ('d', symbol_size / gmtpy.cm), in_rows=[(source.lon, source.lat, 10) + m6 + (1, 0, 0)], M=True, *automap.jxyr)
def test_rect_source(self): store = self.dummy_homogeneous_store() rect1 = gf.RectangularSource(depth=10 * km, magnitude=5.0, width=5 * km, length=5 * km) rect2 = gf.RectangularSource( depth=10 * km, slip=pmt.magnitude_to_moment(5.0) / (5 * km * 5 * km * store.config.earthmodel_1d.material(10 * km).shear_modulus()), width=5 * km, length=5 * km) self.assertAlmostEqual( rect1.get_magnitude(), rect2.get_magnitude(store, gf.Target(interpolation='nearest_neighbor')))
def test_rect_source(self): store = self.dummy_homogeneous_store() rect1 = gf.RectangularSource( depth=10*km, magnitude=5.0, width=5*km, length=5*km) rect2 = gf.RectangularSource( depth=10*km, slip=pmt.magnitude_to_moment(5.0) / ( 5*km * 5*km * store.config.earthmodel_1d.material( 10*km).shear_modulus()), width=5*km, length=5*km) self.assertAlmostEqual( rect1.get_magnitude(), rect2.get_magnitude( store, gf.Target(interpolation='nearest_neighbor')))
from pyrocko import moment_tensor as mtm magnitude = 6.3 # Magnitude of the earthquake exp = mtm.magnitude_to_moment(magnitude) # convert the mag to moment in [Nm] # init pyrocko moment tensor m = mtm.MomentTensor( mnn = 2.34*exp, mee = -2.64*exp, mdd = 0.295*exp, mne = 1.49*exp, mnd = 0.182*exp, med = -0.975*exp) print(m) # print moment tensor # gives out both nodal planes: (s1, d1, r1), (s2, d2, r2) = m.both_strike_dip_rake() print('strike1=%s, dip1=%s, rake1=%s' % (s1, d1, r1)) print('strike2=%s, dip2=%s, rake2=%s' % (s2, d2, r2))
def model( engine, store_id, magnitude_min, magnitude_max, moment_tensor, stress_drop_min, stress_drop_max, rupture_velocity_min, rupture_velocity_max, depth_min, depth_max, distance_min, distance_max, measures, nsources=400, nreceivers=1, apply_source_response_via_spectra=True, debug=True): d2r = math.pi / 180. components = set() for measure in measures: if not measure.components: raise Exception('no components given in measurement rule') for component in measure.components: components.add(component) components = list(components) data = [] nerrors = 0 traces_debug = [] markers_debug = [] for isource in xrange(nsources): magnitude = num.random.uniform( magnitude_min, magnitude_max) stress_drop = num.random.uniform( stress_drop_min, stress_drop_max) rupture_velocity = num.random.uniform( rupture_velocity_min, rupture_velocity_max) radius = (pmt.magnitude_to_moment(magnitude) * 7./16. / stress_drop)**(1./3.) duration = 1.5 * radius / rupture_velocity if moment_tensor is None: mt = pmt.MomentTensor.random_dc(magnitude=magnitude) else: mt = copy.deepcopy(moment_tensor) mt.magnitude = magnitude depth = num.random.uniform(depth_min, depth_max) if apply_source_response_via_spectra: source = gf.MTSource( m6=mt.m6(), depth=depth) extra_responses = [ wmeasure.BruneResponse(duration=duration)] else: source = gf.MTSource( m6=mt.m6(), depth=depth, stf=gf.HalfSinusoidSTF(effective_duration=duration)) extra_responses = [] for ireceiver in xrange(nreceivers): angle = num.random.uniform(0., 360.) distance = num.exp(num.random.uniform( math.log(distance_min), math.log(distance_max))) targets = [] for comp in components: targets.append(gf.Target( quantity='displacement', codes=('', '%i_%i' % (isource, ireceiver), '', comp), north_shift=distance*math.cos(d2r*angle), east_shift=distance*math.sin(d2r*angle), depth=0., store_id=store_id)) resp = engine.process(source, targets) amps = [] for measure in measures: comp_to_tt = {} for (source, target, tr) in resp.iter_results(): comp_to_tt[target.codes[-1]] = (target, tr) targets, trs = zip(*( comp_to_tt[c] for c in measure.components)) try: result = wmeasure.evaluate( engine, source, targets, trs, extra_responses, debug=debug) if not debug: amps.append(result) else: amp, trs, marker = result amps.append(amp) traces_debug.extend(trs) markers_debug.append(marker) except wmeasure.AmplitudeMeasurementFailed: nerrors += 1 amps.append(None) data.append([magnitude, duration, depth, distance] + amps) if debug: trace.snuffle(traces_debug, markers=markers_debug) return num.array(data, dtype=num.float)
def rho(self): return mtm.magnitude_to_moment(self.magnitude) * sqrt2
def PRIOR(self, stream, inventory=False): if inventory: if self.cat == None: raise ValueError('No path for xml file specified!') else: inv = read_events(self.inv) trace = stream.traces[0] PRIOR = {} PRIOR['PLOT'] = False PRIOR['save_name'] = 'TAYAK' + trace.id.replace('.', '_') PRIOR['save_dir'] = self.directory + 'Output' #'/home/nienke/MSS' if not os.path.exists(PRIOR['save_dir']): os.makedirs(PRIOR['save_dir']) # = Radius of the body used = PRIOR['radius'] = 3389.5 # Mars # PRIOR['radius'] = 6378137.0 # Earth # = Flattening planet = PRIOR['f'] = 0 # Mars # PRIOR['f'] = 1 / 298.257223563 # Earth # = Receiver = if inventory == False: print('Location of InSight is used!') PRIOR['la_r'] = 4.5 # InSight PRIOR['lo_r'] = 136 # InSight else: PRIOR['la_r'] = inv._networks[0].stations[ 0]._latitude #4.5 # InSight PRIOR['lo_r'] = inv._networks[0].stations[ 0]._longitude #136 # InSight PRIOR['network'] = trace.stats.network PRIOR['station'] = trace.stats.channel PRIOR['location'] = trace.stats.location PRIOR['rec_depth'] = 0 #589 # For BFO station # = Source = ## Catalogue: if inventory == False: PRIOR['origin_time'] = obspy.UTCDateTime(2019, 5, 23, 2, 19, 33) PRIOR['P_pick'] = obspy.UTCDateTime(2019, 5, 23, 2, 22, 59.1) # If not know: None PRIOR['S_pick'] = obspy.UTCDateTime(2019, 5, 23, 2, 25, 53.8) # If not know: None PRIOR['depth_s'] = 45000 PRIOR['la_s'] = 3.45 PRIOR['lo_s'] = 164.68 Mw = 2.7 else: PRIOR['la_s'] = inv.events[0].origins[0].latitude PRIOR['lo_s'] = inv.events[0].origins[0].longitude PRIOR['depth_s'] = inv.events[0].origins[0].depth PRIOR['origin_time'] = inv.events[0].origins[0].time Mw = None PRIOR['M0'] = self.Magnitude2Scalarmoment(Mw) # Scalar Moment exp = mtm.magnitude_to_moment(Mw) # Using Pyrocko package.... # self.M0 = PRIOR['M0'] PRIOR['components'] = ["Z", "R", "T"] PRIOR['kind'] = 'displacement' dist, az, baz = gps2dist_azimuth(lat1=PRIOR['la_s'], lon1=PRIOR['lo_s'], lat2=PRIOR['la_r'], lon2=PRIOR['lo_r'], a=PRIOR['radius'], f=PRIOR['f']) PRIOR['baz'] = baz PRIOR['az'] = az PRIOR['epi_s'] = kilometer2degrees(dist, radius=PRIOR['radius']) # PRIOR['baz'] = 243 # PRIOR['epi_s'] = 86 # = Velocity model = # -Mars- # PRIOR['VELOC'] = 'http://instaseis.ethz.ch/blindtest_1s/TAYAK_1s/' PRIOR['VELOC'] = '/opt/databases/Mars/TAYAK_1s' # PRIOR['VELOC_taup'] = '/home/nienke/Documents/Master/Data/Database/TAYAK.npz' PRIOR['VELOC_taup'] = '/home/nienke/MARSQUAKES/TAYAK.npz' # -Earth- # PRIOR['VELOC'] = 'syngine://iasp91_2s' # PRIOR['VELOC_taup'] = 'iasp91' # = Noise model = # PRIOR['noise_model'] = 'Tcompact' #'STS2' # # = Sample information = PRIOR['npts'] = 30000 PRIOR['Temperature'] = 1 PRIOR['sample_number'] = 300000 # PRIOR['sampling_rate'] = 20 # [Hz] PRIOR[ 'sampling_rate'] = trace.stats.sampling_rate # [Hz] InSight Mission PRIOR['directory'] = self.directory # = Filter information = PRIOR['P_LP'] = 1.0 / 1.0 PRIOR['P_HP'] = 1.0 / 8.0 # could also be 1.0/10.0 PRIOR['S_LP'] = 1.0 / 1.0 PRIOR['S_HP'] = 1.0 / 10. # = Pick information in seconds = PRIOR['Pre_P'] = 4 #10 PRIOR['Pre_S'] = 5 PRIOR['Post_P'] = 20 PRIOR['Post_S'] = 20 #40 return PRIOR
def save_rapid_dataset(acc, stations, traces, event, config): if config.has('data_dir'): data_dir = config.path('data_dir') if os.path.exists(data_dir): shutil.rmtree(data_dir) if config.has('skeleton_dir'): copy_files(config.path('skeleton_dir'), config.path('main_dir')) if config.has('raw_trace_path'): trace_selector = None if config.has('station_filter'): trace_selector = lambda tr: get_nsl(tr) in stations and config.station_filter(stations[get_nsl(tr)]) for raw_traces in acc.iter_traces(trace_selector=trace_selector): io.save(raw_traces, config.path('raw_trace_path')) dstations = stations.values() dstations.sort( lambda a,b: cmp(a.dist_m, b.dist_m) ) save_event_info_file(config.path('event_info_path'), event) used_traces = [] have = set() used_stations = [] for station in dstations: if station.station in have: continue used_stations.append(station) have.add(station.station) for tr in traces: if get_nsl(tr) == get_nsl(station): tr = tr.copy() if config.trace_time_zero == 'event': tr.shift(-event.time) ydata = tr.get_ydata() ydata *= config.trace_factor used_traces.append(tr) save_rapid_station_table(config.path('stations_path'), used_stations) io.save(used_traces, config.path('displacement_trace_path')) dss = util.time_to_str(event.time, format='%Y %m %d %H %M %S').split() moment = moment_tensor.magnitude_to_moment(event.magnitude) work_dir = pjoin(config.path('main_dir'), 'work') rapidinp = ''' INVERSION_DIR %s DATA_DIR %s DATA_FILE %s LATITUDE_NORTH %g LONGITUDE_EAST %g YEAR %s MONTH %s DAY %s HOUR %s MIN %s SEC %s DEPTH_1 %g DEPTH_2 %g SCAL_MOM_1 %g SCAL_MOM_2 %g ''' % (( pjoin('..', 'result'), pjoin('..', 'data'), util.time_to_str(event.time, format='%Y-%m-%d_%H-%M-S'), event.lat, event.lon) + tuple(dss) + (event.depth/km, event.depth/km, moment, moment)) f = open(pjoin(work_dir, 'rapidinv.inp'), 'w') f.write(rapidinp) f.close()
def moment(self): return mt.magnitude_to_moment(self.magnitude)
def oldloadf(file): d = {} try: for line in file: if line.lstrip().startswith('#'): continue toks = line.split(' = ', 1) if len(toks) == 2: k, v = toks[0].strip(), toks[1].strip() if k in ('name', 'region', 'catalog', 'magnitude_type'): d[k] = v if k in (('latitude longitude magnitude depth duration ' 'mnn mee mdd mne mnd med strike1 dip1 rake1 ' 'strike2 dip2 rake2 duration').split()): d[k] = float(v) if k == 'time': d[k] = util.str_to_time(v) if line.startswith('---'): d['have_separator'] = True break except Exception as e: raise FileParseError(e) if not d: raise EOF() if 'have_separator' in d and len(d) == 1: raise EmptyEvent() mt = None m6 = [d[x] for x in 'mnn mee mdd mne mnd med'.split() if x in d] if len(m6) == 6: mt = moment_tensor.MomentTensor(m=moment_tensor.symmat6(*m6)) else: sdr = [d[x] for x in 'strike1 dip1 rake1'.split() if x in d] if len(sdr) == 3: moment = 1.0 if 'moment' in d: moment = d['moment'] elif 'magnitude' in d: moment = moment_tensor.magnitude_to_moment(d['magnitude']) mt = moment_tensor.MomentTensor( strike=sdr[0], dip=sdr[1], rake=sdr[2], scalar_moment=moment) return ( d.get('latitude', 0.0), d.get('longitude', 0.0), d.get('time', 0.0), d.get('name', ''), d.get('depth', None), d.get('magnitude', None), d.get('magnitude_type', None), d.get('region', None), d.get('catalog', None), mt, d.get('duration', None))
def make_time_line(self, events): if self.cli_mode: import matplotlib.pyplot as plt self.fig = plt.figure() else: fframe = self.figure_frame() self.fig = fframe.gcf() gs = gridspec.GridSpec( 2, 1, figure=self.fig, hspace=0.005, top=0.95) gs1 = gridspec.GridSpec( 2, 2, figure=self.fig) ax = self.fig.add_subplot(gs[0]) ax1 = ax.twinx() ax2 = self.fig.add_subplot(gs1[-1]) ax3 = self.fig.add_subplot(gs1[-2]) events.sort(key=lambda x: x.time) magnitudes = [] i_has_magnitude = [] for i, e in enumerate(events): if e.moment_tensor is not None: magnitude = e.moment_tensor.magnitude else: magnitude = e.magnitude if magnitude is not None: magnitudes.append(magnitude) i_has_magnitude.append(i) cum_events = num.cumsum(num.ones(len(i_has_magnitude))) moments = moment_tensor.magnitude_to_moment(num.array(magnitudes)) cum_events_magnitude = num.cumsum(moments) times = num.array([events[i].time for i in i_has_magnitude]) timeslabels = [datetime.datetime(1970, 1, 1) + datetime.timedelta(seconds=t) for t in times] ax.plot(timeslabels, cum_events) ax.set_ylabel('Cumulative number of events') ax.axes.get_xaxis().set_ticklabels([]) ax1.plot(timeslabels, cum_events_magnitude, '-b') ax1.set_ylabel('Cumulative moment [Nm]') xfmt = md.DateFormatter('%Y-%m-%d') ax1.xaxis.set_major_formatter(xfmt) ax.yaxis.label.set_color('r') ax1.yaxis.label.set_color('b') ax.grid(True) ax1.grid(True) t0 = min(times) if self.variation == 'daily': normalization = 60 * 60 nbins = 24 t0_day = util.day_start(t0) ax2.set_xlabel('hour of day') elif self.variation == 'annual': normalization = 60 * 60 * 24 nbins = 365 t0_day = util.year_start(t0) ax2.set_xlabel('day of year') binned = (times - t0_day) % (nbins * normalization) ax2.hist(binned/normalization, bins=nbins, color='grey') ax2.set_ylabel('Number of events') ax2.set_xlim((0, nbins)) ax3.hist(magnitudes, bins=21, histtype='stepfilled') ax3.set_xlabel('Magnitude') ax3.set_ylabel('Number of events') if self.cli_mode: plt.show() else: self.fig.canvas.draw()
def make_time_line(self, events): if self.cli_mode: import matplotlib.pyplot as plt self.fig = plt.figure() else: fframe = self.figure_frame() self.fig = fframe.gcf() gs = gridspec.GridSpec(2, 1) gs.update(hspace=0.005, top=0.95) gs1 = gridspec.GridSpec(2, 1) gs1.update(bottom=0.06, hspace=0.01) ax = self.fig.add_subplot(gs[0]) ax1 = ax.twinx() ax2 = self.fig.add_subplot(gs1[-1]) events.sort(key=lambda x: x.time) magnitudes = [] cum_events = num.cumsum(num.ones(len(events))) for e in events: if e.moment_tensor is not None: magnitudes.append(e.moment_tensor.magnitude) else: magnitudes.append(e.magnitude) if magnitudes[-1] is None: magnitudes.pop() magnitudes.append(0.) magnitudes = moment_tensor.magnitude_to_moment(num.array(magnitudes)) cum_events_magnitude = num.cumsum(magnitudes) times = num.array([e.time for e in events]) timeslabels = [datetime.datetime(1970, 1, 1) + datetime.timedelta(seconds=t) for t in times] ax.plot(timeslabels, cum_events) ax.set_ylabel('Cumulative number of events') ax.axes.get_xaxis().set_ticklabels([]) ax1.plot(timeslabels, cum_events_magnitude, '-b') ax1.set_ylabel('Cumulative moment [Nm]') xfmt = md.DateFormatter('%Y-%m-%d') ax1.xaxis.set_major_formatter(xfmt) ax.yaxis.label.set_color('r') ax1.yaxis.label.set_color('b') ax.grid(True) ax1.grid(True) t0 = min(times) if self.variation == 'daily': normalization = 60 * 60 nbins = 24 t0_day = util.day_start(t0) ax2.set_xlabel('hour of day') elif self.variation == 'annual': normalization = 60 * 60 * 24 nbins = 365 t0_day = util.year_start(t0) ax2.set_xlabel('day of year') binned = (times - t0_day) % (nbins * normalization) ax2.hist(binned/normalization, bins=nbins, color='grey') ax2.set_ylabel('Number of events') ax2.set_xlim((0, nbins)) if self.cli_mode: plt.show() else: self.fig.canvas.draw()
factor_symbl_size = 5.0 for ev in events: mag = ev.magnitude if ev.moment_tensor is None: ev_symb = 'c' + str(mag * factor_symbl_size) + 'p' m.gmt.psxy(in_rows=[[ev.lon, ev.lat]], S=ev_symb, G=gmtpy.color('scarletred2'), W='1p,black', *m.jxyr) else: devi = ev.moment_tensor.deviatoric() beachball_size = mag * factor_symbl_size mt = devi.m_up_south_east() mt = mt / ev.moment_tensor.scalar_moment() \ * pmt.magnitude_to_moment(5.0) m6 = pmt.to6(mt) data = (ev.lon, ev.lat, 10) + tuple(m6) + (1, 0, 0) if m.gmt.is_gmt5(): kwargs = dict(M=True, S='%s%g' % (beachball_symbol[0], (beachball_size) / gmtpy.cm)) else: kwargs = dict(S='%s%g' % (beachball_symbol[0], (beachball_size) * 2 / gmtpy.cm)) m.gmt.psmeca(in_rows=[data], G=gmtpy.color('chocolate1'), E='white', W='1p,%s' % gmtpy.color('chocolate3'),
from matplotlib import pyplot as plt from pyrocko import moment_tensor as pmt, cake, orthodrome from pyrocko.plot import beachball from pyrocko import moment_tensor as mtm km = 1000. # source position and mechanism slat, slon, sdepth = 43, 32, 21 * km magnitude = 6.5 strike = 231 dip = 43 rake = 22 m0 = mtm.magnitude_to_moment(magnitude) # Convert MW to M0 [Nm] mt = mtm.MomentTensor(strike=strike, dip=dip, rake=rake, scalar_moment=m0) # Create Moment tensor m6 = [mt.mnn, mt.mee, mt.mdd, mt.mne, mt.mnd, mt.med] # Six identical components Mt = (m6 / mt.scalar_moment()) # Normalize the six identical components # receiver positions rdepth = 0.0 rlatlons = [ (35, 45), (33, 48), (32, 45), ] # earth model and phase for takeoff angle computations
def PRIOR(self,stream,inventory=False): if inventory: if self.cat == None: raise ValueError('No path for xml file specified!') else: inv = read_events(self.inv) trace = stream.traces[0] PRIOR = {} PRIOR['PLOT'] = False PRIOR['save_name'] = 'MAAK_' + trace.id.replace('.','_') PRIOR['save_dir'] = self.directory + 'Output' #'/home/nienke/MSS' if not os.path.exists(PRIOR['save_dir']): os.makedirs(PRIOR['save_dir']) # = Radius of the body used = PRIOR['radius'] = 3389.5 # Mars # PRIOR['radius'] = 6378137.0 # Earth # = Flattening planet = PRIOR['f']= 0 # Mars # PRIOR['f'] = 1 / 298.257223563 # Earth # = Receiver = if inventory == False: print('Location of InSight is used!') PRIOR['la_r'] = 4.5 # InSight PRIOR['lo_r'] = 136 # InSight else: PRIOR['la_r'] = inv._networks[0].stations[0]._latitude #4.5 # InSight PRIOR['lo_r'] = inv._networks[0].stations[0]._longitude #136 # InSight PRIOR['network'] = trace.stats.network PRIOR['station'] = trace.stats.channel PRIOR['location'] = trace.stats.location PRIOR['rec_depth'] = 0#589 # For BFO station # = Source = ## Catalogue: if inventory == False: PRIOR['origin_time'] = obspy.UTCDateTime(2019, 1, 3, 15, 00, 30) PRIOR['depth_s'] = 38438 PRIOR['la_s'] = - 26.443 PRIOR['lo_s'] = 50.920 Mw = 4.46 else: PRIOR['la_s'] = inv.events[0].origins[0].latitude PRIOR['lo_s'] = inv.events[0].origins[0].longitude PRIOR['depth_s'] = inv.events[0].origins[0].depth PRIOR['origin_time'] = inv.events[0].origins[0].time Mw = 4.46 PRIOR['M0'] = self.Magnitude2Scalarmoment(Mw) # Scalar Moment --> 6165950018614810.0 exp = mtm.magnitude_to_moment(Mw) # Using Pyrocko package.... --> 5495408738576270.0 # self.M0 = PRIOR['M0'] PRIOR['components'] = ["Z", "R", "T"] PRIOR['kind'] = 'velocity' dist, az, baz = gps2dist_azimuth(lat1=PRIOR['la_s'], lon1=PRIOR['lo_s'], lat2=PRIOR['la_r'], lon2=PRIOR['lo_r'], a=PRIOR['radius'], f=PRIOR['f']) PRIOR['baz'] = baz PRIOR['az'] = az PRIOR['epi_s'] = kilometer2degrees(dist, radius=PRIOR['radius']) # = Velocity model = # -Mars- # PRIOR['VELOC'] = 'http://instaseis.ethz.ch/blindtest_1s/MAAK_1s/' PRIOR['VELOC'] = 'http://instaseis.ethz.ch/blindtest_1s/MAAK_1s/' # PRIOR['VELOC'] = '/home/nienke/mnt_databases/databases/blindtestmodels_1s/MAAK_1s' # PRIOR['VELOC'] = 'mnt_databases/databases/blindtestmodels_1s/EH45TcoldCrust1' # PRIOR['VELOC_taup'] = 'EH45TcoldCrust1b.npz' PRIOR['VELOC_taup'] = '/home/nienke/Documents/Master/Data/Database/maak.npz' # -Earth- # PRIOR['VELOC'] = 'syngine://iasp91_2s' # PRIOR['VELOC_taup'] = 'iasp91' # = Noise model = # PRIOR['noise_model'] = 'Tcompact' #'STS2' # # = Sample information = PRIOR['npts'] = 30000 PRIOR['Temperature'] = 1 PRIOR['sample_number'] = 50000 # PRIOR['sampling_rate'] = 20 # [Hz] PRIOR['sampling_rate'] = trace.stats.sampling_rate # [Hz] InSight Mission PRIOR['directory'] = self.directory # = Filter information = PRIOR['P_LP'] = 0.75 PRIOR['P_HP'] = 1.0 / 10.0 PRIOR['S_LP'] = 1.0 / 7.0 PRIOR['S_HP'] = 1.0 / 30.0 return PRIOR
def testMagnitudeMoment(self): for i in range(1, 10): mag = float(i) assert abs(mag - moment_to_magnitude(magnitude_to_moment(mag))) \ < 1e-6, 'Magnitude to moment to magnitude test failed.'
for ev in events: mag = ev.magnitude if ev.moment_tensor is None: ev_symb = 'c'+str(mag*factor_symbl_size)+'p' m.gmt.psxy( in_rows=[[ev.lon, ev.lat]], S=ev_symb, G=gmtpy.color('scarletred2'), W='1p,black', *m.jxyr) else: devi = ev.moment_tensor.deviatoric() beachball_size = mag*factor_symbl_size mt = devi.m_up_south_east() mt = mt / ev.moment_tensor.scalar_moment() \ * pmt.magnitude_to_moment(5.0) m6 = pmt.to6(mt) data = (ev.lon, ev.lat, 10) + tuple(m6) + (1, 0, 0)# if m.gmt.is_gmt5(): kwargs = dict( M=True, S='%s%g' % (beachball_symbol[0], (beachball_size) / gmtpy.cm)) else: kwargs = dict( S='%s%g' % (beachball_symbol[0], (beachball_size)*2 / gmtpy.cm)) m.gmt.psmeca( in_rows=[data], G=gmtpy.color('chocolate1'),
def call(self): if not self.viewer_connected: self.get_viewer().about_to_close.connect( self.file_serving_worker.stop) self.viewer_connected = True try: from OpenGL import GL # noqa except ImportError: logger.warn( 'Could not find package OpenGL, ' 'if the map does not work try installing OpenGL\n' 'e.g. sudo pip install PyOpenGL') self.cleanup() try: viewer = self.get_viewer() cli_mode = False except NoViewerSet: viewer = None cli_mode = True if not cli_mode: if self.only_active: _, active_stations = \ self.get_active_event_and_stations() else: active_stations = viewer.stations.values() elif cli_mode: active_stations = self.stations station_list = [] if active_stations: for stat in active_stations: is_blacklisted = util.match_nslc(viewer.blacklist, stat.nsl()) if (viewer and not is_blacklisted) or cli_mode: xml_station_marker = XMLStationMarker( nsl='.'.join(stat.nsl()), longitude=float(stat.lon), latitude=float(stat.lat), active='yes') station_list.append(xml_station_marker) active_station_list = StationMarkerList(stations=station_list) if self.only_active: markers = [viewer.get_active_event_marker()] else: if cli_mode: markers = self.markers else: markers = self.get_selected_markers() if len(markers) == 0: tmin, tmax = self.get_selected_time_range(fallback=True) markers = [m for m in viewer.get_markers() if isinstance(m, gui_util.EventMarker) and m.tmin >= tmin and m.tmax <= tmax] ev_marker_list = [] for m in markers: if not isinstance(m, gui_util.EventMarker): continue xmleventmarker = convert_event_marker(m) if xmleventmarker is None: continue ev_marker_list.append(xmleventmarker) event_list = EventMarkerList(events=ev_marker_list) event_station_list = MarkerLists( station_marker_list=active_station_list, event_marker_list=event_list) event_station_list.validate() if self.map_kind != 'GMT': tempdir = self.marker_tempdir if self.map_kind == 'Google Maps': map_fn = 'map_googlemaps.html' elif self.map_kind == 'OpenStreetMap': map_fn = 'map_osm.html' url = 'http://localhost:' + str(self.port) + '/%s' % map_fn files = ['loadxmldoc.js', 'map_util.js', 'plates.kml', map_fn] snuffling_dir = op.dirname(op.abspath(__file__)) for entry in files: shutil.copy(os.path.join(snuffling_dir, entry), os.path.join(tempdir, entry)) logger.debug('copied data to %s' % tempdir) markers_fn = os.path.join(self.marker_tempdir, 'markers.xml') self.data_proxy.content_to_serve.emit(self.port) dump_xml(event_station_list, filename=markers_fn) if self.open_external: qg.QDesktopServices.openUrl(qc.QUrl(url)) else: global g_counter g_counter += 1 self.web_frame( url, name='Map %i (%s)' % (g_counter, self.map_kind)) else: lats_all = [] lons_all = [] slats = [] slons = [] slabels = [] for s in active_stations: slats.append(s.lat) slons.append(s.lon) slabels.append('.'.join(s.nsl())) elats = [] elons = [] elats = [] elons = [] psmeca_input = [] markers = self.get_selected_markers() for m in markers: if isinstance(m, gui_util.EventMarker): e = m.get_event() elats.append(e.lat) elons.append(e.lon) if e.moment_tensor is not None: mt = e.moment_tensor.m6() psmeca_input.append( (e.lon, e.lat, e.depth/1000., mt[0], mt[1], mt[2], mt[3], mt[4], mt[5], 1., e.lon, e.lat, e.name)) else: if e.magnitude is None: moment = -1. else: moment = moment_tensor.magnitude_to_moment( e.magnitude) psmeca_input.append( (e.lon, e.lat, e.depth/1000., moment/3., moment/3., moment/3., 0., 0., 0., 1., e.lon, e.lat, e.name)) lats_all.extend(elats) lons_all.extend(elons) lats_all.extend(slats) lons_all.extend(slons) lats_all = num.array(lats_all) lons_all = num.array(lons_all) if len(lats_all) == 0: return center_lat, center_lon = ortho.geographic_midpoint( lats_all, lons_all) ntotal = len(lats_all) clats = num.ones(ntotal) * center_lat clons = num.ones(ntotal) * center_lon dists = ortho.distance_accurate50m_numpy( clats, clons, lats_all, lons_all) maxd = num.max(dists) or 0. m = Map( lat=center_lat, lon=center_lon, radius=max(10000., maxd) * 1.1, width=35, height=25, show_grid=True, show_topo=True, color_dry=(238, 236, 230), topo_cpt_wet='light_sea_uniform', topo_cpt_dry='light_land_uniform', illuminate=True, illuminate_factor_ocean=0.15, show_rivers=False, show_plates=False) m.gmt.psxy(in_columns=(slons, slats), S='t15p', G='black', *m.jxyr) for i in range(len(active_stations)): m.add_label(slats[i], slons[i], slabels[i]) m.gmt.psmeca( in_rows=psmeca_input, S='m1.0', G='red', C='5p,0/0/0', *m.jxyr) tmpdir = self.tempdir() self.outfn = os.path.join(tmpdir, '%i.png' % self.figcount) m.save(self.outfn) f = self.pixmap_frame(self.outfn) # noqa
def main(args=None): if args is None: args = sys.argv[1:] parser = OptionParser( usage=usage, description=description) parser.add_option( '--width', dest='width', type='float', default=20.0, metavar='FLOAT', help='set width of output image [cm] (%default)') parser.add_option( '--height', dest='height', type='float', default=15.0, metavar='FLOAT', help='set height of output image [cm] (%default)') parser.add_option( '--topo-resolution-min', dest='topo_resolution_min', type='float', default=40.0, metavar='FLOAT', help='minimum resolution of topography [dpi] (%default)') parser.add_option( '--topo-resolution-max', dest='topo_resolution_max', type='float', default=200.0, metavar='FLOAT', help='maximum resolution of topography [dpi] (%default)') parser.add_option( '--no-grid', dest='show_grid', default=True, action='store_false', help='don\'t show grid lines') parser.add_option( '--no-topo', dest='show_topo', default=True, action='store_false', help='don\'t show topography') parser.add_option( '--no-cities', dest='show_cities', default=True, action='store_false', help='don\'t show cities') parser.add_option( '--no-illuminate', dest='illuminate', default=True, action='store_false', help='deactivate artificial illumination of topography') parser.add_option( '--illuminate-factor-land', dest='illuminate_factor_land', type='float', metavar='FLOAT', help='set factor for artificial illumination of land (0.5)') parser.add_option( '--illuminate-factor-ocean', dest='illuminate_factor_ocean', type='float', metavar='FLOAT', help='set factor for artificial illumination of ocean (0.25)') parser.add_option( '--theme', choices=['topo', 'soft'], default='topo', help='select color theme, available: topo, soft (topo)"') parser.add_option( '--download-etopo1', dest='download_etopo1', action='store_true', help='download full ETOPO1 topography dataset') parser.add_option( '--download-srtmgl3', dest='download_srtmgl3', action='store_true', help='download full SRTMGL3 topography dataset') parser.add_option( '--make-decimated-topo', dest='make_decimated', action='store_true', help='pre-make all decimated topography datasets') parser.add_option( '--stations', dest='stations_fn', metavar='FILENAME', help='load station coordinates from FILENAME') parser.add_option( '--events', dest='events_fn', metavar='FILENAME', help='load event coordinates from FILENAME') parser.add_option( '--debug', dest='debug', action='store_true', default=False, help='print debugging information to stderr') (options, args) = parser.parse_args(args) if options.debug: util.setup_logging(program_name, 'debug') else: util.setup_logging(program_name, 'info') if options.download_etopo1: import pyrocko.datasets.topo.etopo1 pyrocko.datasets.topo.etopo1.download() if options.download_srtmgl3: import pyrocko.datasets.topo.srtmgl3 pyrocko.datasets.topo.srtmgl3.download() if options.make_decimated: import pyrocko.datasets.topo pyrocko.datasets.topo.make_all_missing_decimated() if (options.download_etopo1 or options.download_srtmgl3 or options.make_decimated) and len(args) == 0: sys.exit(0) if options.theme == 'soft': color_kwargs = { 'illuminate_factor_land': options.illuminate_factor_land or 0.2, 'illuminate_factor_ocean': options.illuminate_factor_ocean or 0.15, 'color_wet': (216, 242, 254), 'color_dry': (238, 236, 230), 'topo_cpt_wet': 'light_sea_uniform', 'topo_cpt_dry': 'light_land_uniform'} elif options.theme == 'topo': color_kwargs = { 'illuminate_factor_land': options.illuminate_factor_land or 0.5, 'illuminate_factor_ocean': options.illuminate_factor_ocean or 0.25} events = [] if options.events_fn: events = model.load_events(options.events_fn) stations = [] if options.stations_fn: stations = model.load_stations(options.stations_fn) if not (len(args) == 4 or ( len(args) == 1 and (events or stations))): parser.print_help() sys.exit(1) if len(args) == 4: try: lat = float(args[0]) lon = float(args[1]) radius = float(args[2])*km except Exception: parser.print_help() sys.exit(1) else: lats, lons = latlon_arrays(stations+events) lat, lon = map(float, od.geographic_midpoint(lats, lons)) radius = float( num.max(od.distance_accurate50m_numpy(lat, lon, lats, lons))) radius *= 1.1 m = automap.Map( width=options.width, height=options.height, lat=lat, lon=lon, radius=radius, topo_resolution_max=options.topo_resolution_max, topo_resolution_min=options.topo_resolution_min, show_topo=options.show_topo, show_grid=options.show_grid, illuminate=options.illuminate, **color_kwargs) logger.debug('map configuration:\n%s' % str(m)) if options.show_cities: m.draw_cities() if stations: lats = [s.lat for s in stations] lons = [s.lon for s in stations] m.gmt.psxy( in_columns=(lons, lats), S='t8p', G='black', *m.jxyr) for s in stations: m.add_label(s.lat, s.lon, '%s' % '.'.join( x for x in s.nsl() if x)) if events: beachball_symbol = 'mt' beachball_size = 20.0 for ev in events: if ev.moment_tensor is None: m.gmt.psxy( in_rows=[[ev.lon, ev.lat]], S='c12p', G=gmtpy.color('scarletred2'), W='1p,black', *m.jxyr) else: devi = ev.moment_tensor.deviatoric() mt = devi.m_up_south_east() mt = mt / ev.moment_tensor.scalar_moment() \ * pmt.magnitude_to_moment(5.0) m6 = pmt.to6(mt) data = (ev.lon, ev.lat, 10) + tuple(m6) + (1, 0, 0) if m.gmt.is_gmt5(): kwargs = dict( M=True, S='%s%g' % ( beachball_symbol[0], beachball_size / gmtpy.cm)) else: kwargs = dict( S='%s%g' % ( beachball_symbol[0], beachball_size*2 / gmtpy.cm)) m.gmt.psmeca( in_rows=[data], G=gmtpy.color('chocolate1'), E='white', W='1p,%s' % gmtpy.color('chocolate3'), *m.jxyr, **kwargs) m.save(args[-1])
def plot_map(stations, center, events=None, savename=None): from pyrocko.plot.automap import Map from pyrocko.example import get_example_data from pyrocko import model, gmtpy from pyrocko import moment_tensor as pmt gmtpy.check_have_gmt() # Generate the basic map m = Map(lat=center[0], lon=center[1], radius=150000., width=30., height=30., show_grid=False, show_topo=True, color_dry=(238, 236, 230), topo_cpt_wet='light_sea_uniform', topo_cpt_dry='light_land_uniform', illuminate=True, illuminate_factor_ocean=0.15, show_rivers=False, show_plates=False) # Draw some larger cities covered by the map area m.draw_cities() # Generate with latitute, longitude and labels of the stations lats = [s.lat for s in stations] lons = [s.lon for s in stations] labels = ['.'.join(s.nsl()) for s in stations] # Stations as black triangles. m.gmt.psxy(in_columns=(lons, lats), S='t20p', G='black', *m.jxyr) # Station labels for i in range(len(stations)): m.add_label(lats[i], lons[i], labels[i]) beachball_symbol = 'd' factor_symbl_size = 5.0 if events is not None: for ev in events: mag = ev.magnitude if ev.moment_tensor is None: ev_symb = 'c' + str(mag * factor_symbl_size) + 'p' m.gmt.psxy(in_rows=[[ev.lon, ev.lat]], S=ev_symb, G=gmtpy.color('scarletred2'), W='1p,black', *m.jxyr) else: devi = ev.moment_tensor.deviatoric() beachball_size = mag * factor_symbl_size mt = devi.m_up_south_east() mt = mt / ev.moment_tensor.scalar_moment() \ * pmt.magnitude_to_moment(5.0) m6 = pmt.to6(mt) data = (ev.lon, ev.lat, 10) + tuple(m6) + (1, 0, 0) if m.gmt.is_gmt5(): kwargs = dict(M=True, S='%s%g' % (beachball_symbol[0], (beachball_size) / gmtpy.cm)) else: kwargs = dict(S='%s%g' % (beachball_symbol[0], (beachball_size) * 2 / gmtpy.cm)) m.gmt.psmeca(in_rows=[data], G=gmtpy.color('chocolate1'), E='white', W='1p,%s' % gmtpy.color('chocolate3'), *m.jxyr, **kwargs) if savename is None: if events is None: m.save('pics/stations_ridgecrest.png') else: m.save('pics/mechanisms_scedc_ridgecrest.png') else: m.save(savename)
def get_factor(self): return mt.magnitude_to_moment(self.magnitude)
shutil.rmtree(output_root) print('[' + sys._getframe().f_code.co_name + '] Output files root folder \'' + output_root + '\' existed and has been deleted, as required by script.') else: sys.exit( '[' + sys._getframe().f_code.co_name + '] Output files root folder \'' + output_root + '\' exists, and script is not set to overwrite. Rename or delete it before running again.' ) os.makedirs(output_root) # Plot sources' beachballs. for source in options_source['sources']: mw = source['mag'] m0 = mtm.magnitude_to_moment(mw) # convert the mag to moment strike, dip, rake = source['strike'], source['dip'], source['rake'] mt = mtm.MomentTensor(strike=strike, dip=dip, rake=rake, scalar_moment=m0) fig = plt.figure() ax = fig.add_subplot(111) aa = (mt.m6_up_south_east() * m0).tolist() bball = beach(aa, xy=(0., 0.), width=200, linewidth=1, axes=ax) bball.set_zorder(100) ax.add_collection(bball) plt.title('$M_w$ ' + str(round(mw, 2)) + ' - $f_0 = ' + str(round(options_source['f0'], 3)) + '$ Hz' + ' - depth $ = ' + str(round(source['depth'], 3)) + '$ km') plt.xlim([-0.5, 0.5])
from pyrocko import moment_tensor as pmt magnitude = 6.3 # Magnitude of the earthquake m0 = pmt.magnitude_to_moment(magnitude) # convert the mag to moment strike = 130 dip = 40 rake = 110 mt = pmt.MomentTensor(strike=strike, dip=dip, rake=rake, scalar_moment=m0) m6 = [mt.mnn, mt.mee, mt.mdd, mt.mne, mt.mnd, mt.med] # The six MT components print(m6/mt.scalar_moment()) # normalized MT components
from pyrocko import moment_tensor as mtm magnitude = 6.3 # Magnitude of the earthquake m0 = mtm.magnitude_to_moment(magnitude) # convert the mag to moment strike = 130 dip = 40 rake = 110 mt = mtm.MomentTensor(strike=strike, dip=dip, rake=rake, scalar_moment=m0) m6 = [mt.mnn, mt.mee, mt.mdd, mt.mne, mt.mnd, mt.med] # The six MT components print(m6/mt.scalar_moment()) # normalized MT components
def plot_spatial_with_dcs(events, eventsclusters, clusters, conf, plotdir): ''' Plot map of seismicity clusters, with focal mechanisms ''' lats = [ev.lat for ev in events] lons = [ev.lon for ev in events] # deps = [ev.depth for ev in events] # colors = [cluster_to_color(clid) for clid in eventsclusters] if conf.sw_filterevent: latmin, latmax = conf.latmin, conf.latmax lonmin, lonmax = conf.lonmin, conf.lonmax # depmin, depmax = conf.depthmin, conf.depthmax if latmin > latmax: print('cases over lon +-180 still to be implemented') sys.exit() center = model.event(0.5 * (latmin + latmax), 0.5 * (lonmin + lonmax)) else: latmin, latmax = min(lats) - 0.1, max(lats) + 0.1 lonmin, lonmax = min(lons) - 0.1, max(lons) + 0.1 # depmin = 0.*km # depmax = 1.05*max(deps) center = od.Loc(0.5 * (latmin + latmax), 0.5 * (lonmin + lonmax)) # Map size if conf.sw_manual_radius: safe_radius = conf.map_radius else: corners = [od.Loc(latmin, lonmin), od.Loc(latmin, lonmax)] dist1 = od.distance_accurate50m(center, corners[0]) dist2 = od.distance_accurate50m(center, corners[1]) safe_radius = max(dist1, dist2) # Generate the basic map m = Map(lat=center.lat, lon=center.lon, radius=safe_radius, width=30., height=30., show_grid=False, show_topo=False, color_dry=(238, 236, 230), topo_cpt_wet='light_sea_uniform', topo_cpt_dry='light_land_uniform', illuminate=True, illuminate_factor_ocean=0.15, show_rivers=False, show_plates=False) if conf.sw_filterevent: rectlons = [lonmin, lonmin, lonmax, lonmax, lonmin] rectlats = [latmin, latmax, latmax, latmin, latmin] m.gmt.psxy(in_columns=(rectlons, rectlats), W='thin,0/0/0,dashed', *m.jxyr) # Draw some larger cities covered by the map area m.draw_cities() # Events in clusters factor_symbl_size = 5. beachball_symbol = 'd' for id_cluster in clusters: col = cluster_to_color(id_cluster) g_col = color2rgb(col) for iev, evcl in enumerate(eventsclusters): if evcl == id_cluster: ev = events[iev] if ev.moment_tensor is not None: factor_symbl_size = ev.magnitude devi = ev.moment_tensor.deviatoric() beachball_size = 3. * factor_symbl_size mt = devi.m_up_south_east() mt = mt / ev.moment_tensor.scalar_moment() \ * pmt.magnitude_to_moment(5.0) m6 = pmt.to6(mt) if m.gmt.is_gmt5(): kwargs = dict(M=True, S='%s%g' % (beachball_symbol[0], (beachball_size) / gmtpy.cm)) else: kwargs = dict(S='%s%g' % (beachball_symbol[0], (beachball_size) * 2 / gmtpy.cm)) data = (ev.lon, ev.lat, 10) + tuple(m6) + (1, 0, 0) m.gmt.psmeca(in_rows=[data], G=g_col, E='white', W='1p,%s' % g_col, *m.jxyr, **kwargs) figname = os.path.join(plotdir, 'plot_map_with_dcs.' + conf.figure_format) m.save(figname)
def plot_tm(events, eventsclusters, clusters, conf, plotdir): ''' Plot magnitude vs time for the seismicity clusters. Plot cumulative moment vs time for the seismicity clusters. ''' times = [ev.time for ev in events] orig_dates = [datetime.datetime.fromtimestamp(ev.time) for ev in events] mpl_dates = dates.date2num(orig_dates) mags = [ev.magnitude for ev in events] colors = [cluster_to_color(clid) for clid in eventsclusters] dates_format = dates.DateFormatter('%Y-%m-%d') if conf.sw_filterevent: tmin, tmax = conf.tmin, conf.tmax magmin, magmax = conf.magmin, conf.magmax else: if (max(times) - min(times)) / 86400. > 720.: dt = 86400. dates_loc = dates.YearLocator() elif (max(times) - min(times)) / 86400. > 10.: dt = 86400. dates_loc = dates.MonthLocator() elif (max(times) - min(times)) / 3600. > 10.: dt = 3600. dates_loc = dates.DayLocator() else: dt = 1. dates_loc = dates.HourLocator() dates_format = dates.DateFormatter('%Y-%m-%d %h:%m:%s') tmin, tmax = min(times) - dt, max(times) + dt magmin, magmax = min(mags) - 0.1, max(mags) + 0.1 dmin = dates.date2num(datetime.datetime.fromtimestamp(tmin)) dmax = dates.date2num(datetime.datetime.fromtimestamp(tmax)) f = plt.figure() f.suptitle('Temporal evolution of seismicity clusters', fontsize=14) ax = f.add_subplot(111) ax.scatter(mpl_dates, mags, s=15., c=colors, alpha=0.5) ax.xaxis.set_major_locator(dates_loc) ax.xaxis.set_major_formatter(dates_format) plt.xlim(xmax=dmax, xmin=dmin) plt.ylim(ymax=magmax, ymin=magmin) plt.xticks(rotation=45.) plt.xlabel("Time") plt.ylabel("Magnitude") plt.subplots_adjust(bottom=.3) figname = os.path.join(plotdir, 'plot_tm.' + conf.figure_format) f.savefig(figname) times = [ev.time for ev in events] orig_dates = [datetime.datetime.fromtimestamp(ev.time) for ev in events] mpl_dates = dates.date2num(orig_dates) colors = [cluster_to_color(clid) for clid in eventsclusters] dates_format = dates.DateFormatter('%Y-%m-%d') if conf.sw_filterevent: tmin, tmax = conf.tmin, conf.tmax magmin, magmax = conf.magmin, conf.magmax else: if (max(times) - min(times)) / 86400. > 720.: dt = 86400. dates_loc = dates.YearLocator() elif (max(times) - min(times)) / 86400. > 10.: dt = 86400. dates_loc = dates.MonthLocator() elif (max(times) - min(times)) / 3600. > 10.: dt = 3600. dates_loc = dates.DayLocator() else: dt = 1. dates_loc = dates.HourLocator() dates_format = dates.DateFormatter('%Y-%m-%d %h:%m:%s') tmin, tmax = min(times) - dt, max(times) + dt dmin = dates.date2num(datetime.datetime.fromtimestamp(tmin)) dmax = dates.date2num(datetime.datetime.fromtimestamp(tmax)) f = plt.figure() f.suptitle('Cumulative moment release of seismicity clusters', fontsize=14) ax = f.add_subplot(111) cum_dates = [] d1 = dates.date2num(datetime.datetime.fromtimestamp(tmin)) cum_dates.append(d1) cum_m0s = [] cm0 = 0. cum_m0s.append(cm0) for ev in events: print(ev.name, ev.time) new_date = dates.date2num(datetime.datetime.fromtimestamp(ev.time)) cum_dates.append(new_date) cum_dates.append(new_date) cum_m0s.append(cm0) cm0 = cm0 + pmt.magnitude_to_moment(ev.magnitude) cum_m0s.append(cm0) cum_dates.append(dmax) cum_m0s.append(cm0) cm0max = cm0 cm0min = pmt.magnitude_to_moment(min(mags) - 0.5) cm0max = 2. * cm0 ax.plot(cum_dates, cum_m0s, color='black', alpha=0.5) for irun in clusters: cl_events = [] for iev, ev in enumerate(events): if irun == eventsclusters[iev]: cl_events.append(ev) # cl_events = [events[iev] for iev in len(events) # if irun == eventsclusters[iev]] print('A', irun, cl_events) cum_dates = [] d1 = dates.date2num(datetime.datetime.fromtimestamp(tmin)) cum_dates.append(d1) cum_m0s = [] cm0 = 0. cum_m0s.append(cm0) color = cluster_to_color(irun) for ev in cl_events: print(ev.name, ev.time) new_date = dates.date2num(datetime.datetime.fromtimestamp(ev.time)) cum_dates.append(new_date) cum_dates.append(new_date) cum_m0s.append(cm0) cm0 = cm0 + pmt.magnitude_to_moment(ev.magnitude) cum_m0s.append(cm0) cum_dates.append(dmax) cum_m0s.append(cm0) ax.plot(cum_dates, cum_m0s, color=color, alpha=0.5) ax.xaxis.set_major_locator(dates_loc) ax.xaxis.set_major_formatter(dates_format) plt.xlim(xmax=dmax, xmin=dmin) plt.ylim(ymax=cm0max, ymin=cm0min) plt.xticks(rotation=45.) plt.xlabel("Time") plt.ylabel("Cumulative Scalar Moment [Nm]") plt.yscale('log') plt.subplots_adjust(bottom=.3) figname = os.path.join(plotdir, 'plot_tcm0.' + conf.figure_format) f.savefig(figname)
from pyrocko import moment_tensor as pmt import numpy as num r2d = 180. / num.pi magnitude = 6.3 # Magnitude of the earthquake exp = pmt.magnitude_to_moment(magnitude) # convert the mag to moment in [Nm] # init pyrocko moment tensor m = pmt.MomentTensor(mnn=2.34 * exp, mee=-2.64 * exp, mdd=0.295 * exp, mne=1.49 * exp, mnd=0.182 * exp, med=-0.975 * exp) print(m) # print moment tensor # gives out both nodal planes: (s1, d1, r1), (s2, d2, r2) = m.both_strike_dip_rake() print('strike1=%g, dip1=%g, rake1=%g' % (s1, d1, r1)) print('strike2=%g, dip2=%g, rake2=%g' % (s2, d2, r2)) # p-axis normal vector in north-east-down coordinates p_ned = m.p_axis().A[0] print('p_ned=(%g, %g, %g)' % tuple(p_ned)) # convert to azimuth and dip
def test_rect_source(self): store = self.dummy_homogeneous_store() depth = 10 * km # shear rect1 = gf.RectangularSource(depth=10 * km, magnitude=5.0, width=5 * km, length=5 * km) rect2 = gf.RectangularSource( depth=depth, slip=pmt.magnitude_to_moment(5.0) / (5 * km * 5 * km * store.config.earthmodel_1d.material(depth).shear_modulus()), width=5 * km, length=5 * km) self.assertAlmostEqual( rect1.get_magnitude(), rect2.get_magnitude(store, gf.Target(interpolation='nearest_neighbor'))) # tensile rect3 = gf.RectangularSource(depth=depth, magnitude=5.0, width=5 * km, length=5 * km, opening_fraction=1.) rect4 = gf.RectangularSource( depth=depth, slip=pmt.magnitude_to_moment(5.0) / (5 * km * 5 * km * store.config.earthmodel_1d.material(depth).bulk()), width=5 * km, length=5 * km, opening_fraction=1.) self.assertAlmostEqual( rect3.get_magnitude(), rect4.get_magnitude(store, gf.Target(interpolation='nearest_neighbor'))) # mixed of = -0.4 rect5 = gf.RectangularSource(depth=depth, magnitude=5.0, width=5 * km, length=5 * km, opening_fraction=of) rect6 = gf.RectangularSource( depth=depth, slip=pmt.magnitude_to_moment(5.0) / (5 * km * 5 * km * (store.config.earthmodel_1d.material(depth).bulk() * abs(of) + store.config.earthmodel_1d.material(depth).shear_modulus() * (1 - abs(of)))), width=5 * km, length=5 * km, opening_fraction=of) self.assertAlmostEqual( rect5.get_magnitude(), rect6.get_magnitude(store, gf.Target(interpolation='nearest_neighbor')))
class Event(Object): '''Seismic event representation :param lat: latitude of hypocenter (default 0.0) :param lon: longitude of hypocenter (default 0.0) :param time: origin time as float in seconds after '1970-01-01 00:00:00 :param name: event identifier as string (optional) :param depth: source depth (optional) :param magnitude: magnitude of event (optional) :param region: source region (optional) :param catalog: name of catalog that lists this event (optional) :param moment_tensor: moment tensor as :py:class:`moment_tensor.MomentTensor` instance (optional) :param duration: source duration as float (optional) ''' lat = Float.T(default=0.0) lon = Float.T(default=0.0) time = Timestamp.T(default=util.str_to_time('1970-01-01 00:00:00')) name = String.T(default='', optional=True) depth = Float.T(optional=True) magnitude = Float.T(optional=True) magnitude_type = String.T(optional=True) region = String.T(optional=True) catalog = String.T(optional=True) moment_tensor = moment_tensor.MomentTensor.T(optional=True) duration = Float.T(optional=True) def __init__(self, lat=0., lon=0., time=0., name='', depth=None, magnitude=None, magnitude_type=None, region=None, load=None, loadf=None, catalog=None, moment_tensor=None, duration=None): vals = None if load is not None: vals = Event.oldload(load) elif loadf is not None: vals = Event.oldloadf(loadf) if vals: lat, lon, time, name, depth, magnitude, magnitude_type, region, \ catalog, moment_tensor, duration = vals Object.__init__(self, lat=lat, lon=lon, time=time, name=name, depth=depth, magnitude=magnitude, magnitude_type=magnitude_type, region=region, catalog=catalog, moment_tensor=moment_tensor, duration=duration) def time_as_string(self): return util.time_to_str(self.time) def set_name(self, name): self.name = name def olddump(self, filename): file = open(filename, 'w') self.olddumpf(file) file.close() def olddumpf(self, file): file.write('name = %s\n' % self.name) file.write('time = %s\n' % util.time_to_str(self.time)) if self.lat is not None: file.write('latitude = %.12g\n' % self.lat) if self.lon is not None: file.write('longitude = %.12g\n' % self.lon) if self.magnitude is not None: file.write('magnitude = %g\n' % self.magnitude) file.write('moment = %g\n' % moment_tensor.magnitude_to_moment(self.magnitude)) if self.magnitude_type is not None: file.write('magnitude_type = %s\n' % self.magnitude_type) if self.depth is not None: file.write('depth = %.10g\n' % self.depth) if self.region is not None: file.write('region = %s\n' % self.region) if self.catalog is not None: file.write('catalog = %s\n' % self.catalog) if self.moment_tensor is not None: m = self.moment_tensor.m() sdr1, sdr2 = self.moment_tensor.both_strike_dip_rake() file.write( ('mnn = %g\nmee = %g\nmdd = %g\nmne = %g\nmnd = %g\nmed = %g\n' 'strike1 = %g\ndip1 = %g\nrake1 = %g\n' 'strike2 = %g\ndip2 = %g\nrake2 = %g\n') % ((m[0, 0], m[1, 1], m[2, 2], m[0, 1], m[0, 2], m[1, 2]) + sdr1 + sdr2)) if self.duration is not None: file.write('duration = %g\n' % self.duration) @staticmethod def unique(events, deltat=10., group_cmp=(lambda a, b: cmp(a.catalog, b.catalog))): groups = Event.grouped(events, deltat) events = [] for group in groups: if group: group.sort(group_cmp) events.append(group[-1]) return events @staticmethod def grouped(events, deltat=10.): events = list(events) groups = [] for ia, a in enumerate(events): groups.append([]) haveit = False for ib, b in enumerate(events[:ia]): if abs(b.time - a.time) < deltat: groups[ib].append(a) haveit = True break if not haveit: groups[ia].append(a) groups = [g for g in groups if g] groups.sort(key=lambda g: sum(e.time for e in g) / len(g)) return groups @staticmethod def dump_catalog(events, filename=None, stream=None): if filename is not None: file = open(filename, 'w') else: file = stream try: i = 0 for ev in events: ev.olddumpf(file) file.write('--------------------------------------------\n') i += 1 finally: if filename is not None: file.close() @staticmethod def oldload(filename): with open(filename, 'r') as file: return Event.oldloadf(file) @staticmethod def oldloadf(file): d = {} try: for line in file: if line.lstrip().startswith('#'): continue toks = line.split(' = ', 1) if len(toks) == 2: k, v = toks[0].strip(), toks[1].strip() if k in ('name', 'region', 'catalog', 'magnitude_type'): d[k] = v if k in (('latitude longitude magnitude depth duration ' 'mnn mee mdd mne mnd med strike1 dip1 rake1 ' 'strike2 dip2 rake2 duration').split()): d[k] = float(v) if k == 'time': d[k] = util.str_to_time(v) if line.startswith('---'): d['have_separator'] = True break except Exception, e: raise FileParseError(e) if not d: raise EOF() if 'have_separator' in d and len(d) == 1: raise EmptyEvent() mt = None m6 = [d[x] for x in 'mnn mee mdd mne mnd med'.split() if x in d] if len(m6) == 6: mt = moment_tensor.MomentTensor(m=moment_tensor.symmat6(*m6)) else: sdr = [d[x] for x in 'strike1 dip1 rake1'.split() if x in d] if len(sdr) == 3: moment = 1.0 if 'moment' in d: moment = d['moment'] elif 'magnitude' in d: moment = moment_tensor.magnitude_to_moment(d['magnitude']) mt = moment_tensor.MomentTensor(strike=sdr[0], dip=sdr[1], rake=sdr[2], scalar_moment=moment) return (d.get('latitude', 0.0), d.get('longitude', 0.0), d.get('time', 0.0), d.get('name', ''), d.get('depth', None), d.get('magnitude', None), d.get('magnitude_type', None), d.get('region', None), d.get('catalog', None), mt, d.get('duration', None))
def testMagnitudeMoment(self): for i in range(1, 10): mag = float(i) assert ( abs(mag - moment_to_magnitude(magnitude_to_moment(mag))) < 1e-6 ), "Magnitude to moment to magnitude test failed."
def call(self): if not self.viewer_connected: self.get_viewer().about_to_close.connect( self.file_serving_worker.stop) self.viewer_connected = True try: from OpenGL import GL # noqa except ImportError: logger.warn('Could not find package OpenGL, ' 'if the map does not work try installing OpenGL\n' 'e.g. sudo pip install PyOpenGL') self.cleanup() try: viewer = self.get_viewer() cli_mode = False except NoViewerSet: viewer = None cli_mode = True if not cli_mode: if self.only_active: _, active_stations = \ self.get_active_event_and_stations() else: active_stations = viewer.stations.values() elif cli_mode: active_stations = self.stations station_list = [] if active_stations: for stat in active_stations: is_blacklisted = util.match_nslc(viewer.blacklist, stat.nsl()) if (viewer and not is_blacklisted) or cli_mode: xml_station_marker = XMLStationMarker( nsl='.'.join(stat.nsl()), longitude=float(stat.lon), latitude=float(stat.lat), active='yes') station_list.append(xml_station_marker) active_station_list = StationMarkerList(stations=station_list) if self.only_active: markers = [viewer.get_active_event_marker()] else: if cli_mode: markers = self.markers else: markers = self.get_selected_markers() if len(markers) == 0: tmin, tmax = self.get_selected_time_range(fallback=True) markers = [ m for m in viewer.get_markers() if isinstance(m, gui_util.EventMarker) and m.tmin >= tmin and m.tmax <= tmax ] ev_marker_list = [] for m in markers: if not isinstance(m, gui_util.EventMarker): continue xmleventmarker = convert_event_marker(m) if xmleventmarker is None: continue ev_marker_list.append(xmleventmarker) event_list = EventMarkerList(events=ev_marker_list) event_station_list = MarkerLists( station_marker_list=active_station_list, event_marker_list=event_list) event_station_list.validate() if self.map_kind != 'GMT': tempdir = self.marker_tempdir if self.map_kind == 'Google Maps': map_fn = 'map_googlemaps.html' elif self.map_kind == 'OpenStreetMap': map_fn = 'map_osm.html' url = 'http://localhost:' + str(self.port) + '/%s' % map_fn files = ['loadxmldoc.js', 'map_util.js', 'plates.kml', map_fn] snuffling_dir = op.dirname(op.abspath(__file__)) for entry in files: shutil.copy(os.path.join(snuffling_dir, entry), os.path.join(tempdir, entry)) logger.debug('copied data to %s' % tempdir) markers_fn = os.path.join(self.marker_tempdir, 'markers.xml') self.data_proxy.content_to_serve.emit(self.port) dump_xml(event_station_list, filename=markers_fn) if self.open_external: qg.QDesktopServices.openUrl(qc.QUrl(url)) else: global g_counter g_counter += 1 self.web_frame(url, name='Map %i (%s)' % (g_counter, self.map_kind)) else: lats_all = [] lons_all = [] slats = [] slons = [] slabels = [] for s in active_stations: slats.append(s.lat) slons.append(s.lon) slabels.append('.'.join(s.nsl())) elats = [] elons = [] elats = [] elons = [] psmeca_input = [] markers = self.get_selected_markers() for m in markers: if isinstance(m, gui_util.EventMarker): e = m.get_event() elats.append(e.lat) elons.append(e.lon) if e.moment_tensor is not None: mt = e.moment_tensor.m6() psmeca_input.append((e.lon, e.lat, e.depth / 1000., mt[0], mt[1], mt[2], mt[3], mt[4], mt[5], 1., e.lon, e.lat, e.name)) else: if e.magnitude is None: moment = -1. else: moment = moment_tensor.magnitude_to_moment( e.magnitude) psmeca_input.append( (e.lon, e.lat, e.depth / 1000., moment / 3., moment / 3., moment / 3., 0., 0., 0., 1., e.lon, e.lat, e.name)) lats_all.extend(elats) lons_all.extend(elons) lats_all.extend(slats) lons_all.extend(slons) lats_all = num.array(lats_all) lons_all = num.array(lons_all) if len(lats_all) == 0: return center_lat, center_lon = ortho.geographic_midpoint( lats_all, lons_all) ntotal = len(lats_all) clats = num.ones(ntotal) * center_lat clons = num.ones(ntotal) * center_lon dists = ortho.distance_accurate50m_numpy(clats, clons, lats_all, lons_all) maxd = num.max(dists) or 0. m = Map(lat=center_lat, lon=center_lon, radius=max(10000., maxd) * 1.1, width=35, height=25, show_grid=True, show_topo=True, color_dry=(238, 236, 230), topo_cpt_wet='light_sea_uniform', topo_cpt_dry='light_land_uniform', illuminate=True, illuminate_factor_ocean=0.15, show_rivers=False, show_plates=False) m.gmt.psxy(in_columns=(slons, slats), S='t15p', G='black', *m.jxyr) for i in range(len(active_stations)): m.add_label(slats[i], slons[i], slabels[i]) m.gmt.psmeca(in_rows=psmeca_input, S='m1.0', G='red', C='5p,0/0/0', *m.jxyr) tmpdir = self.tempdir() self.outfn = os.path.join(tmpdir, '%i.png' % self.figcount) m.save(self.outfn) f = self.pixmap_frame(self.outfn) # noqa
def plot_gnss(gnss_target, result, ifig, vertical=False): campaign = gnss_target.campaign item = PlotItem( name='fig_%i' % ifig, attributes={'targets': gnss_target.path}, title=u'Static GNSS Surface Displacements - Campaign %s' % campaign.name, description=u''' Static surface displacement from GNSS campaign %s (black vectors) and displacements derived from best model (red). ''' % campaign.name) event = source.pyrocko_event() locations = campaign.stations + [event] lat, lon = od.geographic_midpoint_locations(locations) if self.radius is None: coords = num.array([loc.effective_latlon for loc in locations]) radius = od.distance_accurate50m_numpy(lat[num.newaxis], lon[num.newaxis], coords[:, 0].max(), coords[:, 1]).max() radius *= 1.1 if radius < 30. * km: logger.warn('Radius of GNSS campaign %s too small, defaulting' ' to 30 km' % campaign.name) radius = 30 * km model_camp = gnss.GNSSCampaign(stations=copy.deepcopy( campaign.stations), name='grond model') for ista, sta in enumerate(model_camp.stations): sta.north.shift = result.statics_syn['displacement.n'][ista] sta.north.sigma = 0. sta.east.shift = result.statics_syn['displacement.e'][ista] sta.east.sigma = 0. if sta.up: sta.up.shift = -result.statics_syn['displacement.d'][ista] sta.up.sigma = 0. m = automap.Map(width=self.size_cm[0], height=self.size_cm[1], lat=lat, lon=lon, radius=radius, show_topo=self.show_topo, show_grid=self.show_grid, show_rivers=self.show_rivers, color_wet=(216, 242, 254), color_dry=(238, 236, 230)) all_stations = campaign.stations + model_camp.stations offset_scale = num.zeros(len(all_stations)) for ista, sta in enumerate(all_stations): for comp in sta.components.values(): offset_scale[ista] += comp.shift offset_scale = num.sqrt(offset_scale**2).max() m.add_gnss_campaign(campaign, psxy_style={ 'G': 'black', 'W': '0.8p,black', }, offset_scale=offset_scale, vertical=vertical) m.add_gnss_campaign(model_camp, psxy_style={ 'G': 'red', 'W': '0.8p,red', 't': 30, }, offset_scale=offset_scale, vertical=vertical, labels=False) if isinstance(problem, CMTProblem) \ or isinstance(problem, VLVDProblem): from pyrocko import moment_tensor from pyrocko.plot import gmtpy mt = event.moment_tensor.m_up_south_east() ev_lat, ev_lon = event.effective_latlon xx = num.trace(mt) / 3. mc = num.matrix([[xx, 0., 0.], [0., xx, 0.], [0., 0., xx]]) mc = mt - mc mc = mc / event.moment_tensor.scalar_moment() * \ moment_tensor.magnitude_to_moment(5.0) m6 = tuple(moment_tensor.to6(mc)) symbol_size = 20. m.gmt.psmeca(S='%s%g' % ('d', symbol_size / gmtpy.cm), in_rows=[(ev_lon, ev_lat, 10) + m6 + (1, 0, 0)], M=True, *m.jxyr) elif isinstance(problem, RectangularProblem): m.gmt.psxy(in_rows=source.outline(cs='lonlat'), L='+p2p,black', W='1p,black', G='black', t=60, *m.jxyr) elif isinstance(problem, VolumePointProblem): ev_lat, ev_lon = event.effective_latlon dV = abs(source.volume_change) sphere_radius = num.cbrt(dV / (4. / 3. * num.pi)) volcanic_circle = [ev_lon, ev_lat, '%fe' % sphere_radius] m.gmt.psxy(S='E-', in_rows=[volcanic_circle], W='1p,black', G='orange3', *m.jxyr) return (item, m)
def make_time_line(self, markers, stations=None, cmap=cmap): events = [m.get_event() for m in markers] kinds = num.array([m.kind for m in markers]) if self.cli_mode: self.fig = plt.figure() else: fframe = self.figure_frame() self.fig = fframe.gcf() ax = self.fig.add_subplot(311) ax_cum = ax.twinx() ax1 = self.fig.add_subplot(323) ax2 = self.fig.add_subplot(325, sharex=ax1) ax3 = self.fig.add_subplot(324, sharey=ax1) num_events = len(events) data = num.zeros((num_events, 6)) column_to_index = dict(zip(['magnitude', 'latitude', 'longitude', 'depth', 'time', 'kind'], range(6))) c2i = column_to_index for i, e in enumerate(events): if e.magnitude: mag = e.magnitude else: mag = 0. data[i, :] = mag, e.lat, e.lon, e.depth, e.time, kinds[i] s_coords = num.array([]) s_labels = [] if stations is not None: s_coords = num.array([(s.lon, s.lat, s.elevation-s.depth) for s in stations]) s_labels = ['.'.join(s.nsl()) for s in stations] isorted = num.argsort(data[:, c2i['time']]) data = data[isorted] def _D(key): return data[:, c2i[key]] tmin = _D('time').min() tmax = _D('time').max() lon_max = _D('longitude').max() lon_min = _D('longitude').min() lat_max = _D('latitude').max() lat_min = _D('latitude').min() depths_min = _D('depth').min() depths_max = _D('depth').max() mags_min = _D('magnitude').min() mags_max = _D('magnitude').max() moments = moment_tensor.magnitude_to_moment(_D('magnitude')) dates = list(map(datetime.fromtimestamp, _D('time'))) fds = mdates.date2num(dates) tday = 3600*24 tweek = tday*7 if tmax-tmin < 1*tday: hfmt = mdates.DateFormatter('%Y-%m-%d %H:%M:%S') elif tmax-tmin < tweek*52: hfmt = mdates.DateFormatter('%Y-%m-%d') else: hfmt = mdates.DateFormatter('%Y/%m') color_values = _D(self.color_by) color_args = dict(c=color_values, vmin=color_values.min(), vmax=color_values.max(), cmap=cmap) ax.scatter(fds, _D('magnitude'), s=20, **color_args) ax.xaxis.set_major_formatter(hfmt) ax.spines['top'].set_color('none') ax.spines['right'].set_color('none') ax.set_ylim((mags_min, mags_max*1.10)) ax.set_xlim(map(datetime.fromtimestamp, (tmin, tmax))) ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') ax.set_ylabel('Magnitude') init_pos = ax.get_position() ax_cum.plot(fds, num.cumsum(moments), 'grey') ax_cum.xaxis.set_major_formatter(hfmt) ax_cum.spines['top'].set_color('none') ax_cum.spines['right'].set_color('grey') ax_cum.set_ylabel('Cumulative seismic moment') lats_min = num.array([lat_min for x in range(num_events)]) lons_min = num.array([lon_min for x in range(num_events)]) if self.coord_system == 'cartesian': lats, lons = orthodrome.latlon_to_ne_numpy( lats_min, lons_min, _D('latitude'), _D('longitude')) _x = num.empty((len(s_coords), 3)) for i, (slon, slat, sele) in enumerate(s_coords): n, e = orthodrome.latlon_to_ne(lat_min, lon_min, slat, slon) _x[i, :] = (e, n, sele) s_coords = _x else: lats = _D('latitude') lons = _D('longitude') s_coords = s_coords.T ax1.scatter(lons, lats, s=20, **color_args) ax1.set_aspect('equal') ax1.grid(True, which='both') ax1.set_ylabel('Northing [m]') ax1.get_yaxis().tick_left() if len(s_coords): ax1.scatter(s_coords[0], s_coords[1], marker='v', s=40, color='black') for c, sl in zip(s_coords.T, s_labels): ax1.text(c[0], c[1], sl, color='black') # bottom left plot ax2.scatter(lons, _D('depth'), s=20, **color_args) ax2.grid(True) ax2.set_xlabel('Easting [m]') ax2.set_ylabel('Depth [m]') ax2.get_yaxis().tick_left() ax2.get_xaxis().tick_bottom() ax2.invert_yaxis() ax2.text(1.1, 0, 'Origin at:\nlat=%1.3f, lon=%1.3f' % (lat_min, lon_min), transform=ax2.transAxes) # top right plot ax3.scatter(_D('depth'), lats, s=20, **color_args) ax3.set_xlim((depths_min, depths_max)) ax3.grid(True) ax3.set_xlabel('Depth [m]') ax3.get_xaxis().tick_bottom() ax3.get_yaxis().tick_right() self.fig.subplots_adjust( bottom=0.05, right=0.95, left=0.075, top=0.95, wspace=0.02, hspace=0.02) init_pos.y0 += 0.05 ax.set_position(init_pos) ax_cum.set_position(init_pos) if self.cli_mode: plt.show() else: self.fig.canvas.draw()