-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtoolbox.py
2818 lines (2474 loc) · 146 KB
/
toolbox.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
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 dependencies
import os
import time
import glob
import json
import pickle
import random
import pyproj
import numpy as np
import pandas as pd
import colorcet as cc
import seaborn as sns
import tensorflow as tf
import statistics as sts
import matplotlib.pyplot as plt
from DataGenerator import DataGenerator
from geopy.distance import geodesic as GD
from keras import layers, models, losses, optimizers
from keras.models import load_model
from keras.callbacks import EarlyStopping, ModelCheckpoint, Callback
from matplotlib import dates, rcParams
from matplotlib.transforms import Bbox
from matplotlib.colors import ListedColormap
from obspy import UTCDateTime, read, Stream, Trace
from ordpy import complexity_entropy
from scipy.signal import spectrogram, find_peaks, medfilt
from scipy.fft import rfft, rfftfreq
from sklearn import metrics
from waveform_collection import gather_waveforms
def load_data(network,station,channel,location,starttime,endtime,pad=None,local=None,data_dir=None,client=None):
"""
Load data from local miniseed repository or query data from server
:param network (str or list): SEED network code(s)
:param station (str or list): SEED station code(s)
:param channel (str or list): SEED channel code(s)
:param location (str or list): SEED location code(s)
:param starttime (:class:`~obspy.core.utcdatetime.UTCDateTime`): start time for desired data
:param endtime (:class:`~obspy.core.utcdatetime.UTCDateTime`): end time for desired data
:param pad (float): Number of seconds to add on to the start and end times for desired data [s]. This should be greater than or equal to the taper length if tapering is needed.
:param local (bool): If `True`, pull local data from data_dir. If `False`, query client for data.
:param data_dir (str): Full file path for data directory
:param client (str): Name of desired FDSN client (e.g., IRIS)
:return: Stream (:class:`~obspy.core.stream.Stream`) data object
"""
# Sanity check to see if data needs to be pulled from local directory of queried from client
if (local==True and data_dir!=None and client==None) or (local==False and data_dir==None and client!=None):
pass
else:
raise ValueError('Either set local=True and provide data_dir, or set local=False and provide client.')
# Edit starttime and endtime if padding is required
if pad is not None:
starttime = starttime - pad
endtime = endtime + pad
# If we are pulling data from local
if local:
# Floor the start and end times, construct a list of UTCDateTimes marking the start of each day
starttime_floor = UTCDateTime(starttime.date)
endtime_floor = UTCDateTime(endtime.date)
num_days = int((endtime_floor - starttime_floor) / 86400)
time_list = [starttime_floor + i*86400 for i in range(num_days+1)]
# Initialize list for all station channel data filenames
data_filenames = []
# If only one station-channel input is given,
if type(network) == str and type(station) == str and type(channel) == str and type(location) == str:
# Loop over time list, craft file string and append
for time in time_list:
data_filename = data_dir + station + '.' + channel + '.' + str(time.year) + ':' + f'{time.julday:03}' + ':*'
data_filenames.append(data_filename)
# If multiple station-channel inputs are given,
elif type(network) == list and type(station) == list and type(channel) == list and type(location) == list and len(network) == len(station) == len(channel) == len(location):
# Loop over station-channel inputs
for i in range(len(network)):
# Loop over time list, craft file string and append
for time in time_list:
data_filename = data_dir + station[i] + '.' + channel[i] + '.' + str(time.year) + ':' + f'{time.julday:03}' + ':*'
data_filenames.append(data_filename)
# If the checks fail,
else:
# Raise error
raise ValueError('Inputs are in the wrong format. Either input a string (one station) or a lists of the same length (multiple stations) for network/station/channel/location.')
# Now permutate the list of filenames and times to glob and load data
stream = Stream()
for data_filename in data_filenames:
matching_filenames = (glob.glob(data_filename))
for matching_filename in matching_filenames:
try:
stream_contribution = read(matching_filename)
stream = stream + stream_contribution
except:
continue
# Trim and merge stream
stream = stream.trim(starttime=starttime,endtime=endtime)
stream = stream.merge()
return stream
# If user provides a client,
elif not local and client is not None:
# Prepare client
from obspy.clients.fdsn import Client
client = Client(client)
# Initialize stream
stream = Stream()
# If only one station-channel input is given,
if type(network) == str and type(station) == str and type(channel) == str and type(location) == str:
# Grab stream
stream_contribution = client.get_waveforms(network, station, location, channel, starttime, endtime, attach_response=True)
stream = stream + stream_contribution
# If multiple station-channel inputs are given,
elif type(network) == list and type(station) == list and type(channel) == list and type(
location) == list and len(network) == len(station) == len(channel) == len(location):
# Loop over station-channel inputs
for i in range(len(network)):
# Grab stream
stream_contribution = client.get_waveforms(network[i], station[i], location[i], channel[i], starttime, endtime, attach_response=True)
stream = stream + stream_contribution
# If the checks fail,
else:
# Raise error
raise ValueError('Inputs are in the wrong format. Either input a string (one station) or a lists of the same length (multiple stations) for network/station/channel/location.')
# Trim and merge stream
stream = stream.trim(starttime=starttime,endtime=endtime)
stream = stream.merge()
return stream
# If not no client is provided
else:
# Raise error
raise ValueError('Please provide an input client (e.g. "IRIS").')
def process_waveform(stream,remove_response=True,rr_output='VEL',detrend=False,taper_length=None,taper_percentage=None,filter_band=None,verbose=True):
"""
Process waveform by removing response, detrending, tapering and filtering (in that order)
:param stream (:class:`~obspy.core.stream.Stream`): Input data
:param remove_response (bool): If `True`, remove response using metadata. If `False`, response is not removed
:param rr_output (str): Set to 'DISP', 'VEL', 'ACC', or 'DEF'. See obspy documentation for more details.
:param detrend (bool): If `True`, demean input data. If `False`, data is not demeaned
:param taper_length (float): Taper length in seconds [s]. This is usually set to be similar as the pad length when loading data. If both taper_length and taper_percentage are `None`, data is not tapered
:param taper_percentage (float): Taper length in percentage [%], if desired. If both taper_length and taper_percentage are `None`, data is not tapered
:param filter_band (tuple): Tuple of length 2 storing minimum frequency and maximum frequency for bandpass filter ([Hz],[Hz])
:param verbose (bool): If `True`, print out a declaration for each processing step
:return: Stream (:class:`~obspy.core.stream.Stream`) data object
"""
# If the input is a trace and not a stream, convert it to a stream and activate flag to return a trace later
return_trace = False
if type(stream) == Trace:
stream = Stream([stream])
return_trace = True
if verbose:
print('Processing trace/stream...')
if remove_response:
for tr in stream:
fs_resp = tr.stats.sampling_rate
pre_filt = [0.005, 0.01, fs_resp/2-2, fs_resp/2]
tr.remove_response(pre_filt=pre_filt, output=rr_output, water_level=60, plot=False)
if verbose:
print('Response removed.')
if detrend:
#stream.detrend(type='linear')
stream.detrend('demean')
if verbose:
print('Waveform demeaned.')
if taper_length is not None and taper_percentage is None:
#stream.taper(max_percentage=.02)
stream.taper(max_percentage=None, max_length=taper_length/2)
if verbose:
print('Waveform tapered by pad length.')
elif taper_length is None and taper_percentage is not None:
if taper_percentage > 1:
taper_percentage = taper_percentage/100
stream.taper(max_percentage=taper_percentage, max_length=None)
if verbose:
print('Waveform tapered by pad percentage.')
elif taper_length is None and taper_percentage is None:
pass
else:
raise ValueError('Either provide taper_length OR taper_percentage if tapering.')
if filter_band is not None:
stream.filter('bandpass', freqmin=filter_band[0], freqmax=filter_band[1], zerophase=False)
if verbose:
print('Waveform bandpass filtered from %.2f Hz to %.2f Hz.' % (filter_band[0],filter_band[1]))
if return_trace:
return stream[0]
else:
return stream
def plot_spectrogram(stream,starttime,endtime,window_duration,freq_lims,log=False,demean=False,v_percent_lims=(20,100),cmap=cc.cm.rainbow,earthquake_times=None,db_hist=False,figsize=(32,9),export_path=None):
"""
Plot all traces in a stream and their corresponding spectrograms in separate plots using matplotlib
:param stream (:class:`~obspy.core.stream.Stream`): Input data
:param starttime (:class:`~obspy.core.utcdatetime.UTCDateTime`): Start time for desired plot
:param endtime (:class:`~obspy.core.utcdatetime.UTCDateTime`): End time for desired plot
:param window_duration (float): Duration of spectrogram window [s]
:param freq_lims (tuple): Tuple of length 2 storing minimum frequency and maximum frequency for the spectrogram plot ([Hz],[Hz])
:param log (bool): If `True`, plot spectrogram with logarithmic y-axis
:param v_percent_lims (tuple): Tuple of length 2 storing the percentile values in the spectrogram matrix used as colorbar limits. Default is (20,100).
:param cmap (str or :class:`matplotlib.colors.LinearSegmentedColormap`): Colormap for spectrogram plot. Default is colorcet.cm.rainbow.
:param earthquake_times (list of :class:`~obspy.core.utcdatetime.UTCDateTime`): List of UTCDateTimes storing earthquake origin times to be plotted as vertical black dashed lines.
:param db_hist (bool): If `True`, plot a db histogram (spanning the plotted timespan) on the right side of the spectrogram across the sample frequencies
:param figsize (tuple): Tuple of length 2 storing output figure size. Default is (32,9).
:param export_path (str or `None`): If str, export plotted figures as '.png' files, named by the trace id and time. If `None`, show figure in interactive python.
"""
# Be nice and accept traces as well
if type(stream) == Trace:
stream = Stream() + stream
# Loop over each trace in the stream
for trace in stream:
# Check if input trace is infrasound (SEED channel name ends with 'DF'). Else, assume seismic.
if trace.stats.channel[1:] == 'DF':
# If infrasound, define corresponding axis labels and reference values
y_axis_label = 'Pressure (Pa)'
REFERENCE_VALUE = 20 * 10**-6 # Pressure, in Pa
SPEC_THRESH = 0 # Power value indicative of gap
colorbar_label = f'Power (dB rel. [{REFERENCE_VALUE * 1e6:g} µPa]$^2$ Hz$^{{-1}}$)'
rescale_factor = 1 # Plot waveform in Pa
else:
# If seismic, define corresponding axis labels and reference values
y_axis_label = 'Velocity (µm s$^{-1}$)'
REFERENCE_VALUE = 1 # Velocity, in m/s
SPEC_THRESH = -220 # Power value indicative of gap
colorbar_label = f'Power (dB rel. {REFERENCE_VALUE:g} [m s$^{{-1}}$]$^2$ Hz$^{{-1}}$)'
rescale_factor = 10**-6 # Plot waveform in micrometer/s
# Extract trace information for FFT
sampling_rate = trace.stats.sampling_rate
samples_per_segment = int(window_duration * sampling_rate)
# Compute spectrogram (Note that overlap is 90% of samples_per_segment)
sample_frequencies, segment_times, spec = spectrogram(trace.data, sampling_rate, window='hann', scaling='density', nperseg=samples_per_segment, noverlap=samples_per_segment*.9)
# Convert spectrogram matrix to decibels for plotting
spec_db = 10 * np.log10(abs(spec) / (REFERENCE_VALUE**2))
# If demeaning is desired, remove temporal mean from spectrogram
if demean:
# column_ht = np.shape(spec_db)[0]
# ratio_vec = np.linspace(0,0.5,column_ht).reshape(column_ht,1)
# spec_db = spec_db - np.mean(spec_db,1)[:, np.newaxis]*ratio_vec
spec_db = spec_db - np.mean(spec_db, 1)[:, np.newaxis]
# Convert trace times to matplotlib dates
trace_time_matplotlib = trace.stats.starttime.matplotlib_date + (segment_times / dates.SEC_PER_DAY)
# If earthquake times are provided, convert them from UTCDateTime to matplotlib dates
if earthquake_times:
earthquake_times_matplotlib = [eq.matplotlib_date for eq in earthquake_times]
else:
earthquake_times_matplotlib = []
# Prepare time ticks for spectrogram and waveform figure (Note that we divide the duration into 10 equal increments and 11 uniform ticks)
if ((endtime-starttime)%1800) == 0:
denominator = 12
time_tick_list = np.arange(starttime,endtime+1,(endtime-starttime)/denominator)
else:
denominator = 10
time_tick_list = np.arange(starttime,endtime+1,(endtime-starttime)/denominator)
time_tick_list_mpl = [t.matplotlib_date for t in time_tick_list]
time_tick_labels = [time.strftime('%H:%M') for time in time_tick_list]
# Craft figure
fig, (ax1,ax2) = plt.subplots(2,1,figsize=figsize,constrained_layout=True)
# If frequency limits are defined
if freq_lims is not None:
# Determine frequency limits and trim spec_db
freq_min = freq_lims[0]
freq_max = freq_lims[1]
spec_db_plot = spec_db[np.flatnonzero((sample_frequencies>freq_min) & (sample_frequencies<freq_max)),:]
c = ax1.imshow(spec_db, extent=[trace_time_matplotlib[0], trace_time_matplotlib[-1],sample_frequencies[0], sample_frequencies[-1]],
vmin=np.percentile(spec_db_plot[spec_db_plot>SPEC_THRESH], v_percent_lims[0]),
vmax=np.percentile(spec_db_plot[spec_db_plot>SPEC_THRESH], v_percent_lims[1]),
origin='lower', aspect='auto', interpolation='None', cmap=cmap)
# If we want a db spectrogram across the plotted time span, compute and plot on the right side of the figure
if db_hist:
spec_db_hist = np.sum(spec_db_plot,axis=1)
spec_db_hist = (spec_db_hist-np.min(spec_db_hist)) / (np.max(spec_db_hist)-np.min(spec_db_hist))
hist_plotting_range = (1/denominator) * (trace_time_matplotlib[-1] - trace_time_matplotlib[0])
hist_plotting_points = trace_time_matplotlib[-1] - (spec_db_hist * hist_plotting_range)
sample_frequencies_plot = sample_frequencies[np.flatnonzero((sample_frequencies>freq_min) & (sample_frequencies<freq_max))]
ax1.plot(hist_plotting_points, sample_frequencies_plot, 'k-', linewidth=10, alpha=0.6)
ax1.plot([trace_time_matplotlib[-1], trace_time_matplotlib[-1] - hist_plotting_range],
[sample_frequencies_plot[-1], sample_frequencies_plot[-1]], 'k-', linewidth=10, alpha=0.6)
ax1.plot(trace_time_matplotlib[-1] - hist_plotting_range, sample_frequencies_plot[-1], 'k<', markersize=50)
# If no frequencies limits are given
else:
# We go straight into plotting spec_db
c = ax1.imshow(spec_db, extent=[trace_time_matplotlib[0], trace_time_matplotlib[-1], sample_frequencies[0],sample_frequencies[-1]],
vmin=np.percentile(spec_db[spec_db>SPEC_THRESH], v_percent_lims[0]),
vmax=np.percentile(spec_db[spec_db>SPEC_THRESH], v_percent_lims[1]),
origin='lower', aspect='auto', interpolation='None', cmap=cmap)
# If we want a db spectrogram across the plotted time span, compute and plot on the right side of the figure
if db_hist:
spec_db_hist = np.sum(spec_db, axis=1)
spec_db_hist = (spec_db_hist - np.min(spec_db_hist)) / (np.max(spec_db_hist) - np.min(spec_db_hist))
hist_plotting_range = (1/denominator) * (trace_time_matplotlib[-1] - trace_time_matplotlib[0])
hist_plotting_points = trace_time_matplotlib[-1] - (spec_db_hist * hist_plotting_range)
ax1.plot(hist_plotting_points, sample_frequencies, 'k-', linewidth=10, alpha=0.6)
ax1.plot([trace_time_matplotlib[-1],trace_time_matplotlib[-1]-hist_plotting_range],
[sample_frequencies[-1],sample_frequencies[-1]], 'k-', linewidth=10, alpha=0.6)
ax1.plot(trace_time_matplotlib[-1]-hist_plotting_range, sample_frequencies[-1], 'k<', markersize=50)
for earthquake_time_matplotlib in earthquake_times_matplotlib:
ax1.axvline(x=earthquake_time_matplotlib, linestyle='--', color='k', linewidth=3, alpha=0.7)
ax1.set_ylabel('Frequency (Hz)',fontsize=22)
if log:
ax1.set_yscale('log')
if freq_lims is not None:
ax1.set_ylim([freq_min,freq_max])
ax1.tick_params(axis='y',labelsize=18)
ax1.set_xlim([starttime.matplotlib_date,endtime.matplotlib_date])
ax1.set_xticks(time_tick_list_mpl)
ax1.set_xticklabels(time_tick_labels,fontsize=18,rotation=30,ha='right',rotation_mode='anchor')
ax1.set_title(trace.id, fontsize=24, fontweight='bold')
cbar = fig.colorbar(c, aspect=10, pad=0.005, ax=ax1, location='right')
cbar.set_label(colorbar_label, fontsize=18)
cbar.ax.tick_params(labelsize=16)
ax2.plot(trace.times('matplotlib'), trace.data * rescale_factor,'k-',linewidth=1)
ax2.set_ylabel(y_axis_label, fontsize=22)
ax2.tick_params(axis='y',labelsize=18)
ax2.yaxis.offsetText.set_fontsize(18)
ax2.set_xlim([starttime.matplotlib_date, endtime.matplotlib_date])
ax2.set_xticks(time_tick_list_mpl)
ax2.set_xticklabels(time_tick_labels,fontsize=18,rotation=30, ha='right',rotation_mode='anchor')
ax2.set_xlabel('UTC Time on ' + starttime.date.strftime('%b %d, %Y'), fontsize=22)
ax2.grid()
if export_path is None:
fig.show()
else:
file_label = starttime.strftime('%Y%m%d_%H%M_') + trace.id.replace('.','_')
fig.savefig(export_path + file_label + '.png',bbox_inches='tight')
extent = ax1.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
fig.savefig(export_path + file_label + 'spec.png',bbox_inches=extent)
plt.close()
def plot_spectrogram_multi(stream,starttime,endtime,window_duration,freq_lims,log=False,demean=False,v_percent_lims=(20,100),cmap=cc.cm.rainbow,earthquake_times=None,explosion_times=None,db_hist=False,export_path=None,export_spec=True):
"""
Plot all traces in a stream and their corresponding spectrograms in separate plots using matplotlib
:param stream (:class:`~obspy.core.stream.Stream`): Input data
:param starttime (:class:`~obspy.core.utcdatetime.UTCDateTime`): Start time for desired plot
:param endtime (:class:`~obspy.core.utcdatetime.UTCDateTime`): End time for desired plot
:param window_duration (float): Duration of spectrogram window [s]
:param freq_lims (tuple): Tuple of length 2 storing minimum frequency and maximum frequency for the spectrogram plot ([Hz],[Hz])
:param log (bool): If `True`, plot spectrogram with logarithmic y-axis
:param v_percent_lims (tuple): Tuple of length 2 storing the percentile values in the spectrogram matrix used as colorbar limits. Default is (20,100).
:param cmap (str or :class:`matplotlib.colors.LinearSegmentedColormap`): Colormap for spectrogram plot. Default is colorcet.cm.rainbow.
:param earthquake_times (list of :class:`~obspy.core.utcdatetime.UTCDateTime`): List of UTCDateTimes storing earthquake origin times to be plotted as vertical black dashed lines.
:param explosion_times (list of :class:`~obspy.core.utcdatetime.UTCDateTime`): List of UTCDateTimes storing explosion detection times to be plotted as vertical dark red dashed lines.
:param db_hist (bool): If `True`, plot a db histogram (spanning the plotted timespan) on the right side of the spectrograms across the sample frequencies
:param export_path (str or `None`): If str, export plotted figures as '.png' files, named by the trace id and time. If `None`, show figure in interactive python.
:param export_spec (bool): If `True`, export spectrogram with trimmed-off axis labels (useful for labeling)
"""
# Initialize figure based on length of input stream
figsize = (32, 4 * len(stream))
fig, axs = plt.subplots(len(stream), 1, figsize=figsize)
fig.subplots_adjust(hspace=0)
# Loop over each trace in the stream
for axs_index, trace in enumerate(stream):
# Define target axis
if len(stream) > 1:
target_ax = axs[axs_index]
else:
target_ax = axs
# Check if input trace is infrasound (SEED channel name ends with 'DF'). Else, assume seismic.
if trace.stats.channel[1:] == 'DF':
# If infrasound, define corresponding reference values
REFERENCE_VALUE = 20 * 10 ** -6 # Pressure, in Pa
SPEC_THRESH = 0 # Power value indicative of gap
rescale_factor = 1 # Plot waveform in Pa
else:
# If seismic, define corresponding reference values
REFERENCE_VALUE = 1 # Velocity, in m/s
SPEC_THRESH = -220 # Power value indicative of gap
rescale_factor = 10 ** -6 # Plot waveform in micrometer/s
# Extract trace information for FFT
sampling_rate = trace.stats.sampling_rate
samples_per_segment = int(window_duration * sampling_rate)
# Compute spectrogram (Note that overlap is 90% of samples_per_segment)
sample_frequencies, segment_times, spec = spectrogram(trace.data, sampling_rate, window='hann',
scaling='density', nperseg=samples_per_segment,
noverlap=samples_per_segment * .9)
# Convert spectrogram matrix to decibels for plotting
spec_db = 10 * np.log10(abs(spec) / (REFERENCE_VALUE ** 2))
# If demeaning is desired, remove temporal mean from spectrogram
if demean:
# column_ht = np.shape(spec_db)[0]
# ratio_vec = np.linspace(0,0.5,column_ht).reshape(column_ht,1)
# spec_db = spec_db - np.mean(spec_db,1)[:, np.newaxis]*ratio_vec
spec_db = spec_db - np.mean(spec_db, 1)[:, np.newaxis]
# Convert trace times to matplotlib dates
trace_time_matplotlib = trace.stats.starttime.matplotlib_date + (segment_times / dates.SEC_PER_DAY)
# Determine number of ticks smartly
if ((endtime - starttime) % 1800) == 0:
denominator = 12
else:
denominator = 10
# If earthquake times are provided, convert them from UTCDateTime to matplotlib dates
if earthquake_times:
earthquake_times_matplotlib = [eq.matplotlib_date for eq in earthquake_times]
else:
earthquake_times_matplotlib = []
# If explosion times are provided, convert them from UTCDateTime to matplotlib dates
if explosion_times:
explosion_times_matplotlib = [ex.matplotlib_date for ex in explosion_times]
else:
explosion_times_matplotlib = []
# Craft figure
# If frequency limits are defined
if freq_lims is not None:
# Determine frequency limits and trim spec_db
freq_min = freq_lims[0]
freq_max = freq_lims[1]
spec_db_plot = spec_db[np.flatnonzero((sample_frequencies > freq_min) & (sample_frequencies < freq_max)), :]
target_ax.imshow(spec_db,
extent=[trace_time_matplotlib[0], trace_time_matplotlib[-1],
sample_frequencies[0],
sample_frequencies[-1]],
vmin=np.percentile(spec_db_plot[spec_db_plot>SPEC_THRESH], v_percent_lims[0]),
vmax=np.percentile(spec_db_plot[spec_db_plot>SPEC_THRESH], v_percent_lims[1]),
origin='lower', aspect='auto', interpolation='None', cmap=cmap)
# If we want a db spectrogram across the plotted time span, compute and plot on the right side of the figure
if db_hist:
spec_db_hist = np.sum(spec_db_plot, axis=1)
spec_db_hist = (spec_db_hist - np.min(spec_db_hist)) / (np.max(spec_db_hist) - np.min(spec_db_hist))
hist_plotting_range = (1/denominator) * (trace_time_matplotlib[-1] - trace_time_matplotlib[0])
hist_plotting_points = trace_time_matplotlib[-1] - (spec_db_hist * hist_plotting_range)
sample_frequencies_plot = sample_frequencies[
np.flatnonzero((sample_frequencies > freq_min) & (sample_frequencies < freq_max))]
target_ax.plot(hist_plotting_points, sample_frequencies_plot, 'k-', linewidth=8, alpha=0.6)
target_ax.plot([trace_time_matplotlib[-1], trace_time_matplotlib[-1] - hist_plotting_range],
[sample_frequencies_plot[-1], sample_frequencies_plot[-1]], 'k-', linewidth=8, alpha=0.6)
target_ax.plot(trace_time_matplotlib[-1] - hist_plotting_range, sample_frequencies_plot[-1], 'k<', markersize=30)
# If no frequencies limits are given
else:
# We go straight into plotting spec_db
target_ax.imshow(spec_db,
extent=[trace_time_matplotlib[0], trace_time_matplotlib[-1],
sample_frequencies[0],
sample_frequencies[-1]],
vmin=np.percentile(spec_db[spec_db>SPEC_THRESH], v_percent_lims[0]),
vmax=np.percentile(spec_db[spec_db>SPEC_THRESH], v_percent_lims[1]),
origin='lower', aspect='auto', interpolation='None', cmap=cmap)
# If we want a db spectrogram across the plotted time span, compute and plot on the right side of the figure
if db_hist:
spec_db_hist = np.sum(spec_db, axis=1)
spec_db_hist = (spec_db_hist - np.min(spec_db_hist)) / (np.max(spec_db_hist) - np.min(spec_db_hist))
hist_plotting_range = (1 / denominator) * (trace_time_matplotlib[-1] - trace_time_matplotlib[0])
hist_plotting_points = trace_time_matplotlib[-1] - (spec_db_hist * hist_plotting_range)
target_ax.plot(hist_plotting_points, sample_frequencies, 'k-', linewidth=8, alpha=0.6)
target_ax.plot([trace_time_matplotlib[-1], trace_time_matplotlib[-1] - hist_plotting_range],
[sample_frequencies[-1], sample_frequencies[-1]], 'k-', linewidth=8, alpha=0.6)
target_ax.plot(trace_time_matplotlib[-1] - hist_plotting_range, sample_frequencies[-1], 'k<', markersize=30)
for earthquake_time_matplotlib in earthquake_times_matplotlib:
target_ax.axvline(x=earthquake_time_matplotlib, linestyle='--', color='k', linewidth=3, alpha=0.7)
for explosion_time_matplotlib in explosion_times_matplotlib:
target_ax.axvline(x=explosion_time_matplotlib, linestyle='--', color='darkred', linewidth=3, alpha=0.7)
if log:
target_ax.set_yscale('log')
if freq_lims is not None:
target_ax.set_ylim([freq_min, freq_max])
target_ax.set_yticks(range(2, freq_max + 1, 2))
target_ax.set_xlim([starttime.matplotlib_date, endtime.matplotlib_date])
target_ax.tick_params(axis='y', labelsize=18)
target_ax.set_ylabel(trace.id, fontsize=22, fontweight='bold')
time_tick_list = np.arange(starttime, endtime + 1, (endtime - starttime) / denominator)
time_tick_list_mpl = [t.matplotlib_date for t in time_tick_list]
time_tick_labels = [time.strftime('%H:%M') for time in time_tick_list]
bottom_ax = axs[-1] if len(stream)>1 else axs
bottom_ax.set_xticks(time_tick_list_mpl)
bottom_ax.set_xticklabels(time_tick_labels, fontsize=22, rotation=30, ha='right', rotation_mode='anchor')
bottom_ax.set_xlabel('UTC Time on ' + starttime.date.strftime('%b %d, %Y'), fontsize=25)
if export_path is None:
fig.show()
else:
file_label = starttime.strftime('%Y%m%d_%H%M') + '__' + endtime.strftime('%Y%m%d_%H%M') + '_' + '_'.join([tr.id.split('.')[1] for tr in stream])
fig.savefig(export_path + file_label + '.png', bbox_inches='tight')
if export_spec:
top_ax = axs[0] if len(stream)>1 else axs
extent1 = top_ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
extent2 = bottom_ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
extent = Bbox([extent2._points[0], extent1._points[1]])
fig.savefig(export_path + file_label + '_spec.png', bbox_inches=extent)
plt.close()
def calculate_spectrogram(trace,starttime,endtime,window_duration,freq_lims,overlap=0.9,demean=False):
"""
Calculates and returns a 2D matrix storing the spectrogram values (of the input trace) in decibels
:param trace (:class:`~obspy.core.stream.Trace`): Input data
:param starttime (:class:`~obspy.core.utcdatetime.UTCDateTime`): Start time for desired spectrogram
:param endtime (:class:`~obspy.core.utcdatetime.UTCDateTime`): End time for desired spectrogram
:param window_duration (float): Duration of spectrogram window [s]
:param freq_lims (tuple): Tuple of length 2 storing minimum frequency and maximum frequency for the spectrogram plot ([Hz],[Hz])
:param overlap (float): Ratio of window to overlap when computing spectrogram (0 to 1)
:return: numpy.ndarray: 2D spectrogram matrix storing power ratio values in decibels
:return: numpy.ndarray: 1D array storing segment times in (:class:`~obspy.core.utcdatetime.UTCDateTime`) format
"""
# Check if input trace is infrasound (SEED channel name ends with 'DF'). Else, assume seismic.
if trace.stats.channel[1:] == 'DF':
# If infrasound, define corresponding reference values
REFERENCE_VALUE = 20 * 10 ** -6 # Pressure, in Pa
else:
# If seismic, define corresponding reference values
REFERENCE_VALUE = 1 # Velocity, in m/s
# Extract trace information for FFT
sampling_rate = trace.stats.sampling_rate
samples_per_segment = int(window_duration * sampling_rate)
# Compute spectrogram (Note that overlap is 90% of samples_per_segment)
sample_frequencies, segment_times, spec = spectrogram(trace.data, sampling_rate, window='hann',
scaling='density', nperseg=samples_per_segment,
noverlap=samples_per_segment * overlap)
# Calculate UTC times corresponding to all segments
trace_time_matplotlib = trace.stats.starttime.matplotlib_date + (segment_times / dates.SEC_PER_DAY)
utc_times = np.array([UTCDateTime(dates.num2date(mpl_time)) for mpl_time in trace_time_matplotlib])
# Find desired indices and trim spectrogram output
desired_indices = np.flatnonzero([starttime <= t < endtime for t in utc_times])
spec = spec[:,desired_indices]
utc_times = utc_times[desired_indices]
# Convert spectrogram matrix to decibels
spec_db = 10 * np.log10(abs(spec) / (REFERENCE_VALUE ** 2))
# If demeaning is desired, remove temporal mean from spectrogram
if demean:
spec_db = spec_db - np.mean(spec_db, 1)[:, np.newaxis]
# If frequency limits are defined
if freq_lims is not None:
# Determine frequency limits and trim spec_db
freq_min = freq_lims[0]
freq_max = freq_lims[1]
spec_db = spec_db[np.flatnonzero((sample_frequencies > freq_min) & (sample_frequencies < freq_max)), :]
return spec_db, utc_times
def create_labeled_dataset(json_filepath, output_dir, label_dict, transient_indices, time_step, source, network, station, location, channel, pad, window_duration, freq_lims, transient_ratio=0.1):
"""
Create a labeled spectrogram dataset from a json file from label studio
:param json_filepath (str): File path to the json file from label studio
:param output_dir (str): Directory to save the npy files
:param label_dict (dict): Dictionary to convert labels to appended file index
:param transient_indices (list): List of indices for transients (these will be prioritized in assigning labels, and the higher index number will be prioritized)
:param time_step (float): Time step for the 2D matrices
:param source (str): Source of the data
:param network (str or list): SEED network code(s)
:param station (str or list): SEED station code(s)
:param channel (str or list): SEED channel code(s)
:param location (str or list): SEED location code(s)
:param pad (float): Padding length [s]
:param window_duration (float): Window duration for the spectrogram [s]
:param freq_lims (tuple): Tuple of length 2 storing minimum frequency and maximum frequency for the spectrogram plot ([Hz],[Hz])
:param transient_ratio (float): Ratio of transient-related time samples for transient classes to be prioritized (default: 0.1)
"""
# Check if output directory exists
if not os.path.exists(output_dir):
raise ValueError('Output directory does not exist')
# Parse json file from label studio
f = open(json_filepath)
labeled_images = json.load(f)
f.close()
# Loop over all labeled images:
for labeled_image in labeled_images:
# Extract out file name, and define starttime, endtime and stations covered by spectrogram image
filename = labeled_image['file_upload'].split('-')[1]
chunks = filename.split('_')
t1 = UTCDateTime(chunks[0] + chunks[1])
t2 = UTCDateTime(chunks[3] + chunks[4])
stations = chunks[5:-1]
# Extract all annotations
annotations = labeled_image['annotations'][0]['result']
# If no annotations exist, skip
if len(annotations) == 0:
print('No annotations on image')
continue
# Otherwise define original width and height of image in pixels and determine pixels indicating each station
else:
time_per_percent = (t2 - t1) / 100
y_span = annotations[0]['original_height']
y_per_percent = y_span / 100
station_indicators = np.arange(y_span / (len(stations) * 2), y_span, y_span / (len(stations)))
# Initialize time bound list
time_bounds = []
# Now loop over annotations to fill
for annotation in annotations:
if annotation['value']['rectanglelabels'] == []:
continue
label = annotation['value']['rectanglelabels'][0]
x1 = t1 + (annotation['value']['x'] * time_per_percent)
x2 = t1 + ((annotation['value']['x'] + annotation['value']['width']) * time_per_percent)
y1 = (annotation['value']['y'] * y_per_percent)
y2 = ((annotation['value']['y'] + annotation['value']['height']) * y_per_percent)
stations_observed = [stations[i] for i in range(len(stations))
if (station_indicators[i] > y1 and station_indicators[i] < y2)]
for station_observed in stations_observed:
time_bound = [station_observed, x1, x2, label]
time_bounds.append(time_bound)
# Load data using waveform_collection tool
successfully_loaded = False
while not successfully_loaded:
try:
# Gather waveforms
stream = gather_waveforms(source=source, network=network, station=station, location=location,
channel=channel, starttime=t1 - pad, endtime=t2 + pad, verbose=False)
# Process waveform
stream = process_waveform(stream, remove_response=True, detrend=False, taper_length=pad,
taper_percentage=None, filter_band=None, verbose=False)
successfully_loaded = True
except:
print('gather_waveforms failed to retrieve response')
pass
# Loop over stations that have data
stream_stations = [tr.stats.station for tr in stream]
for i, stream_station in enumerate(stream_stations):
# Choose trace corresponding to station
trace = stream[i]
# Calculate spectrogram power matrix
spec_db, utc_times = calculate_spectrogram(trace, t1, t2, window_duration, freq_lims, demean=False)
# Get label time bounds that are observed on station
time_bounds_station = [tb for tb in time_bounds if tb[0] == stream_station]
# Define array of time steps for spectrogram slicing
step_bounds = np.arange(t1, t2 + time_step, time_step)
# Loop over time steps
for j in range(len(step_bounds) - 1):
# Slice spectrogram
sb1 = step_bounds[j]
sb2 = step_bounds[j + 1]
spec_slice_indices = np.flatnonzero([sb1 < t < sb2 for t in utc_times])
spec_slice = spec_db[:, spec_slice_indices]
# Enforce spectrogram length
if np.shape(spec_slice)[1] != time_step:
# Try inclusive slicing time span (<= sb2)
spec_slice_indices = np.flatnonzero([sb1 < t <= sb2 for t in utc_times])
spec_slice = spec_db[:, spec_slice_indices]
# If it still doesn't fit our shape, try double inclusive time bounds
if np.shape(spec_slice)[1] != time_step:
spec_slice_indices = np.flatnonzero([sb1 <= t <= sb2 for t in utc_times])
spec_slice = spec_db[:, spec_slice_indices]
# Otherwise, raise error
if np.shape(spec_slice)[1] != time_step:
raise ValueError('THE SHAPE IS NOT RIGHT.')
# Skip matrices that have a spectrogram data gap
amplitude_threshold = 0 if channel[-2:] == 'DF' else -220
if np.sum(spec_slice.flatten() < amplitude_threshold) > (0.2 * time_step):
print('Skipping due to data gap, %d elements failed the check' % np.sum(spec_slice.flatten() < amplitude_threshold))
continue
# Obtain corresponding time samples for spectrogram slice
time_slice = utc_times[spec_slice_indices]
# Check for overlaps and fill a vector with labels to decide final label
label_indices = np.ones(len(time_slice)) * -1
for time_bound_station in time_bounds_station:
# Labeled time bound starts in slice and ends in slice
if time_bound_station[1] >= sb1 and time_bound_station[2] <= sb2:
valid_indices = np.flatnonzero(
np.logical_and(time_slice >= time_bound_station[1], time_slice <= time_bound_station[2]))
label_indices[valid_indices] = label_dict[time_bound_station[3]]
# Labeled time bound starts before slice and ends after slice
elif time_bound_station[1] < sb1 and time_bound_station[2] > sb2:
label_indices[:] = label_dict[time_bound_station[3]]
# Labeled time bound starts before slice and ends in slice
elif time_bound_station[1] < sb1 and (sb1 <= time_bound_station[2] <= sb2):
label_indices[np.flatnonzero(time_slice <= time_bound_station[2])] = label_dict[
time_bound_station[3]]
# Labeled time bound starts in slice and ends after slice
elif (sb1 <= time_bound_station[1] <= sb2) and time_bound_station[2] > sb2:
label_indices[np.flatnonzero(time_slice >= time_bound_station[1])] = label_dict[
time_bound_station[3]]
# Count how many time samples correspond to each label
labels_seen, label_counts = np.unique(label_indices, return_counts=True)
# Define dummy label
final_label = -1
# Check for tremor or noise label in > 50 % of the time samples
if np.max(label_counts) > 0.5 * len(label_indices) and sts.mode(label_indices) != -1:
final_label_value = int(labels_seen[np.argmax(label_counts)])
final_label = next(key for key, value in label_dict.items() if value == final_label_value)
# Override label with transient label if it is in > 10 % of the time samples
if len(set(labels_seen) & set(transient_indices)) != 0:
for transient_index in list(set(labels_seen) & set(transient_indices)):
if label_counts[list(labels_seen).index(transient_index)] >= transient_ratio * len(label_indices):
final_label = list(label_dict.keys())[int(transient_index)]
# If label is still invalid, skip
if final_label == -1:
continue
# Construct file name and save
file_name = stream_station + '_' + sb1.strftime('%Y%m%d%H%M') + '_' + \
sb2.strftime('%Y%m%d%H%M') + '_' + str(label_dict[final_label]) + '.npy'
np.save(output_dir + file_name, spec_slice)
print('Done.')
def check_timeline(source,network,station,channel,location,starttime,endtime,model_path,meanvar_path,overlap,pnorm_thresh=None,generate_fig=True,fig_width=32,fig_height=None,font_s=22,spec_kwargs=None,dr_kwargs=None,export_path=None,transparent=False,n_jobs=1):
"""
Pulls data, then loads a trained model to predict the timeline of classes
:param source (str): Which source to gather waveforms from (e.g. IRIS)
:param network (str): SEED network code [wildcards (``*``, ``?``) accepted]
:param station (str): SEED station code or comma separated station codes [wildcards NOT accepted]
:param channel (str): SEED location code [wildcards (``*``, ``?``) accepted]
:param location (str): SEED channel code [wildcards (``*``, ``?``) accepted]
:param starttime (:class:`~obspy.core.utcdatetime.UTCDateTime`): Start time for data request
:param endtime (:class:`~obspy.core.utcdatetime.UTCDateTime`): End time for data request
:param model_path (str): Path to model .keras or .h5 file
:param meanvar_path (str): Path to model's meanvar .npy file. If `None`, no meanvar standardization is applied.
:param overlap (float): Percentage/ratio of overlap for successive spectrogram slices
:param pnorm_thresh (float): Threshold for network-averaged probability cutoff. If `None` [default], no threshold is applied
:param generate_fig (bool): If `True`, produce timeline figure, if `False`, return outputs without plots
:param fig_width (float): Figure width [in]
:param fig_height (float): Figure height [in] (if `None`, figure height = figure width * 0.75)
:param font_s (float): Font size [points]
:param spec_kwargs (dict): Dictionary of spectrogram plotting parameters (pad, window_duration, freq_lims, v_percent_lims)
:param dr_kwargs (dict): Dictionary of reduced displacement plotting parameters (reference_station, filter_band, window_length, overlap, volc_lat, volc_lon, seis_vel, dominant_freq, med_filt_kernel, dr_lims)
:param export_path (str): (str or `None`): If str, export plotted figures as '.png' files, named by the trace id and time. If `None`, show figure in interactive python.
:param transparent (bool): If `True`, export with transparent background
:param n_jobs (int): Number of CPUs used for data retrieval in parallel. If n_jobs = -1, all CPUs are used. If n_jobs < -1, (n_cpus + 1 + n_jobs) are used. Default is 1 (a single processor).
:return: numpy.ndarray: 2D matrix storing all predicted classes (only returns if generate_fig==False or export_path==None)
:return: numpy.ndarray: 2D matrix storing all predicted probabilities (only returns if generate_fig==False or export_path==None)
"""
rcParams['font.size'] = font_s
# Load model
saved_model = load_model(model_path)
nclasses = saved_model.layers[-1].get_config()['units']
nsubrows = len(station.split(','))
# Extract mean and variance from training
if meanvar_path:
standardize_spectrograms = True
saved_meanvar = np.load(meanvar_path)
running_x_mean = saved_meanvar[0]
running_x_var = saved_meanvar[1]
else:
standardize_spectrograms = False
# Define fixed values
spec_height = saved_model.layers[0].input.shape[1]
interval = saved_model.layers[0].input.shape[2]
time_step = int(np.round(interval*(1-overlap)))
spec_kwargs = {} if spec_kwargs is None else spec_kwargs
pad = spec_kwargs['pad'] if 'pad' in spec_kwargs else 360
window_duration = spec_kwargs['window_duration'] if 'window_duration' in\
spec_kwargs else 10
freq_lims = spec_kwargs['freq_lims'] if 'freq_lims' in spec_kwargs else \
(0.5, 10)
v_percent_lims = spec_kwargs['v_percent_lims'] if 'v_percent_lims' in\
spec_kwargs else (20, 97.5)
# Determine if infrasound
infrasound = True if channel[-1] == 'F' else False
reference_value = 20 * 10 ** -6 if infrasound else 1 # Pa for infrasound, m/s for seismic
spec_thresh = 0 if infrasound else -220 # Power value indicative of gap
# Enforce the duration to be a multiple of the model's time step
if (endtime - starttime - interval) % time_step != 0:
print('The desired analysis duration is not a multiple of the inbuilt time step.')
endtime = endtime + (time_step - (endtime - starttime - interval) % time_step)
print('Rounding up endtime to %s.' % str(endtime))
# Load data, remove response, and re-order
successfully_loaded = False
load_starttime = time.time()
while not successfully_loaded:
try:
stream_raw = gather_waveforms(source=source, network=network, station=station,
location=location, channel=channel,
starttime=starttime - pad, endtime=endtime + pad,
verbose=False, n_jobs=n_jobs)
stream = process_waveform(stream_raw.copy(), remove_response=True, detrend=False,
taper_length=pad, verbose=False)
successfully_loaded = True
except:
print('Data pull failed, trying again in 10 seconds...')
time.sleep(10)
load_currenttime = time.time()
if load_currenttime-load_starttime < 60:
pass
else:
raise Exception('Data pull timeout for starttime=%s, endtime=%s' % (str(starttime),str(endtime)))
# reorder both raw and processed streams
stream_default_order = [tr.stats.station for tr in stream]
desired_index_order = [stream_default_order.index(stn) for stn in
station.split(',') if stn in stream_default_order]
stream = Stream([stream[i] for i in desired_index_order])
stream_raw = Stream([stream_raw[i] for i in desired_index_order])
# If stream sampling rate is not an integer, fix
for tr in stream:
if tr.stats.sampling_rate != np.round(tr.stats.sampling_rate):
tr.stats.sampling_rate = np.round(tr.stats.sampling_rate)
# Initialize spectrogram slice and id stack
spec_stack = []
spec_ids = []
# Loop over stations that have data
stream_stations = [tr.stats.station for tr in stream]
for j, stream_station in enumerate(stream_stations):
# Choose trace corresponding to station
trace = stream[j]
# Calculate spectrogram power matrix
spec_db, utc_times = calculate_spectrogram(trace, starttime, endtime,
window_duration=window_duration,
freq_lims=freq_lims)
# Reshape spectrogram into stack of desired spectrogram slices
spec_slices = [spec_db[:, t:(t + interval)] for t in
range(0, spec_db.shape[-1] - interval + 1, time_step)]
spec_tags = [stream_station + '_' + step_bound.strftime('%Y%m%d%H%M%S') + '_' + \
(step_bound + interval).strftime('%Y%m%d%H%M%S') \
for step_bound in np.arange(starttime,endtime-interval+1,time_step)]
spec_stack += spec_slices
spec_ids += spec_tags
# Convert spectrogram slices to an array
spec_stack = np.array(spec_stack)
spec_ids = np.array(spec_ids)
# If there are spectrogram slices
if len(spec_stack) != 0:
# Remove spectrograms with data gap
keep_index = np.where(np.sum(spec_stack<spec_thresh, axis=(1,2)) < (0.2 * interval))
spec_stack = spec_stack[keep_index]
spec_ids = spec_ids[keep_index]
# Standardize and min-max scale
if standardize_spectrograms:
spec_stack = (spec_stack - running_x_mean) / np.sqrt(running_x_var + 1e-5)
spec_stack = (spec_stack - np.min(spec_stack, axis=(1, 2))[:, np.newaxis, np.newaxis]) / \
(np.max(spec_stack, axis=(1, 2)) - np.min(spec_stack, axis=(1, 2)))[:, np.newaxis, np.newaxis]
# Otherwise, return empty class and probability matrix or raise Exception
else:
if not generate_fig:
matrix_length = int(np.ceil((endtime - starttime - interval) / time_step)) + 1
class_mat = np.ones((nsubrows + 1, matrix_length)) * 6
prob_mat = np.vstack((np.zeros((nsubrows, matrix_length)), np.ones((1, matrix_length)) * np.nan))
return class_mat, prob_mat
else:
raise Exception('No data available for desired timeline!')
# Make predictions
spec_predictions = saved_model.predict(spec_stack)
predicted_labels = np.argmax(spec_predictions, axis=1)
indicators = []
for i, spec_id in enumerate(spec_ids):
chunks = spec_id.split('_')
indicators.append([chunks[0], UTCDateTime(chunks[1]) + np.round(interval / 2),
predicted_labels[i], spec_predictions[i, :]])
# Craft plotting matrix and probability matrix
matrix_length = int(np.ceil((endtime - starttime - interval) / time_step)) + 1
matrix_height = nsubrows
matrix_plot = np.ones((matrix_height, matrix_length)) * nclasses
matrix_probs = np.zeros((matrix_height, matrix_length, np.shape(spec_predictions)[1]))
for indicator in indicators:
row_index = station.split(',').index(indicator[0])
col_index = int((indicator[1] - np.round(interval / 2) - starttime) / time_step)
matrix_plot[row_index, col_index] = indicator[2]
matrix_probs[row_index, col_index, :] = indicator[3]
# Add voting row
np.seterr(divide='ignore', invalid='ignore') # Mute division by zero error
na_label = nclasses # this index is one higher than the number of classes
new_row = np.ones((1, np.shape(matrix_plot)[1])) * na_label
matrix_plot = np.concatenate((matrix_plot, new_row))
# Sum different station probabilities and derive network max
matrix_probs_sum = np.sum(matrix_probs, axis=0)
matrix_contributing_station_count = np.sum(np.sum(matrix_probs, axis=2) != 0, axis=0)
voted_labels = np.argmax(matrix_probs_sum, axis=1)
voted_labels[matrix_contributing_station_count==0] = na_label
voted_probabilities = np.max(matrix_probs_sum, axis=1) / matrix_contributing_station_count # normalize by number of stations
# remove low probability votes
if pnorm_thresh:
print(f'Removing low probability classifications (Pnorm < {pnorm_thresh})'
f' from voting scheme.')
# remove low probability votes
voted_labels[voted_probabilities < pnorm_thresh] = na_label
matrix_plot = np.concatenate((matrix_plot, np.reshape(voted_labels, (1, np.shape(matrix_plot)[1]))))
# Calculate and return class and probability outputs if figure plotting is not desired
class_mat = np.vstack((matrix_plot[:-2, :], matrix_plot[-1:, :]))
prob_mat = np.vstack((np.max(matrix_probs, axis=2), voted_probabilities))
if not generate_fig:
return class_mat, prob_mat
# Pad matrix plot and voted probabilities with unclassified columns for plotting
matrix_plot = np.repeat(matrix_plot, 2, axis=1)
num_columns_to_pad = int(np.round(interval / 2) / time_step)
matrix_plot = np.pad(matrix_plot, ((0, 0), (num_columns_to_pad*2-1, num_columns_to_pad*2-1)), 'constant', constant_values=(na_label, na_label))
voted_probabilities = np.pad(voted_probabilities, (num_columns_to_pad, num_columns_to_pad), 'constant', constant_values=(np.nan, np.nan))
# If dealing with seismic, use seismic voting scheme
if not infrasound:
# Craft corresponding rgb values
if nclasses == 6:
rgb_values = np.array([
[193, 39, 45],
[0, 129, 118],
[0, 0, 167],
[238, 204, 22],
[164, 98, 0],
[40, 40, 40],
[255, 255, 255]])
rgb_keys = ['Broadband\nTremor',
'Harmonic\nTremor',
'Monochromatic\nTremor',
'Earthquake',
'Explosion',
'Noise',
'N/A']
elif nclasses == 7: