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

toolbox.py 6.48 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
"""
Script for the paper "Systematic Identification of External Influences in Multi-Year Micro-Seismic Recordings Using Convolutional Neural Networks"

Toolbox for evaluation

Copyright (c) 2018, 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 matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

import os
import yaml
import numpy as np
import pandas as pd 

def threshold(x,thres=0.5):

    # if isinstance(thres,list):


    x = np.copy(x)
    x[x >= thres] = 1
    x[x < thres] = 0
    return x

def evaluate(y_true,y_pred,eval_best=None,return_thresholds=False): 
    from sklearn.metrics import accuracy_score, precision_recall_curve, precision_score, recall_score, roc_auc_score, zero_one_loss
    # from sklearn.metrics import f1_score

    def f1_score(y_true,y_pred):
        y_pred0 = y_pred.astype(np.bool)
        y_test0 = y_true.astype(np.bool)
        mask_fp = np.logical_and(y_pred0, ~y_test0)
        mask_tp = np.logical_and(y_pred0,  y_test0)
        mask_fn = np.logical_and(~y_pred0, y_test0)
        fp = np.sum(mask_fp)
        tp = np.sum(mask_tp)
        fn = np.sum(mask_fn)

        if tp == 0:
            return 0
            
        p = tp / (tp + fp)
        r = tp / (tp + fn)

        return 2*p*r/(p+r)

    scoring = {'acc': accuracy_score,'precision':precision_score,'recall':recall_score,'rocauc':roc_auc_score, 'f1score':f1_score, 'er':zero_one_loss}

    if y_true.ndim == 1:
        y_true_cp = np.copy(y_true).reshape((y_true.shape[0],1))
        y_pred_cp = np.copy(y_pred).reshape((y_true.shape[0],1))
    else:
        y_true_cp = np.copy(y_true)
        y_pred_cp = np.copy(y_pred)

    thresholds = []
    if isinstance(eval_best,str):
        if eval_best not in list(scoring.keys()):
            raise ValueError('eval_best is not a valid scoring function. Valid functions are: %s'%str(scoring.keys()))



        for i in range(y_true_cp.shape[1]):
            best_score = 0
            best_thres = 0
            for thres in np.arange(0,1,0.05):
                y_pt = threshold(y_pred_cp[:,i],thres)
                score = scoring[eval_best](y_true_cp[:,i].astype(np.bool),y_pt.astype(np.bool))
                # print(score,thres)
                if score > best_score:
                    best_score = score
                    best_thres = thres

            # print('Best threshold is',best_thres,'for',i)
            y_pred_cp[:,i] = threshold(y_pred_cp[:,i],best_thres)
            thresholds.append(best_thres)
    else:
        y_pred_cp = threshold(y_pred_cp,0.5)
        for i in range(y_true_cp.shape[1]):
            thresholds.append(0.5)

    eval_results = dict()
    for key in scoring:
        try:
            eval_results[key] = scoring[key](y_true_cp,y_pred_cp)
        except ValueError as e:
            print('An error occured when calculating %s, setting value to zero'%key)
            print(str(e))
            eval_results[key] = 0

    if return_thresholds:
        return eval_results,thresholds
    else:
        return eval_results

def check_overlap(data0,data1,sort_data0=True,sort_data1=True):
    if sort_data0:
        data0.sort_values('start_time',inplace=True)
    if sort_data1:
        data1.sort_values('start_time',inplace=True)

    # data0['start_time'] = pd.to_datetime(data0['start_time'],utc=True)
    # data0['end_time'] = pd.to_datetime(data0['end_time'],utc=True)
    # data1['start_time'] = pd.to_datetime(data1['start_time'],utc=True)
    # data1['end_time'] = pd.to_datetime(data1['end_time'],utc=True)

    data0_start_time = list(pd.to_datetime(data0['start_time'],utc=True))
    data0_end_time = list(pd.to_datetime(data0['end_time'],utc=True))
    data1_start_time = list(pd.to_datetime(data1['start_time'],utc=True))
    data1_end_time = list(pd.to_datetime(data1['end_time'],utc=True))
    
    overlap_indices = []
    # print(data0.head())
    num_overlaps = 0
    start_idx = 0
    for i in range(len(data0)):
        # data0_df = data0.iloc[i]
        data0_start = data0_start_time[i]
        data0_end   = data0_end_time[i]
        # print(data0_df['start_time'])
        label = 'no data'
        ext = []
        for j in range(start_idx,len(data1)):
            # data1_df = data1.iloc[j]
            data1_start = data1_start_time[j]
            data1_end   = data1_end_time[j]
            # print(type(data0_df['end_time']),type(data1_df['start_time']))
            # check if data0_df is completly before data1_df, then all following items will also be non overlapping (sorted list data1)
            cond0 = (data0_end < data1_start)
            if cond0 == True:
                break

            # if data0_df['label'] != data1_df['label']:
            #     continue

            # second condition: data0_df is after data1_df, all items before data1_df can be ignored (sorted list data0)
            cond1 = (data0_start > data1_end)

            if cond1: 
                start_idx = j

            
            if not (cond0 or cond1):
                # overlap
                num_overlaps += 1
                label = 'data'
                overlap_indices.append([int(i),int(j)])

    return overlap_indices