-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy patharray_functions.py
More file actions
1721 lines (1358 loc) · 62.2 KB
/
array_functions.py
File metadata and controls
1721 lines (1358 loc) · 62.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import pandas as pd
import numpy as np
import matplotlib.dates as mdates
import datetime as dt
from scipy.optimize import least_squares
import lts_array
#Obspy dependencies-----------------------------
from obspy.clients.fdsn import Client
from obspy import read
from obspy import read_events
from obspy import read_inventory
from obspy import Stream
from obspy import UTCDateTime
from obspy.taup import TauPyModel
from obspy.core.util import AttribDict
from obspy.signal.array_analysis import array_processing
from obspy.geodetics import gps2dist_azimuth
from obspy.geodetics import kilometers2degrees
from obspy.signal.util import util_geo_km
from obspy.signal.trigger import trigger_onset, classic_sta_lta
from obspy.clients.fdsn.header import FDSNNoDataException
############################################################
#### FUNCTIONS FOR ARRAY CALCULATION ###########################
############################################################
def least_trimmed_squares(processing, st, sta_lats, sta_lons, WINDOW_LENGTH,
WINDOW_OVERLAP, eq_baz_real, eq_slow_real):
'''
Calculates least trimmed squares and organizes data
Parameters:
processing: 'lts', 'ls'
st: obspy stream containing traces
sta_lats: station lats (list or array)
sta_lons: station lons (list or array)
WINDOW_LENGTH: window length of array analysis window (seconds)
WINDOW_OVERLAP: overlap between analysis windows
trigger_time: trigger time in UTC (string)
trigger_type:
'STA/LTA': single STA/LTA trigger
'Multiple triggers': multiple triggers, chosen based on multiple
triggers input
'Taup': no STA/LTA trigger, using Taup time and larger window to
search
peak: STA/LTA ratio of nearest peak to trigger
length: length of STA/LTA trigger duration
origin_lat: latitude of array center
origin_lon: longitude of array center
event_id: USGS earthquake identifier
eq_baz_real: backazimuth between catalog event and array
eq_slow_real: calculated slowness based on velocity model
Returns:
pandas dataframe:
'array_baz': array backazimuth
'array_slow': array slowness
'array_vel': array trace velocity
'mdccm': array mdccm (cross correlation power)
'conf_int_vel': confidence interval of trace velocity
'conf_int_baz': confidene interval of backazimuth
'time': time of array analysis (UTC)
'event_id': USGS event ID
'baz_error': backazimuth error (real - array)
'slow_error': slowness error (real - array)
'trigger_time': trigger time
'trigger_type': trigger type
'sta/lta': peak of nearest peak from sta/lta for trigger
'trigger_length': length of trigger in seconds
'num_stations': number of stations used
'array_lat': array center latitude
'array_lon': array center longitude
'''
if len(st) < 4: #Can't perform lts for less than 4 stations
processing = 'ls'
if processing == 'lts':
ALPHA = 0.5 #least trimmed squares
print('Starting LTS')
else:
ALPHA = 1 #least squares
print('Starting LS')
(lts_vel, lts_baz, t, mdccm, stdict, sigma_tau,
conf_int_vel, conf_int_baz) = lts_array.ltsva(st, sta_lats,
sta_lons,
WINDOW_LENGTH,
WINDOW_OVERLAP,
ALPHA)
#print('Length of data:', len(lts_vel))
if len(lts_baz) >1: #pulling out max cross correlation
print('Pulling out max mdccm')
idx = np.argmax(mdccm)
else: #should only be one value for trigger time
idx = 0
data = {
'array_baz': lts_baz[idx],
'array_slow': 1/lts_vel[idx],
'array_vel': lts_vel[idx],
'mdccm': mdccm[idx],
'conf_int_vel': conf_int_vel[idx],
'conf_int_baz': conf_int_baz[idx],
'time': str(UTCDateTime(mdates.num2date(t[idx]))),
'baz_error': baz_error(eq_baz_real, lts_baz[idx]),
'slow_error': eq_slow_real - (1/lts_vel[idx])
}
array_data = pd.DataFrame(data, index=[0]) #print(array_data)
return array_data
def fk_obspy(st1, stations, sta_lats, sta_lons, sta_elev, START_new, END_new,
WINDOW_LENGTH, WINDOW_OVERLAP, FREQ_MIN, FREQ_MAX,
sll_x, slm_x, sll_y, slm_y, sl_s, semb_thres, vel_thres, timestamp,
prewhiten, eq_baz, eq_slow):
print('Starting FK')
#Add necessary data to streams----------------
for l in range(len(stations)): # Uses all stations in pd dataframe stations
st1[l].stats.coordinates = AttribDict({
'latitude': sta_lats[l],
'elevation': sta_elev[l],
'longitude': sta_lons[l]})
#Set up dictionary based on input parameters----------------------------
kwargs = dict(
# slowness grid: X min, X max, Y min, Y max, Slow Step
sll_x=sll_x, slm_x=slm_x, sll_y=sll_y, slm_y=slm_y, sl_s=sl_s,
# sliding window properties
win_len=WINDOW_LENGTH, win_frac=WINDOW_OVERLAP,
# frequency properties
frqlow=FREQ_MIN, frqhigh=FREQ_MAX, prewhiten=prewhiten,
# restrict output
semb_thres=semb_thres, vel_thres=vel_thres, timestamp=timestamp,
# start and end of analysis
stime=START_new, etime = END_new
)
out = array_processing(st1, **kwargs)
#OUTPUT FROM FK PROCESSING-------------------------------------------------
array_out = pd.DataFrame(out, columns = ['time','relpow','abspow',
'baz_obspy','array_slow'])
#Convert times and baz to same scale as lts (UTC time, centered on window)-
t = array_out['time'].to_numpy()
baz_obspy = array_out['baz_obspy'].to_numpy()
bazs = []
time_error = []
for j in range(len(t)):
matplotlib_time = t[j]
x = mdates.num2date(matplotlib_time)
x = UTCDateTime(x)
#diff = (x-UTCDateTime(time_station))+(win_len/2)
diff = str(x+(WINDOW_LENGTH/2)) #time centered on point
time_error.append(diff)
baz = baz_obspy[j]
if baz <= 0:
baz_correct = baz+360 #converts to all positive backazimuth
else:
baz_correct = baz
bazs.append(baz_correct)
time_error = np.array(time_error)
fk_bazs = np.array(bazs)
#Calculate baz/slow error---------------------------------------
fk_baz_error = baz_error(eq_baz, fk_bazs)
trace_vel_error = (1/eq_slow)- 1/array_out['array_slow'].to_numpy()
slowness_error = (eq_slow) - array_out['array_slow'].to_numpy()
#Start to aggregate data----------------------------
array_out['baz_error'] = fk_baz_error
#array_out['centered_time'] = time_error
array_out['time'] = time_error
array_out['array_baz'] = fk_bazs
array_out['slow_error'] = slowness_error
array_out['array_vel'] = 1/array_out['array_slow'].to_numpy()
#Pull out greatest power (should be only one value if using triggers)-----
idx = np.argmax(array_out['relpow'].to_numpy())
#Save data--------------------------------------
array_data = array_out.loc[[idx]]
array_data['conf_int_vel'] = 0 #values not returned for FK,
array_data['conf_int_baz'] = 0 #values not returned for FK
array_data['mdccm'] = 0 #values not returned for FK
return array_data
############################################################
#### HOMER/KODIAK SPECIFIC ###########################
############################################################
def stations_available_generator_hm_kd(
earthquake_time,
station_d1_list, start_d1_list, end_d1_list,
station_d2_list, start_d2_list, end_d2_list,
array_name
):
# ---------------------------------
# Convert times once
# ---------------------------------
earthquake_time = np.array([utc2datetime(str(t)) for t in earthquake_time])
start_d1 = np.array([utc2datetime(str(t)) for t in start_d1_list])
end_d1 = np.array([utc2datetime(str(t)) for t in end_d1_list])
start_d2 = np.array([utc2datetime(str(t)) for t in start_d2_list])
end_d2 = np.array([utc2datetime(str(t)) for t in end_d2_list])
station_d1 = np.array(station_d1_list)
station_d2 = np.array(station_d2_list)
# ---------------------------------
# Load bear removal data
# ---------------------------------
if array_name == "HM":
bears = pd.read_csv(
"/Users/cadequigley/Downloads/Research/deployment_array_design/homer_mseed_completeness.csv"
)[["station_name","bear_removal_time_d1","bear_removal_time_d2"]]
bear_d1 = dict(zip(bears.station_name, bears.bear_removal_time_d1))
bear_d2 = dict(zip(bears.station_name, bears.bear_removal_time_d2))
# build arrays aligned with station lists
bear_d1_arr = np.array([bear_d1.get(sta, '0') for sta in station_d1])
bear_d2_arr = np.array([bear_d2.get(sta, '0') for sta in station_d2])
# apply bear removal overrides
mask = bear_d1_arr != '0'
end_d1[mask] = np.array([utc2datetime(str(t)) for t in bear_d1_arr[mask]])
mask = bear_d2_arr != '0'
end_d2[mask] = np.array([utc2datetime(str(t)) for t in bear_d2_arr[mask]])
# ---------------------------------
# Output containers
# ---------------------------------
stations_lists = []
stations_available = []
deployment_all = []
# ---------------------------------
# Loop earthquakes only
# ---------------------------------
for eq in earthquake_time:
mask_d1 = (eq >= start_d1) & (eq <= end_d1)
mask_d2 = (eq >= start_d2) & (eq <= end_d2)
sta_d1 = station_d1[mask_d1]
sta_d2 = station_d2[mask_d2]
stations = np.concatenate([sta_d1, sta_d2])
deployments = ["d1"]*len(sta_d1) + ["d2"]*len(sta_d2)
stations_lists.append(stations.tolist())
stations_available.append(len(stations))
deployment_all.append(deployments)
return stations_lists, stations_available, deployment_all
'''
def process_hm_kd_data(net, sta, loc, chan, starttime, endtime, array_name, array, processing,
FREQ_MIN, FREQ_MAX, WINDOW_LENGTH, WINDOW_OVERLAP, window_start, min_mag, max_rad,
short_window, long_window, on_threshold, off_theshold, client = Client('EARTHSCOPE'), remove_stations = [], keep_stations = [],
gain = None, min_stations = 3, use_full_deployment = False, save = False, velocity_model = 'iasp91',
timing = 'trigger', min_triggers = 1, ptolerance = 5, multiple_triggers = 'peak', no_triggers = 'taup', sll_x = -1.0,
slm_x = 1.0, sll_y=-1.0, slm_y = 1.0, sl_s = 0.03, semb_thres = -1e9, vel_thres = -1e9, timestamp = 'mlabday', prewhiten = 0):
#Pull inventory-----------------------
#------------------------------------------------
deployment = 'd1'
path = '/Users/cadequigley/Downloads/Research/deployment_array_design/'
inv1 = read_inventory(path + array+'_'+deployment+'_station.xml')
(lat_list, lon_list, elev_list, station_d1_list,
start_d1_list, end_d1_list, num_channels_d1_list) = data_from_inventory(inv1, remove_stations, keep_stations)
data = {
'station': station_d1_list,
'lat': lat_list,
'lon': lon_list,
'elevation': elev_list}
station_info = pd.DataFrame(data)
## PULL IN DATA FOR SECOND DEPLOYMENT##########################
deployment = 'd2'
## READ IN INVENTORY FOR D2-------------------------
path = '/Users/cadequigley/Downloads/Research/deployment_array_design/'
inv2 = read_inventory(path + array+'_'+deployment+'_station.xml')
(lat_list_d2, lon_list_d2, elev_list_d2, station_d2_list,
start_d2_list, end_d2_list, num_channels_d2_list) = data_from_inventory(inv2, remove_stations, keep_stations)
#Pull earthquakes-----------------------
#------------------------------------------------
#### Get center of array--------
output = get_geometry(lat_list, lon_list, elev_list, return_center = True)
origin_lat = str(output[-1][1])
origin_lon = str(output[-1][0])
moveout = moveout_time(output)
### Pull in earthquakes--------------
start, end = array_time_window(use_full_deployment, start_d1_list, end_d2_list,
starttime, endtime)
df = pull_earthquakes(origin_lat, origin_lon, max_rad, start, end, min_mag, array_name, velocity_model)
print('Number of earthquakes >'+min_mag+' within '+max_rad+' km:', len(df))
#Create station availability lists-----------------------
#------------------------------------------------
earthquake_time = df['time_utc'].to_numpy()
earthquake_names = df['event_id'].to_numpy()
stations_lists, stations_available, deployment_list = stations_available_generator_hm_kd(earthquake_time, station_d1_list, start_d1_list,
end_d1_list, station_d2_list, start_d2_list, end_d2_list, array_name)
#stations_lists, stations_available = stations_available_generator(earthquake_time, station_d1_list, start_d1_list, end_d1_list)
### Drop events that don't have enough stations present--------------
bad_idx = [i for i, v in enumerate(stations_available) if v < min_stations]
keep_idx = [i for i, v in enumerate(stations_available) if v >= min_stations]
stations_available = [stations_available[i] for i in keep_idx]
stations_lists = [stations_lists[i] for i in keep_idx]
deployment_list = [deployment_list[i] for i in keep_idx]
df = df.drop(index=bad_idx)
print('Station lists for each earthquake created. New earthquake number:', len(df))
###Loop over all events---------------------------------
event_ids = df['event_id'].to_numpy()
eq_depths = df['depth'].to_numpy()
eq_lats = df['latitude'].to_numpy()
eq_lons = df['longitude'].to_numpy()
eq_time = df['time_utc'].to_numpy()
expected_parrival = df['p_arrival'].to_numpy()
eq_baz = df['backazimuth'].to_numpy()
eq_slow = df['slowness'].to_numpy()
eq_distance = df['distance'].to_numpy()
array_data_list = []
misbehaving_list = []
for event in range(len(df)):
try:
print("Starting", event_ids[event])
stations = stations_lists[event] #pull out stations available for each event
station_sub = station_info[station_info['station'].isin(stations)] #pull out specific station info
sta_lats = station_sub['lat'].to_numpy()
sta_lons = station_sub['lon'].to_numpy()
stations = station_sub['station'].to_numpy()
sta_elev = station_sub['elevation'].to_numpy()
eq_baz_real = eq_baz[event]
eq_slow_real = eq_slow[event]
event_id = event_ids[event]
START = UTCDateTime(eq_time[event])+expected_parrival[event]-60
END = START +120
try: #Try to pull event from locally
if array_name =='HM':
array = 'homer'
else:
array = 'kodiak'
st = read('/Users/cadequigley/Downloads/Research/deployment_array_design/'+array+'_earthquakes_mseeds/'+event_ids[event]+".mseed")
st = st.slice(START, END)
#st = read('/Users/cadequigley/Downloads/Research/'+array+'_earthquakes_mseeds/'+event_ids[event]+".mseed")
except FileNotFoundError:
print('File not found locally, trying to pull from IRIS')
st = Stream()
failed_stations = []
for sta in stations:
try:
st += client.get_waveforms(net, sta, loc, chan, START, END)
except FDSNNoDataException:
print(f"No data for station {sta}")
failed_stations.append(sta)
except Exception as e:
print(f"Error for station {sta}: {e}")
failed_stations.append(sta)
# Remove failed stations
if failed_stations:
mask = ~np.isin(stations, failed_stations)
stations = stations[mask]
sta_lats = sta_lats[mask]
sta_lons = sta_lons[mask]
sta_elev = sta_elev[mask]
if len(keep_stations) >0:
st_subset = Stream()
for sta in stations:
st_subset += st.select(station=sta)
st = st_subset.copy()
if len(st) < min_stations:
raise ValueError("Not enough traces")
#st.resample(100) #testing to see if data is resampled now
st.merge(fill_value='latest')
#st.trim(START, END, pad='true', fill_value=0)
st.sort()
#if deployment_list[event][0] == 'd1':
#st.remove_sensitivity(inventory = inv1)
#else:
#st.remove_sensitivity(inventory = inv2)
for b in range(len(st)):
tr = st[b]
tr.data = tr.data/gain
# Filter the data
st.filter("bandpass", freqmin=FREQ_MIN, freqmax=FREQ_MAX, corners=2, zerophase=True)
st.taper(max_percentage=0.05)
#print('Done pulling data')
st1 = st.copy()
###Finding triggers---------------------------------
if timing == 'trigger': #use sta/lta triggers
(st, trigger, peak, length,
trigger_type, trigger_time,
START_new, END_new)= triggers(st, short_window, long_window,
on_threshold, off_theshold,
moveout, min_triggers,
ptolerance, START,
window_start, WINDOW_LENGTH,
multiple_triggers, no_triggers)
###Array processing---------------------------------
##Least squares--------------------
if processing == 'lts' or processing == 'ls':
array_data = least_trimmed_squares(processing, st, sta_lats, sta_lons,
WINDOW_LENGTH, WINDOW_OVERLAP,
trigger_time, trigger_type, peak,
length, origin_lat, origin_lon,
event_id, eq_baz_real, eq_slow_real)
else: #fk analysis
array_data = fk_obspy(st1, stations, sta_lats, sta_lons, sta_elev, START, START_new, END_new,
WINDOW_LENGTH, WINDOW_OVERLAP, FREQ_MIN, FREQ_MAX,
sll_x, slm_x, sll_y, slm_y, sl_s, semb_thres, vel_thres, timestamp, prewhiten,
eq_baz_real, eq_slow_real, event_id, trigger, trigger_type, peak, length, origin_lat, origin_lon)
array_data_list.append(array_data)
print('Events completed:', str(event+1)+'/'+str(len(df)))
except ValueError as e:
print(f"Skipping event {event_ids[event]}: {e}")
#traceback.print_exc()
continue
except Exception as e:
print(f"Unexpected error for event {event_ids[event]}: {e}")
#traceback.print_exc()
continue
#Putting data into single dataframe----------------------
array_data_comb1 = pd.concat(array_data_list, ignore_index=True)
array_data_comb = pd.merge(array_data_comb1, df, on='event_id', how='inner')
if save == True:
array_data_comb.to_csv(array_name+'_'+max_rad+'km_m3_fk_wawa.csv')
return array_data_comb, station_info
'''
############################################################
#### FUNCTIONS FOR PREPROCESSING ###########################
############################################################
def grab_preprocess(stations, station_info, inv,
net, loc, chan, min_stations,
START, END, client, array, event_id, path,
save_mseed = False):
#Pull out specific station info
station_sub = station_info[station_info['station'].isin(stations)]
sta_lats = station_sub['lat'].to_numpy()
sta_lons = station_sub['lon'].to_numpy()
stations = station_sub['station'].to_numpy()
sta_elev = station_sub['elevation'].to_numpy()
try: #Try to pull event from locally
#st = read('/Users/cadequigley/Downloads/Research/deployment_array_design/'+array+'_earthquakes_mseeds/'+event_id+".mseed")
st = read(path+event_id+'.mseed')
st = st.slice(START, END)
stations = set(tr.stats.station for tr in st)
station_sub = station_info[station_info['station'].isin(stations)]
valid_stations = set(station_sub['station'])
# Remove traces not in station list
st = Stream([tr for tr in st if tr.stats.station in valid_stations])
#st = st.select(station=list(valid_stations))
sta_lats = station_sub['lat'].to_numpy()
sta_lons = station_sub['lon'].to_numpy()
stations = station_sub['station'].to_numpy()
sta_elev = station_sub['elevation'].to_numpy()
#st = read('/Users/cadequigley/Downloads/Research/'+array+'_earthquakes_mseeds/'+event_ids[event]+".mseed")
except FileNotFoundError:
print('File not found locally, trying to pull from IRIS')
st = Stream()
failed_stations = []
for sta in stations:
try:
st += client.get_waveforms(net, sta, loc, chan, START, END)
except FDSNNoDataException:
print(f"No data for station {sta}")
failed_stations.append(sta)
except Exception as e:
print(f"Error for station {sta}: {e}")
failed_stations.append(sta)
# Remove stations that did not have data from metadata
if failed_stations:
mask = ~np.isin(stations, failed_stations)
stations = stations[mask]
sta_lats = sta_lats[mask]
sta_lons = sta_lons[mask]
sta_elev = sta_elev[mask]
# Check to see if there are enough stations----
if len(st) < min_stations:
raise ValueError("Not enough traces")
if save_mseed == True:
st.sort()
st.write(path+event_id+".mseed", format="MSEED")
print('mseed saved')
# Basic data preperation-----------
st.merge(fill_value='latest')
st.trim(START, END, pad='true', fill_value=0)
st.sort()
st.remove_sensitivity(inventory = inv)
# Filter the data
#st.filter("bandpass", freqmin=FREQ_MIN, freqmax=FREQ_MAX,
#corners=2, zerophase=True)
st.taper(max_percentage=0.05)
return st, stations, sta_lats, sta_lons, sta_elev
def moveout_time(output):
'''
Calculates the minimum moveout time across the array based on maximum
interstation distacne and velocity, including some wiggle room
Parameters:
output: output from get_geometry function. Contains interstation
distances
Returns:
moveout: expected moveout time in seconds (float)
'''
#### Calculate interstation distances/moveout time
xpos = list(output[:,0])
xpos = xpos[:-1]
ypos = list(output[:,1])
ypos = ypos[:-1]
distances_temp = interstation_distances(xpos, ypos)
moveout = (np.max(distances_temp)/3)+0.5 #t = d/v + error
return moveout
def array_time_window(use_full_deployment, start_d1_list, end_d1_list,
starttime, endtime):
'''
Defines what dates to look for earthquakes based on active stations
Parameters:
use_full_deployment: whether to use full time window deployment was
out (True or False)
start_d1_list: list of start times for each station
end_d1_list: list of end times for each station
starttime: specified starttime, will use if use_full_deployment = True
endtime: speficied endtime, will use if use_full_deployment = True
Returns:
start: start time to look for earthquakes
end: end time to look for earthquakes
'''
if use_full_deployment ==True:
start = str(np.min(start_d1_list)) #time when first station online
if str(type(end_d1_list[0])) == "<class 'NoneType'>": #deals with case where station/array is still active by taking time today
end_temp = UTCDateTime.now()
end = str(end_temp)
temp = []
for i in range(len(end_d1_list)):
temp.append(end_temp)
end_d1_list = temp
else:
end = str(np.max(end_d1_list)) #time when last station offline
else: #use restricted time window specified at start
start = starttime
end = endtime
return start, end
def rotate_channel(st, inv, channel): ###NEED TO FINISH-------------
for i in range(len(st)):
tr = st[i]
if channel[:-1] == 'Z':
if inv[0][i].channels[0].dip == 90:
tr.data = -1*tr.data
elif channel[:-1] == 'N':
if inv[0][i].channels[0].azimuth == 180:
tr.data = -1*tr.data
elif channel[:-1] == 'E':
if inv[0][i].channels[0].azimuth == 270:
tr.data = -1*tr.data
def calculate_slowness(distance_km, depth, velocity_model):
"""
Calculates the slowness of an event based on known information about
hypocenter. This is a 1D calculation using the Taup calculator
(Crotwell et al.)
Parameters:
distance_km: epicentral distance to event in km
depth: depth of event in km
velocity_model: velocity model to use for slowness calculation
('iasp91', 'ak135', 'pavdut', 'japan_1d', '')
Returns:
slowness: expected slowness at surface (s/km)
trace_vel: expected trace_vel at surface (km/s)
incident_angle: incident angle of ray at surface (degrees)
p_arrival: calculated p-arrival time (seconds after origin time)
"""
mod = velocity_model #pavdut, iasp91, japan_1d, ak135, scak
model = TauPyModel(model=mod)
dist_deg = kilometers2degrees(distance_km)
arrivals_p = model.get_travel_times(source_depth_in_km=depth,
distance_in_degree=dist_deg,
phase_list = ["P","p"])
arr = arrivals_p[0]
p_arrival = arr.time
incident_angle = arr.incident_angle
if mod == 'iasp91':
trace_vel = 5.8/(np.sin(np.deg2rad(incident_angle))) #iasp91 surface velocity: 5.8
elif mod == 'japan_1d':
trace_vel = 4.8/(np.sin(np.deg2rad(incident_angle))) #japan_1D surface velocity: 5.8
elif mod == 'ak135':
trace_vel = 5.8/(np.sin(np.deg2rad(incident_angle)))
elif mod == 'scak':
trace_vel = 5.3/(np.sin(np.deg2rad(incident_angle)))
else: #pavdut
trace_vel = 3.05/(np.sin(np.deg2rad(incident_angle))) #pavdut surface velocity: 3.05
slowness = 1/trace_vel
return slowness, trace_vel, incident_angle, p_arrival
def misbehaving_stations_lts(d, threshold=4):
"""
Returns a list of values that appear more than `threshold` times
in the first array-like value found in the dictionary `d`.
Ignores non-array entries like 'size'.
"""
# Find the first array in the dictionary
for key, val in d.items():
if isinstance(val, (np.ndarray, list)): # supports arrays or lists
arr = np.array(val) # convert to numpy array if list
unique, counts = np.unique(arr, return_counts=True)
return unique[counts > threshold].tolist()
# Return empty if no array found
return []
def data_from_inventory(inv, remove_stations, keep_stations):
"""
Pulls pertinent information out of an inventory for arrays.
Parameters:
inv: station inventory based on station.xml format from FDSN
remove_stations: list of station names to remove if there is a known
issue with the station. Example: ['2A12', '2A14']
Returns:
lat_list: list of station latitudes
lon_list: list of station longitudes
elev_list: list of station elevation
station_list: list of station names
start_list: stat times of data available
end_list: end times of data available
num_channels_list: number of channels with associated station
"""
## PULL INFORMATION OUT OF INVENTORY-------------------------
lat_list = []
lon_list = []
elev_list = []
station_list = []
start_list = []
end_list = []
num_channels_list = []
for network in inv:
for station in network:
lat_list.append(station.latitude)
lon_list.append(station.longitude)
station_list.append(station.code)
elev_list.append(station.elevation)
start_list.append(station.start_date)
if station.end_date == None:
end_list.append(UTCDateTime.now())
else:
end_list.append(station.end_date)
num_channels_list.append(station.total_number_of_channels)
if len(remove_stations) > 0:
for k in range(len(remove_stations)):
station = remove_stations[k]
idx = station_list.index(station)
del lat_list[idx]
del lon_list[idx]
del station_list[idx]
del elev_list[idx]
del start_list[idx]
del end_list[idx]
del num_channels_list[idx]
if len(keep_stations) > 0:
mask = [sta in keep_stations for sta in station_list]
lat_list = [lat_list[i] for i in range(len(mask)) if mask[i]]
lon_list = [lon_list[i] for i in range(len(mask)) if mask[i]]
station_list = [station_list[i] for i in range(len(mask)) if mask[i]]
elev_list = [elev_list[i] for i in range(len(mask)) if mask[i]]
start_list = [start_list[i] for i in range(len(mask)) if mask[i]]
end_list = [end_list[i] for i in range(len(mask)) if mask[i]]
num_channels_list = [num_channels_list[i] for i in range(len(mask)) if mask[i]]
return (lat_list, lon_list, elev_list, station_list, start_list, end_list,
num_channels_list)
def check_num_stations(min_stations, station_list):
'''
Checks if the minimum number of stations is met.
Parameters:
min_stations: minimum stations wanted
station_list: list of stations
Returns:
ValueError if not enough stations
'''
num_stations = len(station_list)
if num_stations < min_stations:
raise ValueError("The minimum stations is greater then the number of available stations.")
def get_geometry(lat_list, lon_list, elev_list, return_center = False):
"""
Gets the geometry of the array in terms of meters from a center point.
This is slightly modified from obpsy.geotools.get_geometry
Parameters:
lat_list: list of station latitudes
lon_list: list of station longitudes
elev_list: list of station elevations
return_center: return center of array (True of False)
Returns:
geometry of array, including center point if return_center = True.
"""
nstat = len(lat_list)
center_lat = 0.
center_lon = 0.
center_h = 0.
geometry = np.empty((nstat, 3))
for i in range(nstat):
geometry[i, 0] = lon_list[i]
geometry[i, 1] = lat_list[i]
geometry[i, 2] = elev_list[i]
center_lon = geometry[:, 0].mean()
center_lat = geometry[:, 1].mean()
center_h = geometry[:, 2].mean()
for i in np.arange(nstat):
x, y = util_geo_km(center_lon, center_lat, geometry[i, 0],
geometry[i, 1])
geometry[i, 0] = x
geometry[i, 1] = y
geometry[i, 2] -= center_h
if return_center:
return np.c_[geometry.T,
np.array((center_lon, center_lat, center_h))].T
else:
return geometry
def interstation_distances(xpos, ypos):
points = np.column_stack((xpos, ypos)) # shape (N, 2)
dx = points[:, 0][:, None] - points[:, 0][None, :]
dy = points[:, 1][:, None] - points[:, 1][None, :]
distances = np.sqrt(dx**2 + dy**2)
return distances
def utc2datetime(utctime):
'''
Converts string of utctime to datetime
Parameters:
utctime: time in utc (string)
Returns:
datetime object
'''
return (dt.datetime(int(utctime[0:4]),int(utctime[5:7]), int(utctime[8:10]),
int(utctime[11:13]),int(utctime[14:16]),int(utctime[17:19])))
def baz_error(baz_real, baz_calculated):
'''
Calculates backazimuth error between catalog baz and array baz
Parameters:
baz_real: catalog backazimuth
baz_calculated: array calculated backazimuth
Returns:
baz_error: catalog baz - array baz
'''
baz_error_temp = baz_real - baz_calculated
baz_error = ((baz_error_temp + 180) % 360) - 180
return baz_error
############################################################
#### FUNCTIONS FOR PULLING EARTHQUAKES ###########################
############################################################
def pull_earthquakes(lat, lon, max_rad, start, end, min_mag, array_name,
velocity_model):
"""
Pulls in earthquakes from a region based on lat, lon, timing, and magnitude.
It also returns other values of interest about the event for array
processing, such as backazimuth, slowness, and epicentral distance to the
event.
Parameters:
lat: latitude of array/station (str)
lon: longitude of array/station (str)
max_rad: maximum radius of earthquakes in kilometers (str)
start: start time in UTC format (str)
end: end time in UTC format (str)
min_mag: minimum magnitude of earthquakes (str)
array_name: name of array/station (str)
velocity_model: name of velocity model (ex. 'iasp91', 'ak135')
Returns:
pandas DataFrame:
'event_id': event id from USGS catalog
'depth': depth of earthquake in km
'magnitude': magnitude of earthquake
'latitude': earthquake latitude
'longitude': earthquake longitude
'time_utc': origin time in UTC
'time_ak': origin time in AK
'distance': epicentral distance to event in km
'backazimuth': backazimuth from array/station to earthquake
'array': name of station/array
'slowness': surface slowness (s/km)
'trace_vel': surface trace velocity (km/s)
'incident_angle': angle from vertical of first arriving wave (degrees)
'p_arrival': arrival time of p-wave (seconds)
"""
##Pull data in from FDSNWS: https://earthquake.usgs.gov/fdsnws/event/1/
url = ('https://earthquake.usgs.gov/fdsnws/event/1/query?format=quakeml&starttime='+start+'&endtime='
+end+'&latitude='+lat+'&longitude='+lon+'&maxradiuskm='+max_rad+'&minmagnitude='+min_mag+'')
catalog = read_events(url)
depths = []
magnitudes = []
latitudes = []
longitudes = []
times_utc = []
times_ak = []
names = []
distances = []
backazimuth = []
array = []
slowness = []
trace_vel = []
incident_angle = []
p_arrival = []
# Extract data from each event
for event in catalog:
# Extract depth
depth = event.origins[0].depth / 1000 # Depth is in meters, convert to kilometers
# Extract magnitude
magnitude = event.magnitudes[0].mag
# Extract latitude and longitude
latitude = event.origins[0].latitude
longitude = event.origins[0].longitude
# Extract time
time = event.origins[0].time
# Extract event_id
resource_id = event.resource_id.id
name = resource_id.split('?')[-1]
name = name[:-15]
name= name[8:]
#Calculate distance, backazimuth
dist, baz, az = gps2dist_azimuth(float(lat), float(lon),
latitude, longitude)
dist = dist/1000 #converts m to km
if depth < 0:
slow = 0
t_vel = 0
incident = 0
p = 0
else:
#Calculate slowness, trace velocity, incident angle, and arrival time
slow, t_vel, incident, p = calculate_slowness(dist,
depth,
velocity_model)
# Append data to lists
depths.append(depth)
magnitudes.append(magnitude)
latitudes.append(latitude)
longitudes.append(longitude)
times_utc.append(time)