def test_beachball(self): """ Create beachball examples in tests/output directory. """ # http://en.wikipedia.org/wiki/File:USGS_sumatra_mts.gif data = [[0.91, -0.89, -0.02, 1.78, -1.55, 0.47], [274, 13, 55], [130, 79, 98], [264.98, 45.00, -159.99], [160.55, 76.00, -46.78], [1.45, -6.60, 5.14, -2.67, -3.16, 1.36], [235, 80, 35], [138, 56, 168], # Explosion [1, 1, 1, 0, 0, 0], # Implosion [-1, -1, -1, 0, 0, 0], # CLVD - Compensate Linear Vector Dipole [1, -2, 1, 0, 0, 0], # Double Couple [1, -1, 0, 0, 0, 0], # Lars [1, -1, 0, 0, 0, -1], # http://wwweic.eri.u-tokyo.ac.jp/yuji/Aki-nada/ [179, 55, -78], [10, 42.5, 90], [10, 42.5, 92], # http://wwweic.eri.u-tokyo.ac.jp/yuji/tottori/ [150, 87, 1], # http://iisee.kenken.go.jp/staff/thara/2004/09/20040905_1/ # 2nd.html [0.99, -2.00, 1.01, 0.92, 0.48, 0.15], # http://iisee.kenken.go.jp/staff/thara/2004/09/20040905_0/ # 1st.html [5.24, -6.77, 1.53, 0.81, 1.49, -0.05], # http://iisee.kenken.go.jp/staff/thara/miyagi.htm [16.578, -7.987, -8.592, -5.515, -29.732, 7.517], # http://iisee.kenken.go.jp/staff/thara/20050613/chile.html [-2.39, 1.04, 1.35, 0.57, -2.94, -0.94], ] filenames = ['bb_sumatra_mt.png', 'bb_sumatra_np1.png', 'bb_sumatra_np2.png', 'bb_19950128_np1.png', 'bb_19950128_np2.png', 'bb_20090102_mt.png', 'bb_20090102_np1.png', 'bb-20090102-np2.png', 'bb_explosion.png', 'bb_implosion.png', 'bb_clvd.png', 'bb_double_couple.png', 'bb_lars.png', 'bb_geiyo_np1.png', 'bb_honshu_np1.png', 'bb_honshu_np2.png', 'bb_tottori_np1.png', 'bb_20040905_1_mt.png', 'bb_20040905_0_mt.png', 'bb_miyagi_mt.png', 'bb_chile_mt.png', ] for data_, filename in zip(data, filenames): with ImageComparison(self.path, filename) as ic: beachball(data_, outfile=ic.name)
def Beachball(self, moment): params = { 'legend.fontsize': 'x-large', 'figure.figsize': (15, 15), 'axes.labelsize': 25, 'axes.titlesize': 'x-large', 'xtick.labelsize': 25, 'ytick.labelsize': 25 } pylab.rcParams.update(params) try: beachball(moment, size=200, linewidth=2, facecolor='b') plt.show() except TypeError: print("TypeError")
def beachBall(strike,dip,rake,mrr,mtt,mpp,mrt,mrp,mtp,plot_file): """ Plotting the focal mechanism """ # sets figure's dimensions _fig_x = 10 _fig_y = 10 fig = plt.figure(figsize=(_fig_x,_fig_y)) # mt beach.beachball([mrr,mtt,mpp,mrt,mrp,mtp], facecolor='r', fig=fig) # dc beach.beachball([strike,dip,rake], nofill=True, fig=fig) fig.savefig(plot_file)
def save_event_beachball(idx, df, bb_type='tensor', fig_format='svg', directory='./', use_dir_format=True, bb_linewidth=2, bb_size=20, bb_width=100, bb_color='b'): fig = plt.figure(1) if bb_type == 'double_couple': mt = df.ix[idx][['Strike_1', 'Dip_1', 'Rake_1']] elif bb_type == 'tensor': mt = df.ix[idx][['Mrr', 'Mtt', 'Mpp', 'Mrt', 'Mrp', 'Mtp']] event = df.ix[i, 'Event'] beachball(mt, linewidth=bb_linewidth, size=bb_size, width=bb_width, outfile='{}/{}.{}'.format(directory, event, fig_format), fig=fig, facecolor=bb_color) plt.close(fig)
def test_mopad_fallback(self, image_path): """ Test the fallback to mopad. """ mt = [0.000, -1.232e25, 1.233e25, 0.141e25, -0.421e25, 2.531e25] with WarningsCapture() as w: # Always raise warning. beachball(mt, outfile=image_path) # Make sure the appropriate warnings has been raised. assert w # Filter w = [_i.message.args[0] for _i in w] w = [ _i for _i in w if "falling back to the mopad wrapper" in _i.lower() ] assert w
def test_mopad_fallback(self): """ Test the fallback to mopad. """ mt = [0.000, -1.232e25, 1.233e25, 0.141e25, -0.421e25, 2.531e25] with warnings.catch_warnings(record=True) as w: # Always raise warning. warnings.simplefilter("always") with ImageComparison(self.path, 'mopad_fallback.png') as ic: beachball(mt, outfile=ic.name) # Make sure the appropriate warnings has been raised. self.assertTrue(w) # Filter w = [_i.message.args[0] for _i in w] w = [_i for _i in w if "falling back to the mopad wrapper" in _i.lower()] self.assertTrue(w)
def plot_beachball_obspy(cat, **kwargs): # default if 'facecolor' not in kwargs.keys(): kwargs['facecolor'] = [0.5] * 3 if 'width' not in kwargs.keys(): kwargs['width'] = 600 if cat[0].preferred_focal_mechanism is None: logger.warning('nothing to do, the catalog does not have a ' 'preferred focal mechanism') np1 = cat[0].preferred_focal_mechanism().nodal_planes.nodal_plane_1 strike = np1['strike'] dip = np1['dip'] rake = np1['rake'] fm = [strike, dip, rake] beachball(fm, **kwargs) return plt.gca()
def get_beachballs(self, strike, dip, rake, M0, savepath): rdip = np.deg2rad(dip) rstr = np.deg2rad(strike) rrake = np.deg2rad(rake) nx = -np.sin(rdip) * np.sin(rstr) ny = np.sin(rdip) * np.cos(rstr) nz = -np.cos(rdip) dx = np.cos(rrake) * np.cos(rstr) + np.cos(rdip) * np.sin( rrake) * np.sin(rstr) dy = np.cos(rrake) * np.sin(rstr) - np.cos(rdip) * np.sin( rrake) * np.cos(rstr) dz = -np.sin(rdip) * np.sin(rrake) # dx = np.cos(rrake)*np.cos(rstr)+np.cos(rdip)*np.sin(rrake)*np.sin(rstr) # dy = -np.cos(rrake)*np.sin(rstr)+np.cos(rdip)*np.sin(rrake)*np.cos(rstr) # dz = np.sin(rdip) *np.sin(rrake) Mxx = M0 * 2 * dx * nx Myy = M0 * 2 * dy * ny Mzz = M0 * 2 * dz * nz Mxy = M0 * dx * ny + dy * nx Mxz = M0 * dx * nz + dz * nx Myz = M0 * dy * nz + dz * ny moment = np.array([Mxx, Myy, Mzz, Mxy, Mxz, Myz]) stations = { 'names': ['S01', 'S02', 'S03', 'S04'], 'azimuth': np.array([120., 5., 250., 75.]), 'takeoff_angle': np.array([30., 60., 45., 10.]), 'polarity': np.array([0.8, 0.5, 0.7, -0.9]) } # MTplot(np.array([[1], [0], [-1], [0], [0], [0]]), 'beachball', stations=stations, fault_plane=True) beachball(moment, size=200, linewidth=2, facecolor='b', outfile=savepath)
import matplotlib.pyplot as plt import numpy as np import obspy import pandas as pd from obspy.imaging.beachball import beachball from obspy.imaging.beachball import beach from obspy.imaging.source import plot_radiation_pattern fault = [] st = input('Strike:') fault.append(float(st)) dp = input('Dip: ') fault.append(float(dp)) rk = input('Rake: ') fault.append(float(rk)) fig = beachball(fault)
def test_BeachBallOutputFormats(self): """ Tests various output formats. """ fm = [115, 35, 50] # PDF data = beachball(fm, format='pdf') self.assertEqual(data[0:4], b"%PDF") # as file # create and compare image with NamedTemporaryFile(suffix='.pdf') as tf: beachball(fm, format='pdf', outfile=tf.name) # PS data = beachball(fm, format='ps') self.assertEqual(data[0:4], b"%!PS") # as file with NamedTemporaryFile(suffix='.ps') as tf: beachball(fm, format='ps', outfile=tf.name) # PNG data = beachball(fm, format='png') self.assertEqual(data[1:4], b"PNG") # as file with NamedTemporaryFile(suffix='.png') as tf: beachball(fm, format='png', outfile=tf.name) # SVG data = beachball(fm, format='svg') self.assertEqual(data[0:5], b"<?xml") # as file with NamedTemporaryFile(suffix='.svg') as tf: beachball(fm, format='svg', outfile=tf.name)
def parsexml(url): return read_events(url) # =================================== main_event = {'unid': '20170919_0000091'} from obspy.imaging.beachball import beachball #url= "http://vigogne.emsc-csem.org/mtws/api/search\ #?source_catalog=USGS&eventid=20170919_0000091&format=text" url = "http://www.seismicportal.eu/mtws/api/search\ ?source_catalog=USGS&eventid=20170919_0000091&format=text" mt = parsecsv(geturl(url)['content'], usedict=True)[0] #we get a list with only one element. t = map(float, [ mt['mt_mrr'], mt['mt_mtt'], mt['mt_mpp'], mt['mt_mrt'], mt['mt_mrp'], mt['mt_mtp'] ]) print '=' * 46 print "{mt_source_catalog} Solution, Strike: {mt_strike_1}, Dip: {mt_dip_1}, Rake: {mt_rake_1}".format( **mt) print '=' * 46 beachball(t, width=200)
# formulas from Aki & Richards Box 4.4 # mt(1-6): Mrr, Mtt, Mff, Mrt, Mrf, Mtf # mt(1-6): Mzz, Mxx, Myy, Mzx, -Mzy, -Mxy mt = [ sr * sd2, -1. * sd * cr * ss2 - sd2 * sr * ss * ss, sd * cr * ss2 - sd2 * sr * cs * cs, -1. * cd * cr * cs - cd2 * sr * ss, cd * cr * ss - cd2 * sr * cs, -1. * sd * cr * cs2 - 0.5 * sd2 * sr * ss2 ] return mt m1 = 1.0 fault1 = [0, 90, 0] mt1 = getmt(fault1) print('MT 1: ', mt1) m2 = 0.2 fault2 = [135, 45, -90] mt2 = getmt(fault2) print('MT 2: ', mt2) sum_mt = [(m1 * a) + (m2 * a) for a, b, in zip(mt1, mt2)] print('Sum MT: ', sum_mt) compmt = getplanes(sum_mt) print(compmt) fig = beachball(fm=[0.0, -0.0, 0.0, -7.347880794884119e-17, 0.0, -1.2])
def test_beachball_output_format(self): """ Tests various output formats. """ fm = [115, 35, 50] # PDF - Some matplotlib versions internally raise some warnings here # which we don't want to see in the tests. with warnings.catch_warnings(): warnings.simplefilter("ignore") data = beachball(fm, format='pdf') assert data[0:4] == b"%PDF" # as file # create and compare image with NamedTemporaryFile(suffix='.pdf') as tf: beachball(fm, format='pdf', outfile=tf.name) # PS data = beachball(fm, format='ps') assert data[0:4] == b"%!PS" # as file with NamedTemporaryFile(suffix='.ps') as tf: beachball(fm, format='ps', outfile=tf.name) # PNG data = beachball(fm, format='png') assert data[1:4] == b"PNG" # as file with NamedTemporaryFile(suffix='.png') as tf: beachball(fm, format='png', outfile=tf.name) # SVG data = beachball(fm, format='svg') assert data[0:5] == b"<?xml" # as file with NamedTemporaryFile(suffix='.svg') as tf: beachball(fm, format='svg', outfile=tf.name)
""" Make Focal Mech Plots reads hash_df output file """ from obspy.imaging.beachball import beachball from obspy.core import UTCDateTime import pandas as pd import numpy as np import matplotlib.pyplot as plt plt.close('all') file = 'casc2.out' #hash_df solutions fm_save_dir = '/Users/travisalongi/Cascadia/Figures/Focal_mechs/Run3/' #where to save mechs columns = ['evid','yr', 'mon', 'day', 'hr', 'mn', 'sec', 'ev_type', 'mag', 'mag_type', 'lat', 'lon', 'depth', 'loc_qual', 'rms', 'xy_err', 'z_err', 'time_err', 'n_arr', 'n_p', 'n_s', 'strike', 'dip', 'rake', 'fp_uncert', 'aux_uncert', 'n_p_fm', 'pct_misfit', 'fm_quality', 'prob_fm_solution', 'stn_dist_ratio', 's/p_ratio', 'avg_sp_misfit', 'mult_flag'] hash_df = pd.read_csv(file, sep = '\s+', names = columns) hash_df = hash_df.set_index('evid') #index by event id #%% # make obspy beachballs for all HASH solutions plt.ioff() for index, row in hash_df.iterrows(): date = UTCDateTime(row.yr, row.mon, row.day, row.hr, row.mn)
def plot_beachball(filename=None,strike=None,dip=None,rake=None,M0=None): """ reads in CMT solution and plots a beachball """ # obspy uses moment tensor as in # mt = [0.91, -0.89, -0.02, 1.78, -1.55, 0.47] # reads in CMT solution if not filename is None: # # note: obspy.read_events(filename) could also read in CMTSOLUTION format: # > cat = obspy.read_events(filename,format="CMTSOLUTION") # > print(cat) # however it assumes a correct Flinn-Engdahl region which might not hold for UTM coordinates or test CMTs # thus reading in manually moment_tensor = read_CMT(filename) if not strike is None: print("given strike/dip/rake/M0 = ",strike,dip,rake,M0) print("") # limits range: # strike in [0,360] (from North, clockwise) if strike < 0.0 or strike > 360.0: print("invalid strike, must be between 0 and 360 degrees") sys.exit(1) # dip in [0,90] if dip < 0.0 or dip > 90.0: print("invalid dip, must be between 0 and 90 degrees") sys.exit(1) # rake in [-180,180] if rake < -180.0 or rake > 180.0: print("invalid rake, must be between -180 and 180 degrees") sys.exit(1) # angle to rad strike *= pi/180.0 dip *= pi/180.0 rake *= pi/180.0 # converts to moment tensor mt = convert_SDR_to_MT(strike,dip,rake,M0) moment_tensor = [mt] print("moment tensor MT (Mrr Mtt Mpp Mrt Mrp Mtp):") print(moment_tensor) print("") # moment-tensor array can hold several single CMTs. # we will plot for each one a beachball for i in range(len(moment_tensor)): print("moment tensor ",i+1,":") mt = moment_tensor[i] # scalar moment M0 M0 = get_scalar_moment(mt) # moment magnitude Mw Mw = get_moment_magnitude(mt) print(" magnitude of the source:") print(" scalar moment M0 = ",M0,"dyne-cm") print(" moment magnitude Mw = ",Mw) print("") # strike, dip, and rake info strike,dip,rake = convert_MT_to_SDR(mt,verbose=True) print(" strike/dip/rake = ",strike,"/",dip,"/",rake) print("") # plotting print(" plotting beachball") fig = beachball(mt, size=200, linewidth=2, facecolor='r') # saves figure if len(moment_tensor) == 1: outfile = "beachball" + ".png" else: outfile = "beachball_{}".format(i+1) + ".png" fig.savefig(outfile) print(" saved to: ",outfile) # statistics #for i in range(0,36+1): # strike = i*10.0 # for j in range(0,9+1): # dip = j*10.0 # for k in range(-18,18+1): # rake = k*10.0 # mt = convert_SDR_to_MT(strike,dip,rake,M0) # strike_out,dip_out,rake_out = convert_MT_to_SDR(mt) # print(" strike/dip/rake = ",strike,"/",dip,"/",rake) # print("out strike/dip/rake = ",strike_out,"/",dip_out,"/",rake_out) return
from obspy.imaging.beachball import beachball from obspy import read mt = [0.0, -1.0, 1.0, 0.0, 0.0, -0.4] fig = beachball(mt, width=600) fig.savefig('focalmech.png')
def test_beachball_output_format(self): """ Tests various output formats. """ fm = [115, 35, 50] # PDF - Some matplotlib versions internally raise some warnings here # which we don't want to see in the tests. with warnings.catch_warnings(): warnings.simplefilter("ignore") data = beachball(fm, format='pdf') self.assertEqual(data[0:4], b"%PDF") # as file # create and compare image with NamedTemporaryFile(suffix='.pdf') as tf: beachball(fm, format='pdf', outfile=tf.name) # PS data = beachball(fm, format='ps') self.assertEqual(data[0:4], b"%!PS") # as file with NamedTemporaryFile(suffix='.ps') as tf: beachball(fm, format='ps', outfile=tf.name) # PNG data = beachball(fm, format='png') self.assertEqual(data[1:4], b"PNG") # as file with NamedTemporaryFile(suffix='.png') as tf: beachball(fm, format='png', outfile=tf.name) # SVG data = beachball(fm, format='svg') self.assertEqual(data[0:5], b"<?xml") # as file with NamedTemporaryFile(suffix='.svg') as tf: beachball(fm, format='svg', outfile=tf.name)
import numpy as np from obspy.imaging.beachball import beachball import matplotlib.pyplot as plt data = np.genfromtxt('TEST_DATA.txt') mts = np.array(data[:, 3:9]) exp = np.array(data[:, 9]) mts = [mts[i, :] * 10**exp[i] for i in range(len(exp))] mt_sum = np.sum(mts, axis=0) print(sum) beachball(sum) plt.show() ### Mrr -9.2557e26 # my results: [-9.255760e+26 1.911197e+27 -9.823480e+26 -1.706900e+25 3.282760e+26 # -1.650034e+27]
ColorMap = Make_Colormap([ (0.0, 0.0, 1.0), c('cyan'), (np.median(magnitude) - 2 * magnitude.std()) / magnitude.max(), c('cyan'), (0.2, 0.6, 0.2), (np.median(magnitude) / magnitude.max()), (0.2, 0.6, 0.2), c('yellow'), (np.median(magnitude) + 2 * magnitude.std()) / magnitude.max(), c('yellow'), (1.0, 0.0, 0.0) ]) # Toss balls in ballbin, i.e. create png files of moment tensors for kmz os.chdir('Ballbin') for i in range(0, data.shape[0]): ball = beachball([strike[i], dip[i], rake[i]], size=1000, linewidth=2, facecolor=ColorMap(depth[i] / depth.max()), outfile='%s.png' % i) plt.close() # Make directory for legends os.chdir('..') os.mkdir('Legends') os.chdir('Legends') # Create a plot showing depth color bar aka legend 1 a = np.outer(np.arange(0, 1, 0.01), np.ones(10)) legend1, ax1 = plt.subplots() ax1.imshow(a,cmap=ColorMap, origin='lower', extent=[0,1,0,depth.max()], \ aspect=6/depth.max()) ax1.axes.get_xaxis().set_visible(False)
print(sum) print(np.max(data[:, 2])) mt = [-2.39, 1.04, 1.35, 0.57, -2.94, -0.94] test = [-2.39, 0.57, -2.94, 0.57, 1.04, -0.94, -2.94, -0.94, 1.35] test = np.reshape(test, (3, 3)) print(test) w, v = eig(test) print('w: ', w) print('v: ', v) beachball(mt) print('done') mt = [1.73, -0.427, -0.61, 2.98, -2.4, 0.426] mt_test = [1.73, 2.98, -2.4, 2.98, -0.427, 0.426, -2.4, 0.426, -0.61] mt_test = np.reshape(mt_test, (3, 3)) print(mt_test) w, v = eig(mt_test) print('w: ', w) print('v: ', v) beachball(mt) p0 = [0.81400949, 0.57927701, -0.04273997] p1 = [0.46635507, -0.60791683, 0.64261192] p2 = [-0.34626796, 0.5430242, 0.76499884]
from obspy.imaging.beachball import beachball mt = [0.91, -0.89, -0.02, 1.78, -1.55, 0.47] beachball(mt, size=200, linewidth=2, facecolor='b') mt2 = [150, 87, 1] beachball(mt2, size=200, linewidth=2, facecolor='r') mt3 = [-2.39, 1.04, 1.35, 0.57, -2.94, -0.94] beachball(mt3, size=200, linewidth=2, facecolor='g')
def beachball(self, color='gray'): """makes obspy beachball""" beachball([self.strike, self.dip, self.rake], facecolor=color)
mrays = mars.get_ray_paths(source_depth_in_km=55, distance_in_degree=40, phase_list=["P", "S"]) mrays.plot_rays() # source (strike, dip, rake) and P, S velocities at source depth. # thrust fault thats roughly orientated like the faults on the CF fault = [120, 45, 90] mt = getmt(fault) # manual input from the models based on the depth of the marsquake (unknown so can be done later) Pvelz = 5.84666 Svelz = 3.28116 from obspy.imaging.beachball import beachball beachball(mt, size=200, linewidth=2, facecolor='b') # configuration: azimuth = 270 #from the marsquake to the station # exit angles based on velocity at depth iP = np.degrees(np.arcsin(Pvelz * Pp / radius)) jS = np.degrees(np.arcsin(Svelz * Sp / radius)) print('P exit at ', iP) print('S exit at ', jS) P, SV, SH = Rpattern(fault, azimuth, [iP, jS]) print(P, SV, SH) from obspy.imaging.source import plot_radiation_pattern plot_radiation_pattern(mt, kind=['p_sphere', 'beachball', 's_sphere', 's_quiver'], coordinate_system='RTP',
def plot_beachball(filename, mt): """ Plots source mechanism """ beachball(mt, size=200, linewidth=2, facecolor='b') pyplot.savefig(filename)