-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtrain_est.py
2237 lines (1756 loc) · 97.6 KB
/
train_est.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
#!/usr/bin/env python3
import numpy as np
from pdb import set_trace as bp
import pandas as pd
import os
import obspy
import pickle
import joblib
import time
import string
import matplotlib.pyplot as plt
import seaborn as sb
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
import matplotlib.colors as mcolors
import seaborn as sns
from matplotlib.colors import ListedColormap
from mpl_toolkits.axes_grid1.inset_locator import mark_inset
from scipy import interpolate
from obspy.signal.trigger import classic_sta_lta
from sklearn.metrics import roc_curve, auc
from sklearn.neural_network import MLPRegressor
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
from sklearn.ensemble import ExtraTreesClassifier
import joblib
from sklearn import preprocessing
from sklearn.metrics import confusion_matrix, classification_report
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
from sklearn.base import clone
import itertools
import compute_params_waveform, read_data, detector
def create_CNN(input_shape, Nclasses=2, loss='binary_crossentropy', optimizer='adam'):
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Conv2D, Flatten, Dense
## Create model
model = Sequential()
## Add model layers
model.add(Conv2D(64, kernel_size=3, activation='relu', input_shape=input_shape))
model.add(Conv2D(32, kernel_size=3, activation='relu'))
model.add(Flatten())
if Nclasses > 2:
model.add(Dense(Nclasses, activation='softmax'))
else:
model.add(Dense(1, activation='sigmoid'))
## Compile model using accuracy to measure model performance
model.compile(optimizer=optimizer, loss=loss, metrics=['accuracy'])
return model
def train_CNN(model, X_train, y_train, X_test, y_test, epochs=3):
X_train_ = reshape_dataframe_spectrograms(X_train, ['spectro'])
X_test_ = reshape_dataframe_spectrograms(X_test, ['spectro'])
le = build_label_encoder(y_train)
y_train_ = le.transform(y_train)
y_test_ = le.transform(y_test)
## Train the model
model.fit(X_train_, y_train_, validation_data=(X_test_, y_test_), epochs=epochs)
def count_values_over_threhsold(x, threshold):
"""
Add up all correlations over a given threshold
"""
loc_threshold = np.where(abs(x.values) >= threshold)[0]
x['count'] = abs(x[loc_threshold]).sum()
return x
def get_number_correlations(correlations, threshold):
"""
Compute number of correlations over a threshold for each row
"""
number_correlations = (abs(correlations)>=threshold).sum(1)
number_correlations.sort_values(inplace=True, ascending=False)
return number_correlations
def select_uncorrelated_input_features(data, type_corr='spearman', threshold=0.6):
"""
Iteratively remove most correlated inputs from input features
"""
list_corr = data_without_info_columns(data).columns
correlations = find_list_correlations(data, list_corr, type_corr)
## Number of values over the threhsold for each input
most_correlated_inputs = correlations.apply(count_values_over_threhsold, args=[threshold], axis=1)
most_correlated_inputs = most_correlated_inputs['count'].copy()
most_correlated_inputs.sort_values(inplace=True, ascending=False)
cpt_correlation = 0
correlations_output = correlations.copy()
number_correlations_output = get_number_correlations(correlations_output, threshold)
while cpt_correlation < len(most_correlated_inputs) and \
number_correlations_output.sum() > correlations_output.shape[0]:
correlations_output = \
correlations_output.drop(most_correlated_inputs.index[cpt_correlation], axis=0)
correlations_output = \
correlations_output.drop(most_correlated_inputs.index[cpt_correlation], axis=1)
number_correlations_output = get_number_correlations(correlations_output, threshold)
cpt_correlation += 1
return correlations, correlations_output
def find_list_correlations(data, list_corr, type_corr):
"""
Compute cross correlations between inputs features in data[list_corr]
"""
## Find data to get correlations from
list_observations_corr = data[list_corr]
correlations = list_observations_corr.corr(method=type_corr)
return correlations
def plot_statistics(data, list_corr, options, type_corr = 'spearman', fontize=10.):
"""
Plot Spearman's correlation between input features.
"""
## Compute correlations
correlations = find_list_correlations(data, list_corr, type_corr)
correlations = correlations.dropna(thresh=2, axis='rows')
correlations = correlations.dropna(axis='columns')
## Plot correlations
fig, ax = plt.subplots(nrows=1, ncols=1)
sns.heatmap(correlations, cbar=True, ax=ax, vmin=0., vmax=0.8, cbar_kws={'extend':'both'})
ax.set_title(type_corr + ' correlation coefficients', fontsize=fontize)
fig.subplots_adjust(bottom=0.1, left=0.1, top=0.95, right=0.95)
fig.savefig(options['DIR_FIGURES'] + 'correlation_detections_'+read_data.get_str_options(options)+'.pdf')
plt.close('all')
return correlations
def generate_colormap(transparent_below_threshold):
"""
Generate a colormap with a without a transparent end
"""
cmap = sns.color_palette("flare", as_cmap=True)
cmap_background = cmap(np.arange(cmap.N))
if transparent_below_threshold:
cmap_background[:,-1] = np.linspace(0., 1, cmap.N)
cmap_background = ListedColormap(cmap_background)
if not transparent_below_threshold:
cmap_background.set_under(color='grey', alpha=0.2)
return cmap_background
def plot_probability_curves(ax, probas, window, norm_proba, cmap, shift_window, Npoints=10000):
"""
Plot detection probabilities as filled curves
"""
## Create time vector
add_number = 100
shift_window_ = shift_window#window*0.5/3600.
t = shift_window_ + probas['time'].values/3600.
t[0] = probas['time'].min()/3600.
t_add = np.linspace(t[0], t[1], add_number+1)
t = np.concatenate((t_add, t[2:]), axis=None)
## Create probability vector
y1 = probas['proba'].values
y1_add = np.zeros((add_number,)) + y1[0]
y1 = np.concatenate((y1_add, y1[1:]), axis=None)
f = interpolate.interp1d(t, y1, kind='cubic', fill_value='extrapolate')
t = np.linspace(t[0], t[-1], Npoints)
y1 = f(t)
y2 = y1*0. + 0.5
y2 = np.ma.masked_greater(y2, 0.5)
y3 = np.ma.masked_greater(y1, 0.5)
ax.plot(t, y1, color=cmap[-1], linewidth=2)
ax.plot(t, y3, color=cmap[10], linewidth=2)
ax.fill_between(t, y1, y2, where=y2 >= y1,
facecolor=cmap[0], alpha=0.4, interpolate=True)
ax.fill_between(t, y1, y2, where=y2 <= y1,
facecolor=cmap[-1], alpha=0.4, interpolate=True)
def plot_background_shading_arrival_RF(axs, probas_, window, shift_window, begin_time, nb_picks=5, axins_inset_vTEC=None):
"""
Make the plot background grey is there is a RF arrival
"""
grouped_detections = probas_.groupby('arrival_class')
for cpt, (group, detection) in enumerate(grouped_detections):
## Only add label for first detection patch to not overload caption
label = ''
if cpt == 0:
label = 'RF arrival'
## Only shift arrival time if this is not the first window
shift_window_ = shift_window
#shift_window_ = 0.5*window/3600.
#if abs(detection.time.min() - begin_time) < window/2.:
# shift_window_ = 0.1*window/3600.
#first_detection = detection.loc[detection.time == detection.time.min(), :].iloc[0]
## Find arrival time
predicted_time = detection.time.min()/3600. + shift_window_
first_detection = detection.loc[detection.proba == detection.proba.max(), :].iloc[0]
if not first_detection['predicted-time'] == -1:
#for idetect, detect in detection.iloc[:nb_picks].iterrows():
#axs[0].axvline(detect['predicted-time']/3600., color='tab:red', alpha=0.5, zorder=15)
predicted_time = detection['predicted-time'].quantile(q=0.5)/3600.
axs[0].axvline(predicted_time, color='darkslategrey', alpha=1., linewidth=2., zorder=10)
axs[1].axvline(predicted_time, color='darkslategrey', alpha=1., linewidth=2., zorder=10)
axs[0].axvspan(predicted_time, \
detection.time.max()/3600. + shift_window_, \
facecolor='grey', alpha=0.18, label=label, zorder=1);
axs[1].axvspan(predicted_time, \
detection.time.max()/3600. + shift_window_, \
facecolor='grey', alpha=0.18, zorder=1);
if not axins_inset_vTEC == None:
axins_inset_vTEC.axvline(predicted_time, color='darkslategrey', linewidth=2., alpha=1., zorder=10)
axins_inset_vTEC.axvspan(predicted_time, \
detection.time.max()/3600. + shift_window_, \
facecolor='grey', alpha=0.18, label=label, zorder=1);
def plot_AN_curves(axs, no_analytical, analytical_detections):
"""
Plot detected arrivals using Elvira's analytical method
"""
t = analytical_detections.time.values/3600.
y1 = np.array(analytical_detections['class'].values, dtype='int')
y2 = y1*0
axs[no_analytical].plot(t, y1, color='tab:pink', linewidth=2.)
axs[no_analytical].fill_between(t, y1, y2, where=y2 <= y1, facecolor='tab:pink', alpha=0.4, interpolate=True)
AN_detected_arrivals = analytical_detections.loc[analytical_detections['class'] == 1, :]
for cpt, (iAN_arrival, AN_arrival) in enumerate(AN_detected_arrivals.iterrows()):
label = '_nolegend_'
if cpt == 0:
label = 'AN arrival'
axs[0].axvline(AN_arrival['time']/3600., color='tab:pink', alpha=0.4, label=label, zorder=10)
axs[no_analytical].text(0.995, 0.98, 'AN', fontsize=10, ha='right', va='top', transform = axs[no_analytical].transAxes)
def plot_STA_LTA_curves(axs, no_stalta, sta_lta_detections, cmap, options):
"""
Plot detected arrivals and characteristic function using classic STA/LTA
"""
colors = ['tab:green', 'tab:orange']
t = sta_lta_detections.time.values/3600.
y1 = sta_lta_detections['proba'].values
y2 = y1*0. + options['STALTA_threshold_in']
grouped_sta_lta_detections = \
sta_lta_detections.loc[sta_lta_detections['arrival_class'] >= 0, :].groupby('arrival_class')
for group, detection in grouped_sta_lta_detections:
itimemin = np.argmin(abs(t - detection.time.min()/3600.))
itimemax = np.argmin(abs(t - detection.time.max()/3600.))
y2[itimemin:itimemax+1] = options['STALTA_threshold_out']
axs[no_stalta].axvspan(detection.time.min()/3600., \
detection.time.max()/3600., \
facecolor='grey', alpha=0.18, zorder=1);
y3 = np.ma.masked_greater(y1, y2)
axs[no_stalta].axhline(options['STALTA_threshold_in'], color='black', alpha=0.5, linestyle=':', label='thresholds')
axs[no_stalta].axhline(options['STALTA_threshold_out'], color='black', alpha=0.5, linestyle=':')
axs[no_stalta].plot(t, y1, color=colors[0], linewidth=2)
axs[no_stalta].plot(t, y3, color=cmap[0], linewidth=2)
axs[no_stalta].fill_between(t, y1, y2, where=y2 >= y1,
facecolor=cmap[0], alpha=0.4, interpolate=True)
axs[no_stalta].fill_between(t, y1, y2, where=y2 <= y1,
facecolor=colors[0], alpha=0.4, interpolate=True)
axs[no_stalta].set_ylabel('Charac.\nfunction')
axs[no_stalta].legend(loc='upper left')
for cpt, (group, detection) in enumerate(grouped_sta_lta_detections):
label = '_nolegend_'
if cpt == 0:
label = 'STA/LTA arrival'
axs[0].axvline(detection['time'].min()/3600., color=colors[0], label=label, linewidth=1., zorder=110)
axs[no_stalta].axvline(detection['time'].min()/3600., color=colors[0], label=label, linewidth=1., zorder=110)
axs[no_stalta].text(0.995, 0.98, 'STA', fontsize=10, ha='right', va='top', transform = axs[no_stalta].transAxes)
def plot_processed_timeseries(event, satellite, station, waveform, probas, probas_, window, options,
transparent_below_threshold=True, true_arrival=-1,
analytical_detections=pd.DataFrame(),
sta_lta_detections=pd.DataFrame(), figsize=(),
nb_picks = 5, add_label='', fsz=15., add_inset=False) -> None:
"""
Plot timeseries and detection probabilities for a given event/satellite/station
"""
begin_time = waveform['time_s'].min()
## Setup figures
#fig, axs = plt.subplots(nrows=2, ncols=1, sharex=True, sharey=False)
if figsize:
fig = plt.figure(figsize=figsize)
else:
fig = plt.figure()
nb_rows = 4
no_analytical = -1
if analytical_detections.size > 0:
nb_rows += 1
no_analytical = nb_rows-3
no_stalta = -1
if sta_lta_detections.size > 0:
nb_rows += 1
no_stalta = nb_rows-3
grid = fig.add_gridspec(nb_rows, 1)
axs = []
axs.append( fig.add_subplot(grid[:3]) )
axs.append( fig.add_subplot(grid[3]) )
if analytical_detections.size > 0:
axs.append( fig.add_subplot(grid[no_analytical+2]) )
if sta_lta_detections.size > 0:
axs.append( fig.add_subplot(grid[no_stalta+2]) )
## Background probabilities colormap
probas_val = np.linspace(0., 1., 100)
cmap_background = generate_colormap(transparent_below_threshold)
cmap_background = [cmap_background(x) for x in np.linspace(0., 1., len(probas_val))]
## Second panel colormap
cmap = generate_colormap(False)
bounds = np.linspace(0, 1, 3)
norm_proba = mcolors.BoundaryNorm(bounds, cmap.N)
cmap = [cmap(x) for x in np.linspace(0., 1., len(probas_val))]
## Plot vTEC time series
times = waveform['time_s'].values/3600.
axs[0].plot(times, waveform.vTEC, color='midnightblue', label='_nolegend_', zorder=100);
axs[0].set_ylabel('vTEC (TECU)', fontsize=fsz)
## Plot inset vTEC
axins_inset_vTEC = None
if add_inset:
axins_inset_vTEC = inset_axes(axs[0], width="20%", height="30%", loc='lower left',
bbox_to_anchor=(0.4, 0.6, 1, 1.),
bbox_transform=axs[0].transAxes, borderpad=0)
axins_inset_vTEC.set_xlabel('')
axins_inset_vTEC.set_ylabel('')
axins_inset_vTEC.set_xticklabels([])
axins_inset_vTEC.set_yticklabels([])
print(waveform, true_arrival)
loc_waveform = waveform.loc[(waveform.UT >= true_arrival/3600.-0.1) & (waveform.UT <= true_arrival/3600.+0.1)]
axins_inset_vTEC.plot(loc_waveform.UT, loc_waveform.vTEC, color='midnightblue', label='_nolegend_', zorder=100)
axins_inset_vTEC.set_xlim([true_arrival/3600.-0.025, true_arrival/3600.+0.025])
axs[0].indicate_inset_zoom(axins_inset_vTEC, edgecolor="black")
mark_inset(axs[0], axins_inset_vTEC, loc1=3, loc2=1, fc="none", ec="0.5")
## Plot background shading in probabilities to flag arrivals
#shift_window = (window - window*(1./options['factor_overlap']))/3600.
#shift_window = 0.7 * window/3600.
shift_window = 1. * window/3600.
if probas_.size > 0:
plot_background_shading_arrival_RF(axs, probas_, window, shift_window, begin_time, nb_picks=nb_picks, axins_inset_vTEC=axins_inset_vTEC)
## Plot true arrival
if true_arrival > -1:
axs[0].axvline(true_arrival/3600., color='tab:red', alpha=0.5, zorder=1000, label='True arrival', linewidth=2.)
if add_inset:
axins_inset_vTEC.axvline(true_arrival/3600., color='tab:red', alpha=0.5, zorder=1000, label='True arrival', linewidth=2.)
## Plot analytical detector
if analytical_detections.size > 0:
plot_AN_curves(axs, no_analytical, analytical_detections)
## Plot STA/LTA detector
if sta_lta_detections.size > 0:
plot_STA_LTA_curves(axs, no_stalta, sta_lta_detections, cmap, options)
## Plot probabilities in second panel
plot_probability_curves(axs[1], probas, window, norm_proba, cmap, shift_window)
axs[1].text(0.995, 0.98, 'RF', fontsize=fsz-2., ha='right', va='top', transform = axs[1].transAxes)
#axs[1].grid()
axs[-1].set_xlabel('Time (UT)', fontsize=fsz)
axs[1].set_ylabel('Detection\nprobability', fontsize=fsz)
for iax, ax in enumerate(axs[1:]):
if iax+1 == no_stalta:
continue
ax.set_ylim([0., 1.])
str_title = event
if '_' in event:
str_title = event.split('_')[0]
axs[0].set_title(str_title, pad=20, fontsize=fsz)
axs[0].text(0.5, 1.02, ' satellite ' + satellite + ' - station '+ station, fontsize=fsz-3., ha='center', va='bottom', transform = axs[0].transAxes)
axs[0].get_xaxis().set_visible(False)
if analytical_detections.size > 0 or sta_lta_detections.size > 0:
axs[1].get_xaxis().set_visible(False)
axs[0].legend()
## Shrink time bounds
## Only shift arrival time if this is not the first window
tproba = shift_window + probas['time'].values/3600
tproba[0] = begin_time/3600.
for ax in axs:
minbounds = tproba[0]
# If there is an arrival that is before the range of RF probabilities, we stretch the xaxis to include it in the plot
#if true_arrival > -1:
# minbounds = min(minbounds, true_arrival/3600.)
ax.set_xlim([minbounds, tproba[-1]])
## Plot scale
ylim = axs[0].get_ylim()
scale_location = [(tproba[0], 0), (tproba[0]+window/3600., 0)]
trans = (axs[0].transData + axs[0].transAxes.inverted()).transform(scale_location)
axs[0].plot(trans[:, 0]-trans[:, 0].max()-0.001, [1.05, 1.05], '|-',
color='black', clip_on=False, transform = axs[0].transAxes)
axs[0].text(trans[:, 0].min(), 1.02, 'window length', fontsize=fsz-2., ha='left', va='bottom', transform = axs[0].transAxes)
## Plot overlap
scale_location = [(tproba[0], 0), (tproba[0] + window/3600.-shift_window, 0)]
trans = (axs[0].transData + axs[0].transAxes.inverted()).transform(scale_location)
axs[0].plot(trans[:, 0]-trans[:, 0].max()-0.001, [1.19, 1.19], '|-',
color='steelblue', clip_on=False, transform = axs[0].transAxes)
axs[0].text(trans[:, 0].min(), 1.16, 'time shift', color='steelblue', fontsize=fsz-2., ha='left', va='bottom', transform = axs[0].transAxes)
## Figure dimensions
fig.subplots_adjust(left=0.1, right=0.95, top=0.85, hspace=0.16, bottom=0.15)
fig.align_ylabels(axs)
"""
axins = inset_axes(axs[0], width="1%", height="100%", loc='lower left', bbox_to_anchor=(1.02, 0., 1, 1.), bbox_transform=axs[0].transAxes, borderpad=0)
axins.tick_params(axis='both', which='both', labelbottom=False, labelleft=False, bottom=False, left=False)
cbar = plt.colorbar(sc, cax=axins, extend='both')
cbar.ax.set_ylabel('Detection probability', rotation=270, labelpad=16)
"""
## Label for paper
if add_label:
axs[0].text(-0.05, 1.05, add_label, ha='right', va='bottom', transform=axs[0].transAxes,
bbox=dict(facecolor='w', edgecolor='w', pad=0.1), fontsize=20., fontweight='bold')
## Save figure
name_figure = str(event) + '_' + str(satellite) + '_' + str(station)
comp_analytic = ''
if analytical_detections.size > 0:
comp_analytic = '_withanal'
fig.savefig(options['DIR_FIGURES'] + 'prediction_detection_'+name_figure+comp_analytic+'.pdf')
plt.close('all')
def compute_arrival_time_multiple_stations(tec_data_param, probas, window, nb_for_class=5, nb_for_end_class=3):
detections = pd.DataFrame()
grouped_data = probas.groupby(['event', 'satellite', 'station'])
for group, proba in grouped_data:
event, satellite, station = group
params = tec_data_param.loc[ (tec_data_param['station'] == station)
& (tec_data_param['satellite'] == satellite)
& (tec_data_param['event'] == event), : ]
true_arrival = -1
if params.size > 0:
true_arrival = params.iloc[0]['arrival-time']
detection = \
compute_arrival_time(proba, window,
nb_for_class=nb_for_class,
nb_for_end_class=nb_for_end_class)
detection['true-arrival-time'] = true_arrival
detections = detections.append( detection )
return detections
def compute_arrival_time(probas, window, nb_for_class=5, nb_for_end_class=3):
"""
Retrieve all wavepackets corresponding to arrivals based on the minimum number of points for an arrival
"""
arrival_time_, proba = -1., -1.
probas_ = probas.copy()
if probas_.shape[0] > 0:
probas_.sort_values(by='time', inplace=True)
probas_ = probas_.loc[probas_['class'] == 1, :]
probas_ = probas_.reset_index(drop=True)
if probas_.size > 0:
dt = np.diff(probas.time).max()
current_class = 0
probas_ = probas_.assign(arrival_class = current_class)
for iproba, proba_onetime in probas_.iloc[1:].iterrows():
gap = proba_onetime['time'] - probas_.iloc[iproba-1]['time']
if (gap > nb_for_end_class*dt+0.1) \
or (gap > dt+0.1 and probas_.loc[(probas_['arrival_class'] == current_class) \
& (probas_.index<iproba), :].shape[0] < nb_for_class):
current_class = probas_.iloc[iproba-1]['arrival_class']+1
probas_.loc[probas_.index>=iproba, 'arrival_class'] = probas_.iloc[iproba-1]['arrival_class']+1;
## get the first element of the largest group
probas_['count_class'] = probas_.groupby('arrival_class').transform('count')['class']
probas_ = probas_.loc[probas_['count_class'] >= nb_for_class, :]
"""
if probas_.size > 0:
arrival_time_ = probas_.iloc[0]['time']
proba = probas_.iloc[0]['proba']
return arrival_time_ + window*0.5, proba
"""
return probas_
def process_timeseries_with_forest(time_end, est, tec_data, tec_data_param, event, satellite, station,
columns_in, options, plot_probas=False, type='features', standard_sampling= 30.,
standard_sampling_for_picker=30., adaptative_sampling=False,
figsize=(), add_label='', determine_elapsed_time=False,
est_picker=None, use_STA_LTA_for_picking=False,
return_all_waveforms_used=False,
nb_picks=5, activate_LTA_STA=False,
time_STA=60., time_LTA=300,
STA_LTA_threshold_in=1.5, STA_LTA_threshold_out=0.1, add_inset=False,
zscore_threshold = 50.) -> dict:
"""
Compute detection probabilities for a given satellite and a given event
"""
class_to_no = {'arrival': 1, 'noise': 0}
if determine_elapsed_time:
time_elapsed = pd.DataFrame()
## Plot proba for an example
#example_index = data.loc[data.index == id, :].iloc[0]
#event, satellite, station = example_index['event'], example_index['satellite'], example_index['station']
waveform = tec_data.loc[ (tec_data['station'] == station) & (tec_data['satellite'] == satellite) & (tec_data['event'] == event), : ]
waveform = waveform.loc[waveform['time_s'] <= time_end, :] # Only selecte waveforms up to the end time requested
sampling = waveform.iloc[0]['sampling']
## Remove outliers
unknown = 'vTEC'
std = waveform[unknown].std()
if std == 0.:
observation = {
'probas': pd.DataFrame(),
'detections': pd.DataFrame()
}
return observation
outliers = waveform.loc[abs(waveform[unknown] - waveform[unknown].mean()/std) > zscore_threshold, :]
waveform = waveform.loc[~waveform.index.isin(outliers.index)]
if waveform.size == 0:
observation = {
'probas': pd.DataFrame(),
'detections': pd.DataFrame()
}
return observation
## Get time windows
times = waveform['time_s'].values[:]
window = read_data.get_window(sampling, options['window'])
factor_overlap = options['factor_overlap']
freq_max = options['freq_max']
if adaptative_sampling:
factor_overlap = window/np.round(sampling)
freq_max = 1./standard_sampling
time_boundaries = np.arange(times[0], times[-1]-window, window/options['factor_overlap'])
iloc_time_boundaries = [np.argmin(abs(time - times)) for time in time_boundaries]
size_subset = np.arange(0., window+sampling, np.round(sampling)).size
## Compute parameters for each time step
probas = pd.DataFrame()
all_waveforms_used = pd.DataFrame()
for i0 in iloc_time_boundaries:
iend = i0 + size_subset - 1
#print('----------------------------')
#print(station, satellite, times[iend]-times[i0], window, (size_subset-1)*sampling, size_subset, sampling)
#print(times[i0:iend+1].size, size_subset, abs(times[iend]-times[i0] - window))
if times[i0:iend+1].size < size_subset or abs(times[iend]-times[i0] - window) > 1.:
print('Removed')
continue
if determine_elapsed_time:
time_start = time.time()
## Extract waveform over the right subset
tr, i0_, iend_ = read_data.pre_process_waveform(times, waveform['vTEC'].values,
i0, iend, window, detrend=True,
bandpass=[options['freq_min'], options['freq_max']],
standard_sampling=standard_sampling)
## Compute time-domain features
type_data = '' # dummy value not used
features = read_data.extract_features_based_on_input_type(tr, type_data, type, options)
if determine_elapsed_time:
time_feature = time.time()
## Only select relevant columns
data_in = features[columns_in].copy()
## Quality check
if not data_in.dropna(axis=1).size == data_in.size:
continue
if options['type_ML'] == 'CNN':
data_in = reshape_dataframe_spectrograms(data_in, ['spectro'])
proba = est.predict_proba(data_in.values)
class_predicted = class_to_no[est.predict(data_in.values)[0]]
loc_dict = {
'time': times[i0],
'proba': proba[0, 0],
'class': class_predicted,
'predicted-time': -1,
}
if determine_elapsed_time:
time_classification = time.time()
if return_all_waveforms_used:
this_waveform = pd.DataFrame(data=[tr.data])
this_waveform['time'] = times[i0]
all_waveforms_used = all_waveforms_used.append( this_waveform )
## If a phase picker is provided, we use it to estimate the arrival time on the current window
if class_predicted == 1:
## Downsample trace for picker if needed
#tr_ = tr.copy()
tr_, i0_, iend_ = read_data.pre_process_waveform(times, waveform['vTEC'].values,
i0, iend, window, detrend=False,
bandpass=[options['freq_min'], options['freq_max']],
standard_sampling=standard_sampling)
read_data.downsample_trace(tr_, standard_sampling_for_picker)
vTEC = np.array([tr_.data])
vTEC /= abs(vTEC).max()
if use_STA_LTA_for_picking:
df = tr.stats.sampling_rate
cft = classic_sta_lta(tr.data, int(time_STA * df), int(time_LTA * df))
detections = detector.recursively_find_wavetrains_STA_LTA(tr.times(), cft, STA_LTA_threshold_in, STA_LTA_threshold_out)
if detections.loc[detections.arrival_class>-1, 'time'].size > 0:
loc_dict['predicted-time'] = times[i0] + detections.loc[detections.arrival_class>-1, 'time'].iloc[0]
elif not est_picker == None:
if activate_LTA_STA:
df = tr_.stats.sampling_rate
cft = classic_sta_lta(tr_.data, int(time_STA * df), int(time_LTA * df))
time_cft_max = tr_.times()[cft.argmax()]
cft_max = cft.max()
cft = np.array([[time_cft_max, cft_max]])
vTEC = np.concatenate((vTEC, cft), axis=1)
loc_dict['predicted-time'] = times[i0] + window*0.5 + est_picker.predict(vTEC)[0]
if determine_elapsed_time:
time_prediction = time.time()
probas = probas.append( [loc_dict] )
if determine_elapsed_time:
detections = compute_arrival_time(probas, window, nb_for_class=options['nb_for_class'],
nb_for_end_class=options['nb_for_end_class'])
time_validation = time.time()
loc_time = {
'time': times[i0],
'feature': time_feature - time_start,
'classification': time_classification - time_feature,
'time-picking': time_prediction - time_classification,
'validation': time_validation - time_prediction
}
time_elapsed = time_elapsed.append( [loc_time] )
## Determine arrival
detections = compute_arrival_time(probas, window, nb_for_class=options['nb_for_class'],
nb_for_end_class=options['nb_for_end_class'])
## Plot time series along with detection probabilities
if plot_probas:
true_arrival = -1
print('Plotting')
if tec_data_param.size > 0:
true_arrival = tec_data_param['arrival-time']
print(f'true_arrival: {true_arrival:.2f}s')
#true_arrival = tec_data_param.epoch
plot_processed_timeseries(event, satellite, station, waveform,
probas, detections, window, options,
true_arrival=true_arrival, figsize=figsize,
add_label=add_label, nb_picks=nb_picks,
add_inset=add_inset)
#from importlib import reload; import train_est; reload(train_est)
#train_est.plot_processed_timeseries(event, satellite, station, waveform, probas, detections, window, options,true_arrival=true_arrival,add_label=add_label, nb_picks=nb_picks,add_inset=add_inset, figsize=(10, 4))
observation = {
#'arrival-time': arrival_time_,
#'proba-max': proba_,
'detections': detections,
'probas': probas
}
if return_all_waveforms_used:
observation['all_waveforms_used'] = all_waveforms_used
if determine_elapsed_time:
return observation, time_elapsed
else:
return observation
def plot_cum_distribution(data_all, label_columns, options):
nb_cols = 4
nb_rows = int(np.ceil(data_all.keys().size / nb_cols))
fig, axs = plt.subplots(nrows=nb_rows, ncols=nb_cols, sharey=True)
for iunknown, unknown in enumerate(data_all.keys()):
i, j = iunknown//nb_cols, np.mod(iunknown, nb_cols)
data_cumul = data_all[unknown].values
sorted_data = np.sort(data_cumul) # Or data.sort(), if data can be modified
bins = np.arange(sorted_data.size)
axs[i, j].step(sorted_data, bins/bins.max())
axs[i, j].grid()
axs[i, j].set_xlabel('')
axs[i, j].set_ylabel('')
axs[i, j].set_xticklabels([])
axs[i, j].set_yticklabels([])
axs[i, j].text(0.01, 0.99, label_columns[unknown], fontsize=10, ha='left', va='top', transform = axs[i, j].transAxes)
axs[i, j].set_xlim([sorted_data.min(), sorted_data.max()])
axs[i, j].set_ylim([0., 1.])
## Remove unused subplots
for iunknown in range(data_all.keys().size, nb_rows*nb_cols):
i, j = iunknown//nb_cols, np.mod(iunknown, nb_cols)
fig.delaxes(axs[i, j])
#axs[-1, 0].set_ylabel('Cum. distribution')
fig.subplots_adjust(top=0.97, bottom=0.03, hspace=0.05)
fig.savefig(options['DIR_FIGURES'] + 'cum_distributions_'+read_data.get_str_options(options)+'.pdf')
def plot_RF_importance(est, input_columns, options):
"""
Plot relative importance (Gini coefficient) of input features
"""
oob_score = est.oob_score_
importances = {}
for name, importance in zip(input_columns, est.feature_importances_):
importances[name] = importance;
std = np.std([tree.feature_importances_ for tree in est.estimators_], axis=0)
importances_tab = est.feature_importances_
indices = np.argsort(importances_tab)[::-1]
keys = np.array(input_columns)[indices]
fig, axs = plt.subplots(nrows=1, ncols=1)#, gridspec_kw=gridspec_kw)
plt.title("Feature importances with accuracy "+ str(round(oob_score,2)))
plt.bar(range(len(input_columns)), importances_tab[indices], color="tab:blue", yerr=std[indices], align="center")
plt.xticks(range(len(input_columns)), keys, rotation='vertical')
plt.xlim([-1, len(input_columns)])
fig.subplots_adjust(bottom=0.25)
fig.savefig(options['DIR_FIGURES'] + 'RF_importance_ML_'+read_data.get_str_options(options)+'.pdf')
plt.close('all')
def build_label_encoder(output):
"""
Encode categorical input features
"""
le = preprocessing.LabelEncoder()
le.fit(output.values)
return le
def CNN_get_binary_class_from_proba(prediction, threshold=0.5):
"""
Return a binary class from a list of predicted probabilited bases on an input threshold
"""
return (prediction > threshold).astype(int)
def get_classes_encoded(est, data_test_in, out_test, type_ML, iclass = 0):
"""
Return the encoded predicted and true output from the test dataset
"""
data_test = data_test_in.copy()
if type_ML == 'CNN':
data_test = reshape_dataframe_spectrograms(data_test, ['spectro'])
out_pred_proba = est.predict_proba(data_test)[:, iclass]
if type_ML == 'CNN':
out_pred_class = CNN_get_binary_class_from_proba(out_pred_proba, threshold=0.5)
else:
out_pred_class = est.predict(data_test)[:]
out_test_class = out_test.copy()
classes = np.unique(out_test.values)
## Only encode outputs if needed, i.e., if RF that uses categorical variables
if not type_ML == 'forest':
le = build_label_encoder(out_test)
out_test_class = le.transform(out_test_class.values[:, iclass])
out_pred_class = le.transform(out_pred_class)
classes = np.arange(0, len(le.classes_))
return out_pred_proba, out_pred_class, out_test_class, classes
def get_fpr_tpr(est, data_test, out_test, type_ML, data, iclass = 0):
"""
Get false and true positive rates
"""
out_pred, _, out_test_, _ = \
get_classes_encoded(est, data_test, out_test, type_ML, iclass = 0)
fpr, tpr, _ = roc_curve(out_test_, out_pred, pos_label=iclass)
return fpr, tpr
def plot_results_optimization(scores, options, nb_cols=2, fsz=15., fsz_labels=13., metrics_to_plot=['R2', 'MAE-training', 'MAE-test', 'MSE-test']):
"""
Plot results (MAR, MSE, R2) of RF optimization
"""
nb_rows = len(metrics_to_plot) // nb_cols
fig, axs = plt.subplots(nrows=nb_rows, ncols=nb_cols, figsize=(10,4))
shortname_to_label = {
'oob_score': 'Out-Of-Bag score',
'noise-precision': 'Precision noise',
'arrival-precision': 'Precision arrival',
'noise-recall': 'Recall noise',
'arrival-recall': 'Recall arrival',
'accuracy': 'Accuracy',
}
irow = 0
icol = -1
alphabet = string.ascii_lowercase
for imetric, metric in enumerate(metrics_to_plot):
icol += 1
if icol == nb_cols:
icol = 0
irow += 1
scores_plot = scores.copy()
scores_plot[shortname_to_label[metric]] = scores[metric]
scores_plot = scores_plot.pivot("max_depth", "nb_trees", shortname_to_label[metric])
sns.heatmap(scores_plot, annot=True, cbar=False, ax=axs[irow, icol], robust=True, cmap='rocket', center=scores[metric].quantile(0.1), zorder=1)
axs[irow, icol].set_title(shortname_to_label[metric])
axs[irow, icol].text(-0.29, 1.05, alphabet[imetric] + ')', ha='right', va='bottom', transform=axs[irow, icol].transAxes,
bbox=dict(facecolor='w', edgecolor='w', pad=0.1), fontsize=15., fontweight='bold')
args = {}
if irow+1 == nb_rows and icol == 0:
axs[irow, icol].set_ylabel('Max. tree depth', fontsize=fsz-2.)
axs[irow, icol].set_xlabel('Nb of trees', fontsize=fsz-2.)
else:
axs[irow, icol].set_yticklabels([])
axs[irow, icol].set_ylabel('')
axs[irow, icol].set_xticklabels([])
axs[irow, icol].set_xlabel('')
ymax = scores_plot.idxmax().idxmax()
ypos = scores_plot.columns.get_loc(ymax)
xmax = scores_plot.idxmax().max()
xpos = scores_plot.index.get_loc(xmax)
y, x = np.where(scores_plot.values == scores_plot.values.max())
ypos = x[0]
xpos = y[0]
print(metric, ymax, ypos, xmax, xpos, scores_plot[ymax].max())
axs[irow, icol].add_patch(Rectangle((ypos, xpos),1,1, fill=False, edgecolor='blue', lw=3, zorder=10))
for irow in range(nb_rows):
for icol in range(nb_cols):
ax = axs[irow, icol]
for tick in ax.xaxis.get_major_ticks():
tick.label.set_fontsize(fsz_labels)
for tick in ax.yaxis.get_major_ticks():
tick.label.set_fontsize(fsz_labels)
fig.subplots_adjust(bottom=0.15, left=0.09, right=0.95)
fig.savefig(options['DIR_FIGURES'] + 'optimization_classifier.pdf')
def optimize_RF(data, data_train, out_train, data_test, out_test, seed, split_type,
l_nb_trees=[1000], l_max_depth=[100],
oob_score=True, bootstrap=True,
class_weight={'noise': 1, 'arrival': 1},
hidden_layer_sizes=(64, 64, 64), learning_rate_init=0.05,
early_stopping=True, max_iter=10000, two_steps=True):
"""
Optimize RF tree depth and nb of tress
"""
scores = pd.DataFrame()
for nb_trees in l_nb_trees:
for max_depth in l_max_depth:
est = create_classifier_and_train(data, data_train, out_train, data_test, out_test,
split_type, seed, type_ML = 'forest',
nb_trees=nb_trees, max_depth=max_depth,
oob_score=oob_score, bootstrap=bootstrap,
SMOTE=True, class_weight=class_weight,
hidden_layer_sizes=hidden_layer_sizes,
learning_rate_init=learning_rate_init,
early_stopping=early_stopping, max_iter=max_iter, two_steps=two_steps)
#preds_training = est.oob_decision_function_[:,0]>=0.5
#preds_test = est.predict(data_test)
report_dict = compute_performance_one_model(est, data)
report = detector.convert_report_to_dataframe(report_dict)
report['nb_trees'] = nb_trees
report['max_depth'] = max_depth
report['oob_score'] = est.oob_score_
scores = scores.append( report )
#from sklearn import model_selection
#kfold = model_selection.KFold(n_splits=5, random_state=7, shuffle=True)
#scoring = 'neg_mean_squared_error'
#results = model_selection.cross_val_score(est, data_picker[input_columns].values, data_picker[output_columns].values[:,0], cv=kfold, scoring=scoring)
#results_ = model_selection.cross_val_score(est, data_test.values, out_test.values[:,0], cv=kfold, scoring=scoring)
return scores
def plot_confusion(est, data_test, out_test, options, type_ML = 'forest', ax=None, cbar=False):
"""
Compute and plot confusion matrix
"""
#fpr, tpr = get_fpr_tpr(est, data_test, out_test, test_MLP, data)
_, out_pred_, out_test_, classes_ = \
get_classes_encoded(est, data_test, out_test, type_ML, iclass = 0)
conf_mat = confusion_matrix(out_test_, out_pred_, labels=classes_, normalize='true')