-
Notifications
You must be signed in to change notification settings - Fork 1
/
bp_streamed_parallel_make_beam_test.py
234 lines (219 loc) · 8.92 KB
/
bp_streamed_parallel_make_beam_test.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
import sys,os
import obspy
from obspy.taup import TauPyModel
from obspy.geodetics import locations2degrees
from obspy.geodetics.base import gps2dist_azimuth
from obspy.signal.trigger import recursive_sta_lta_py
from scipy import signal
import numpy as np
import pandas as pd
from datetime import datetime, timedelta
import multiprocessing as mp
import time
###########
import bp_lib
import math
def moving_average(x, w):
"""
Computes the moving average of a 2D numpy array x with a window size of w.
"""
return np.convolve(x, np.ones(w), 'same') / w
time_start = time.process_time()
try:
name = sys.argv[1]
print('Input experiment is :',(name))
except:
print('You did not provided experiment name (foleder). Aborting.')
exit()
#name='KYR_7.0_EU_13.0km_iasp91_0.2_grid_'
path = os.getcwd()
outdir = name #str(Event)+'_'+str(Exp_name)
input = pd.read_csv('./'+name+'/input.csv',header=None)
a=input.to_dict('series')
keys = a[0][:]
values = a[1][:]
res = {}
for i in range(len(keys)):
res[keys[i]] = values[i]
#print(keys[i],values[i])
##########################################################################
'''
bp_l=0.4
bp_u=8
smooth_time_window=10
smooth_space_window=1
peak_scale=10
stack_start=30
stack_end=200
STF_start=0
STF_end=150
'''
## BP parameters from the input file
try:
bp_l = float(sys.argv[2])
bp_u = float(sys.argv[3])
print('bp_l and bp_u is:',(bp_l,bp_u))
except:
bp_l = float(res['bp_l']) #Hz
bp_u = float(res['bp_u']) #Hz
smooth_time_window = int(res['smooth_time_window']) #seconds
smooth_space_window = int(res['smooth_space_window'])
stack_start = int(res['stack_start']) #in seconds
stack_end = int(res['stack_end']) #in seconds
STF_start = int(res['STF_start'])
STF_end = int(res['STF_end'])
sps = int(res['sps']) #samples per seconds
threshold_correlation=float(res['threshold_correlation'])
SNR=float(res['SNR'])
#bp_l=0.8
#bp_u=5
# Event info
Event=res['Event']
event_lat=float(res['event_lat'])
event_long=float(res['event_long'])
event_depth=float(res['event_depth'])
Array_name=res['Array_name']
#Exp_name=res['Exp_name']
azimuth_min=float(res['azimuth_min'])
azimuth_max=float(res['azimuth_max'])
backazimuth_min=float(res['backazimuth_min'])
backazimuth_max=float(res['backazimuth_max'])
dist_min=float(res['dist_min'])
dist_max=float(res['dist_max'])
origin_time=obspy.UTCDateTime(int(res['origin_year']),int(res['origin_month']),
int(res['origin_day']),int(res['origin_hour']),int(res['origin_minute']),float(res['origin_seconds']))
print(origin_time)
Focal_mech = dict(strike=float(res['event_strike']), dip=float(res['event_dip']), rake=float(res['event_rake'])
, magnitude=float(res['event_magnitude']))
model = TauPyModel(model=str(res['model']))
sps = int(res['sps']) #samples per seconds
threshold_correlation=float(res['threshold_correlation'])
SNR=float(res['SNR'])
#smooth_time_window = int((stack_end-stack_start)/10) #int(res['smooth_time_window']) #seconds
source_grid_size = float(res['source_grid_size']) #degrees
source_grid_extend = float(res['source_grid_extend']) #degrees
source_depth_size = float(res['source_depth_size']) #km
source_depth_extend = float(res['source_grid_extend']) #km
#stream_for_bp=obspy.read('./Turky_7.6_all/stream.mseed')
slong,slat = bp_lib.make_source_grid(event_long,event_lat,source_grid_extend,source_grid_size)
stations_file = str(res['stations'])
stream_for_bp= obspy.read('./'+name+'/stream.mseed')
beam_info = np.load('./'+name+'/beam_info.npy',allow_pickle=True)
stream_info = np.load('./'+name+'/array_bp_info.npy',allow_pickle=True)
print('#############################################################################\n')
print('Exp:',name)
print('Origin time:',origin_time)
print('Long= %f Lat= %f Depth= %f' % (event_long,event_lat,event_depth))
print('bp_low= %f bp_high= %f Correlation threshold= %f SNR= %f'% (bp_l,bp_u,threshold_correlation,SNR))
print('#############################################################################\n')
print('Done loading data.')
print('Total time taken:',time.process_time() - time_start)
print('Now gathering stream information..')
sta_name=list(stream_info[:,1])
for t in stream_for_bp:
if len(t.stats['station'].split('.')) > 1:
sta = t.stats.station+str('H')
else:
sta = t.stats.station
#net
if sta in sta_name:
ind = sta_name.index(sta)
t.stats['origin_time'] = origin_time
t.stats['station_longitude'] = float(stream_info[ind,2])
t.stats['station_latitude'] = float(stream_info[ind,3])
t.stats['Dist'] = float(stream_info[ind,4])
t.stats['Azimuth'] = float(stream_info[ind,5])
arrivals = model.get_travel_times(source_depth_in_km=event_depth,distance_in_degree=t.stats.Dist,phase_list=["P"])
arr = arrivals[0]
t_travel = arr.time;
t.stats['P_arrival'] = origin_time + t_travel + timedelta(hours=9)
#t.stats['P_arrival'] = float(stream_info[ind,6])
t.stats['Corr_coeff'] = float(stream_info[ind,7])
t.stats['Corr_shift'] = float(stream_info[ind,8])
t.stats['Corr_sign'] = float(stream_info[ind,9])
#t.stats['Backazimuth'] = float(stream_info[ind,10])
else:
pass
#print('Something is not right.')
Ref_station_index=bp_lib.get_ref_station(stream_for_bp)
ref_trace = stream_for_bp[Ref_station_index]
print('Done gathering stream information.')
print('Total time taken:',time.process_time() - time_start)
print('Now computing station weight..')
for tr in stream_for_bp:
count=0;
for tr_ in stream_for_bp:
dist=((tr.stats.station_latitude-tr_.stats.station_latitude)**2 +
(tr.stats.station_longitude-tr_.stats.station_longitude)**2 )**0.2;
if ( dist <= 1):
count=count+1;
else:
continue
tr.stats['Station_weight'] = count
print('Done computing station weight.')
print('Total time taken:',time.process_time() - time_start)
print('Now making the beam...')
##########################################################################
# Make beam
beam_info_reshaped=beam_info.reshape(len(slat),len(stream_for_bp),4)
'''
beam=[] #obspy.Stream()
for j in range(len(beam_info_reshaped)):
source = beam_info_reshaped[j]
stream_source=stream_for_bp.copy()
for i in range(len(source)):
tr = stream_source.select(station=source[i][2])
arrival=source[i][3]+tr[0].stats.Corr_shift
tr.trim(arrival-stack_start,arrival+stack_end)
tr.detrend('linear')
tr.normalize()
stream_use=stream_source.copy()
#stack=stream_use.stack('linear')
stack=[]
for tr in stream_use:
tr.filter('bandpass',freqmin=bp_l,freqmax=bp_u,corners=5)
tr.detrend("linear")
cut = tr.data * tr.stats.Corr_coeff #/tr.stats.Station_weight
#tr.normalize()
stack.append(cut[0:int((stack_start+stack_end)*sps)])
#print(np.shape(stack))
#stack_reshaped = np.array(stack).reshape((len(stream_for_bp), -1))
#beam.append(np.sum(stack_reshaped,axis=0))
beam.append(np.sum(stack,axis=0))
#print("Progress =",((j/len(beam_info_reshaped))*100),"%" )
#do some stuff
print('Done making the beam.')
print('Total time taken:',time.process_time() - time_start)
print('Saving the beam.')
file_save='beam_'+str(bp_l)+'_'+str(bp_u)+'_'+str(Array_name)+'.dat'
np.savetxt(outdir+'/'+file_save,beam)
print('Total time taken:',time.process_time() - time_start)
'''
def process_beam(j):
source = beam_info_reshaped[j]
stream_source=stream_for_bp.copy()
for i in range(len(source)):
tr = stream_source.select(station=source[i][2])
arrival=source[i][3]+tr[0].stats.Corr_shift
tr.trim(arrival-stack_start,arrival+stack_end)
tr.detrend('linear')
tr.normalize()
stream_use=stream_source.copy()
stack=[]
for tr in stream_use:
tr.filter('bandpass',freqmin=bp_l,freqmax=bp_u,corners=5)
tr.detrend("linear")
cut = tr.data * tr.stats.Corr_coeff/tr.stats.Station_weight
stack.append(cut[0:int((stack_start+stack_end)*sps)])
return np.sum(stack,axis=0)
if __name__ == '__main__':
# Make beam
beam_info_reshaped=beam_info.reshape(len(slat),len(stream_for_bp),4)
time_start = time.process_time()
beam=[] #obspy.Stream()
with mp.Pool() as pool:
results = pool.map(process_beam, range(len(beam_info_reshaped)))
beam = [r for r in results]
print('Total time taken:',time.process_time() - time_start)
file_save='beam_test_pool'+str(bp_l)+'_'+str(bp_u)+'_'+str(Array_name)+'.dat'
np.savetxt(outdir+'/'+file_save,beam)