To receive notifications about scheduled maintenance, please subscribe to the mailing-list gitlab-operations@sympa.ethz.ch. You can subscribe to the mailing-list at https://sympa.ethz.ch

gen_amplitude_triggers.py 7.38 KB
Newer Older
matthmey's avatar
matthmey committed
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
"""
Copyright (c) 2019, Swiss Federal Institute of Technology (ETH Zurich)
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

* Neither the name of the copyright holder nor the names of its
  contributors may be used to endorse or promote products derived from
  this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

"""

import pandas as pd
import numpy as np 
from datetime import datetime,timedelta,timezone
import obspy 
from tqdm import tqdm 
from numba import jit 

# from toolbox import get_data as gd
data_dir = '../data/'
dataset_dir = '../data/dataset/'
tmp_dir = 'tmp/'
print('Warning: If not already done, please run gen_dataset.py and copy_dataset_files.py before running this script.')

@jit(nopython=True)
def amplitude_trigger(x,threshold,post_trigger_length):
    """amplitude trigger for input data.
       triggers if x's absolute value is above `threshold` and appends the index to the trigger_list which will be return.
       After triggering values are ignored for `post_trigger_length` samples.
       For multi-channel it triggers when at least on of the channels triggers.

    
    Arguments:
        x {numpy.array} -- input signal of shape (samples,channels)
    Keyword Arguments:
        threshold {int} -- threshold above which is triggered 
        post_trigger_length {int} -- Time (in samples) after a trigger event when the trigger is bypassed
    
    Returns:
        [numpy.array] -- List of triggers
    """

    x = x
    trigger_list = []
    trigger_cnt = 0
    for i in range(x.shape[0]-post_trigger_length):
        if trigger_cnt == 0:
            if np.any(np.abs(x[i]) > threshold):
                trigger_list.append(i)
                trigger_cnt = post_trigger_length
        else:
            trigger_cnt -= 1
    
    return np.array(trigger_list)


@jit(nopython=True)
def amplitude_trigger_fixed_length(x,threshold,length,post_trigger_length):
    """amplitude trigger for input data.
       triggers if x's absolute value is above `threshold` and appends the index to the trigger_list which will be return.
       After triggering values are ignored for `post_trigger_length` samples.
       For multi-channel it triggers when at least on of the channels triggers.

    
    Arguments:
        x {numpy.array} -- input signal of shape (samples,channels)
    Keyword Arguments:
        threshold {int} -- threshold above which is triggered 
        post_trigger_length {int} -- Time (in samples) after a trigger event when the trigger is bypassed
    
    Returns:
        [numpy.array] -- List of triggers
    """

    x = x
    trigger_list = []
    trigger_cnt = 0
    for i in range(x.shape[0]-length):
        if trigger_cnt == 0:
            if np.any(np.abs(x[i]) > threshold):
                trigger_list.append(i)
                trigger_cnt = post_trigger_length
        else:
            trigger_cnt -= 1
    
    return np.array(trigger_list)

def get_events(name,reload=False,event_length_seconds=12.8):
    print(name)
    ############ LOAD EVENTS ################
    events = pd.read_hdf(data_dir + 'secondary_data/MH36_events.h5', 'events')
    events.index = events.index.tz_localize(timezone.utc)
    events.index                    = pd.to_datetime(events.index,utc=True)
    events['start_time']  = events.index
    events['number_of_events']        = 1
    events = events[['start_time','number_of_events']]
    events['end_time']                = events['start_time'].apply(lambda x: x + timedelta(seconds=event_length_seconds))


    ############ LOAD SET ################
    filename = dataset_dir + 'annotations/%s.csv'%name
    dataset = pd.read_csv(filename)
    dataset['start_time']                  = pd.to_datetime(dataset['start_time'],utc=True)
    dataset['end_time']                    = pd.to_datetime(dataset['end_time'],utc=True)
    dataset['microseismic_labels']         = dataset['microseismic_labels'].map(eval)
    dataset['labels'] = dataset['microseismic_labels']
    dataset['labels'] = dataset['labels'].apply(lambda x: np.unique(x))

    fs = 1000.0       # Hz

    shape = (len(dataset),120001,3)
    if reload:
        X = np.memmap(tmp_dir + 'X_%s.mmap'%name,mode='w+',dtype=np.float32, shape=shape)
    else:
        X = np.memmap(tmp_dir + 'X_%s.mmap'%name,mode='r',dtype=np.float32, shape=shape)


    amp_triggers = []
    stalta_triggers = []
    event_list = []
    for i in tqdm(range(len(dataset))):
    # for i in tqdm(range(100)):
        
        if reload:
            st = obspy.read(dataset_dir + dataset.iloc[i]['microseismic_id'] + '.mseed')
            st.sort(['channel'])
            x = np.array(st).T

            X[i,:] = x
            continue
        else:
            x = X[i]

        post_trigger_seconds = event_length_seconds/4
        triggers = amplitude_trigger_fixed_length(x,1500,event_length_seconds*fs,post_trigger_seconds*fs)
        amp_triggers.append(len(triggers))


        for j in range(triggers.shape[0]):
            start_time = dataset.iloc[i]['start_time'] + timedelta(seconds=triggers[j]/fs)
            event_list.append({'start_time':start_time,
                               'end_time':start_time+timedelta(seconds=event_length_seconds),
                               'microseismic_labels':str(dataset.iloc[i]['microseismic_labels'])})
            

        e = dataset.iloc[i]
        # get only events which are fully in the segment
        stalta_triggers.append(events.loc[e['start_time']:e['end_time'],'number_of_events'].sum())
    
    
    stalta_triggers = np.array(stalta_triggers)
    amp_triggers = np.array(amp_triggers)

    print('Number of amplitude triggers',np.sum(amp_triggers))
    print('Number of STA/LTA triggers',np.sum(stalta_triggers))


    differences = np.abs(amp_triggers-stalta_triggers)
    print(differences.max(),differences.min())

    loc_diff = differences != 0
    print('Differences',loc_diff.sum())


    #### create new pandas dataframe #### 
    events = pd.DataFrame(event_list)
    events = events[['start_time','end_time','microseismic_labels']]
    events.to_csv('tmp/microseismic_%s_events.csv'%name)

    del X       # close memmap file


get_events('train',event_length_seconds=12.8)
get_events('test',event_length_seconds=12.8)


# get_events('train',event_length_seconds=3.2)
# get_events('test',event_length_seconds=3.2)