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

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

Loading and preprocessing for the image and micro-seismic dataset 

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

try:
    import permasense.microseismic.data_loaders as ms_loader
    import permasense
except:
    pass


import os, glob
import librosa
import numpy as np
import pandas as pd
import scipy
import pickle

from aednn.datasets.generic_dataset import generic_dataset

from datetime import datetime,timedelta
import time

import obspy 

from tqdm import tqdm 

from PIL import Image as pil_image
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True

import scipy.misc

import warnings

class NoDataException(Exception):
    pass


def load_params(yaml_filename):
    # load parameters from file
    if os.path.isfile(yaml_filename):
        with open(yaml_filename, 'r') as f:
            params = yaml.load(f)
    else:
        raise IOError("Parameter file not found [%s]" % yaml_filename)

    if params == None:
        params = {}


class microseismic_dataset(generic_dataset):

    def __init__(self,tmp_dir,name='microseismic',params=None,restore_from_disk=True,labels=[],transform_type='melspec',verbose=1, **kwargs):
        """Creates a microseismic dataset object. It allows you to load the microseismic data, transforms it into a 2D time-frequency
        representation and stores it as a numpy memmap array
        
        Arguments:
            tmp_dir {string} -- a temporary directory where the memmap files and the object state are stored
        
        Keyword Arguments:
            name {str} -- [description] (default: {'microseismic'})
            params {[type]} -- [description] (default: {None})
            restore_from_disk {bool} -- [description] (default: {True})
            labels {list} -- [description] (default: {[]})
            transform_type {str} -- [description] (default: {'melspec'})
            verbose {int} -- [description] (default: {1})
        
        Raises:
            ValueError -- [description]
        """


        self.labels = labels
        self.transform_type = transform_type
        self.verbose = verbose
        super().__init__(tmp_dir,name,params,restore_from_disk)

    def init_parameters(self,params):
        if isinstance(params,str):
            try:
                params = load_params(params)
            except:
                raise IOError('Error reading file: ' % params)     

        if params is None:
            params = {}
            
       

        self.use_permasense = False

        if 'dataframe' not in params:
            raise KeyError('dataframe: Please provide a data desciptor, either as a pandas dataframe or as a csv file')
        if 'datadir' not in params:
            try:
                self.data_dir = permasense.global_settings.get_setting('permasense_vault_dir')
                self.use_permasense = True
            except:
                raise KeyError('datadir: Please provide base directory of the matterhorn data or install the permasense package')
        else:
            self.data_dir = params['datadir']

        self.print_msg(self.data_dir)

        
        if isinstance(params['dataframe'],str):
            self.dataframe = pd.read_csv(params['dataframe'])
        else:
            self.dataframe = params['dataframe']


        if 'microseismic_labels' not in self.dataframe:
            warnings.warn("Key 'microseismic_labels' found in dataframe. All samples will be created without any label")
            self.dataframe.loc[:,'microseismic_labels'] = "[]" 
        
        self.label_ids = {}
        self.timestamps = None

        self.fs = 1000                       # sampling rate
        # self.spec_length     = 102.4         # length of each spectrogram in seconds
        # self.spec_hopsize    = 51.2          # hopsize of spec frames in seconds
        self.dft_N           = 1024          # DFT length in samples
        self.dft_hopsize     = 512/self.fs   # DFT hopsize in seconds
        # self.dft_hopsize     = 298/self.fs   # DFT hopsize in seconds

        self.num_mels = 64                  # 

        self.fmin = 2                        # lower frequency limit for specgram
        self.fmax = 250                      # upper frequency limit for specgram
        # self.fmax = 100                    # upper frequency limit for specgram



    def mel_transform(self,X=None):
        mel_basis = librosa.filters.mel(self.fs, self.dft_N, n_mels=self.num_mels,fmin=self.fmin,fmax=self.fmax)


        if X is None:
            return mel_basis
        else:
            return np.dot(mel_basis, X)

    def window(self):
        window = scipy.signal.windows.tukey(self.dft_N,0.25)

        return window


    def transform(self,X):
# #            freqs, t0, spec = scipy.signal.spectrogram(X,nperseg=930,fs=self.fs,noverlap=930//2,scaling='spectrum')
#             freqs, t0, spec = scipy.signal.spectrogram(X,nperseg=768,fs=self.fs,noverlap=768//2,scaling='spectrum')
#             spec = librosa.feature.melspectrogram(S = spec,n_mels=self.num_mels,fmin=self.fmin,fmax=self.fmax,sr=self.fs).T
        if self.transform_type == 'melspec':
            X = X - np.mean(X)
            freqs, t0, spec = scipy.signal.spectrogram(X,nfft=self.dft_N,nperseg=self.dft_N,fs=self.fs,noverlap=self.dft_N-self.dft_hopsize*self.fs,scaling='spectrum')
            # spec = mdct.mdct(X,framelength=self.dft_N)

            # using the melspec function for convenience, but we are in the regime which does linear frequency scaling
            spec = librosa.feature.melspectrogram(S = spec,n_mels=self.num_mels,fmin=self.fmin,fmax=self.fmax,sr=self.fs).T  
            # spec = librosa.power_to_db(spec)
            return spec
            # spec = denoise_wavelet(spec, multichannel=True, convert2ycbcr=False)
        elif self.transform_type == 'signal':
            return X
        elif self.transform_type == 'events':
            return X
        elif self.transform_type == 'custom_melspec':
            # X /= 2**23

            def strided_segmentation(a, L, S ):
                nrows = ((a.size-L)//S)+1
                return a[S*np.arange(nrows)[:,None] + np.arange(L)]

            # X = X - np.mean(X)
            X_sig = strided_segmentation(X,self.dft_N,int(self.dft_hopsize*self.fs))
            # window = scipy.signal.windows.hann(self.dft_N)
            # X_sig = X_sig - np.mean(X_sig,axis=1)
            window = self.window()
            X_sig = X_sig * window
            spec = np.fft.rfft(X_sig)
            spec = np.conjugate(spec) * spec
            spec = spec / window.sum()**2
            spec = spec[:,:513]
            spec[..., 1:] *= 2
            spec = spec.T
            spec = spec.real
            # freqs, t0, spec = scipy.signal.spectrogram(X,nfft=self.dft_N,nperseg=self.dft_N,fs=self.fs,noverlap=self.dft_N-self.dft_hopsize*self.fs,scaling='spectrum')
            return self.mel_transform(spec).T
        return None

    def print_msg(self,*args):
        if self.verbose:
            print(args)

    def load_data(self):
        # do some prelimenary verification if the dataset is correct
        # then load each dataset
        
        # dataframe is either a pandas dataframe or a string containing the filename of a csv file
        if isinstance(self.dataframe,str):
            dataset_df = pd.read_csv(self.dataframe)
        else:
            dataset_df = self.dataframe.copy()
        
        dataset_df = dataset_df.drop_duplicates('start_time')                                             # make sure we have each item only once
        dataset_df['microseismic_labels']           = dataset_df['microseismic_labels'].map(eval)         # need to recreate the lists in the labels column
        dataset_df['start_time']                    = pd.to_datetime(dataset_df['start_time'],utc=True)
        dataset_df['end_time']                      = pd.to_datetime(dataset_df['end_time'],utc=True)

        # print(len(dataset_df))

        # calculate num items and storage requirements
        num_items = len(dataset_df)
        self.num_items = num_items

        # the user might preset the labels, otherwise we are going to retrieve them
        if not self.labels:
            labels = []
            for element_labels in dataset_df['microseismic_labels']:
                for label_name in element_labels:
                    if label_name not in labels:
                        labels.append(label_name)

            # If there is no element in the labels list, create a None element otherwise the we wont be able to generate the dataset
            # if there is any other label and none remove none, because "not any label" is none
            if not labels:
                labels= ['none']
            elif len(labels)>1 and 'none' in labels:
                labels.remove('none')
            elif len(labels)>1 and 'None' in labels:
                labels.remove('None')
            
            self.labels = labels

        
        self.label_ids = {}
        for idx,label in enumerate(self.labels):
            self.label_ids[label]=idx
        
        self.print_msg(self.labels)
        self.print_msg(self.label_ids)
        self.num_labels = len(self.labels) 

        ##### microseismic: get storage requirements  #####
        # we should check that each microseismic event has the same length (probably not a clean solution but it works)
        length = [(dataset_df.iloc[i]['end_time']-dataset_df.iloc[i]['start_time']).total_seconds() for i in range(len(dataset_df))]
        length = np.array(length)
        if np.sum(length == length[0]) != num_items:
            self.print_msg('Item(s)', np.where(length != length[0]), 'with value(s)', length[length != length[0]],'is not',length[0])
            self.print_msg(dataset_df[length != length[0]]['start_time'])
            raise RuntimeError("The microseismic data is inconsistent")

        # load an example
        start_time = dataset_df.iloc[0]['start_time']
        end_time = dataset_df.iloc[0]['end_time']
        if self.use_permasense:
            xtmp = ms_loader.get_numpy_array(start_time,end_time,station='MH36',channels=['EHZ'])
        else:
            st = obspy.read(self.data_dir + dataset_df.iloc[0]['microseismic_id'] + '.mseed')
            st.sort(['channel'])
            xtmp = np.array(st).T
            # xtmp = np.load(self.data_dir + dataset_df.iloc[0]['microseismic_id'] + '.npy')


        print('input shape',xtmp[:,0].shape)
        spec = self.transform(xtmp[:,0])
        self.shape = tuple([num_items] + list(spec.shape) + [xtmp.shape[1]])
        self.print_msg(self.shape)

        X = np.memmap(self.tmp_dir + 'X_%s.mmap'%self.name,mode='w+',dtype=self.dtype, shape=self.shape)
        y = np.memmap(self.tmp_dir + 'y_%s.mmap'%self.name,mode='w+',dtype=np.bool_, shape=(self.shape[0],self.num_labels))
        
        # store the dataset so we fetch more information about timestamps later
        self.timestamps = dataset_df

        for i in tqdm(range(len(self.timestamps))):
            timer_start = time.time()
            item = self.timestamps.iloc[i]
            start_time = item.start_time
            end_time = item.end_time

            
            # load microseismic and store in tmp memmap file
            try:
                if self.use_permasense:
                    x = ms_loader.get_numpy_array(start_time,end_time,station='MH36',channels=['EHZ'])
                else:
                    # x0 = np.zeros_like(xtmp)
                    st = obspy.read(self.data_dir + dataset_df.iloc[i]['microseismic_id'] + '.mseed')
                    st.sort(['channel'])
                    x = np.array(st).T
                    # x0[:x.shape[0],:x.shape[1]] = x
                    # x = x0
                    # self.print_msg(start_time,item['microseismic_id'] + '.npy',item['microseismic_id'])
                    # x = np.load(self.data_dir + item['microseismic_id'] + '.npy')
            except:
                # this means the file we wanted to load was corrupted. In general this should not happen. Something is wrong with the dataset
                self.print_msg('Warning file corrupted')
                continue

            for j in range(self.shape[-1]):
                X[i,...,j] = self.transform(x[:,j])

            y[i] = 0
            for label in item['microseismic_labels']:
                if label in self.labels and label != 'none':
                    y[i][self.label_ids[label]] = 1

            # if 'mountaineer' in item['ids']['image']['labels']:
            #     y_ms[i][label_ids['microseismic']['mountaineer']] = 1

            # self.print_msg(i, '/', self.shape[0],start_time,end_time,item['microseismic_labels'], "Time %.4f"%(time.time()-timer_start))



    def update_labels(self,filename, column='microseismic_labels'):
        """ Load a file containing labels with at least (start_time, microseismic_labels)
            Loop through all samples in the dataset and check for each sample if the file contains
            an entry. Then load the label from the label-column given by the column argument.
        """

        label_df = pd.read_csv(filename)
        label_df['start_time']    = pd.to_datetime(label_df['start_time'],utc=True)
        if column not in label_df.columns:
            return

        mask = label_df[column].str.contains("\[\]")             # find all empty lists (have not been annotated)
        label_df = label_df[~mask]                             # get all annotated rows
        label_df[column]  = label_df[column].map(eval)         # need to recreate the lists in the labels column
        label_df.set_index('start_time',inplace=True)

        y = np.memmap(self.tmp_dir + 'y_%s.mmap'%self.name,mode='r+',dtype=np.bool_, shape=(self.shape[0],self.num_labels))

        for i in range(self.shape[0]):
            item = self.timestamps.iloc[i]
            start_time = item['start_time']
            if start_time in label_df.index:
                y[i] = 0
                self.timestamps.at[self.timestamps.index[i],'microseismic_labels'] = []
                # print(start_time)
                for label in label_df.loc[start_time,column]:
                    if label in self.label_ids and label != 'none' and label != 'tba':      # tba = to be annotated -> will be ignored
                        y[i][self.label_ids[label]] = 1
                        self.timestamps.loc[self.timestamps.index[i],'microseismic_labels'].append(label)
                # print(self.timestamps.loc[self.timestamps.index[i],'microseismic_labels'])


                    

class image_dataset(generic_dataset):

    def __init__(self,tmp_dir,name='image',params=None,restore_from_disk=True,dtype=np.uint8,labels=[],crop_image=False,verbose=1, **kwargs):
        self.labels = labels
        self.crop_image = crop_image  # crop the image into multiple smaller fractions
        self.verbose = verbose
        super().__init__(tmp_dir,name,params,restore_from_disk,dtype)

    def init_parameters(self,params):
        if isinstance(params,str):
            try:
                params = load_params(params)
            except:
                raise IOError('Error reading file: ' % params)


        if params is None:
            params = {}

        if 'dataframe' not in params:
            raise KeyError('dataframe: Please provide a data desciptor, either as a pandas dataframe or as a csv file')
        if 'datadir' not in params:
            try:
                params['datadir'] = permasense.global_settings.get_setting('permasense_vault_dir')
            except:
                raise KeyError('datadir: Please provide base directory of the matterhorn data')

        self.data_dir = params['datadir']



        if 'bounding_boxes' in params:
            if isinstance(params['bounding_boxes'],str):
                self.bounding_boxes = pd.read_csv(params['bounding_boxes'])
            else:
                self.bounding_boxes = params['bounding_boxes']
            self.bounding_boxes['start_time']    = pd.to_datetime(self.bounding_boxes['start_time'],utc=True)
            self.bounding_boxes['start_time']    = pd.to_datetime(self.bounding_boxes['start_time'],utc=True)
        else:
            self.bounding_boxes = None       

        if isinstance(params['dataframe'],str):
            self.dataframe = pd.read_csv(params['dataframe'])
        else:
            self.dataframe = params['dataframe']

        if 'image_labels' not in self.dataframe:
            warnings.warn("Key 'image_labels' found in dataframe. All samples will be created without any label")
            self.dataframe.loc[:,'image_labels'] = "[]" 

        # self.dataframe = self.dataframe[:128]

        self.divy = 3            # no. of vertical subdivisions 
        self.divx = 2            # no. of horizontal subdivisions 

        self.label_ids = {}
        self.timestamps = None


        self.use_diff = False

    def print_msg(self,*args):
        if self.verbose:
            print(args)

    def load_image_patches(self,filename):
        from keras.preprocessing import image

        # we do not scale the image to the CNN input size, but
        # we subdivide the image into patches. each patch has a higher resolution
        # and our network can work on small input sizes
        # but now we need to label each patch individually
        self.img_width = img_width = 1424
        self.img_height = img_height =  2144
        img_path = filename

        Nx = 224
        Ny = 224
        Nd = 3

        # @profile
        # loads the image, rotates it if it is horizontal and resizes it
        def load_mh_img(path,target_size,grayscale=False):
            img = pil_image.open(path) 
            if grayscale:
                if img.mode != 'L':
                    img = img.convert('L')
            else:
                if img.mode != 'RGB':
                    img = img.convert('RGB')
            if img.size[0] > img.size[1]:
                img = img.rotate(90,expand=True)
            if target_size:
                wh_tuple = (target_size[0], target_size[1])
                if img.size != wh_tuple:
                    img = img.resize(wh_tuple)
            return img 

        img = load_mh_img(img_path, target_size=(self.divx*Nx, self.divy*Ny),grayscale=Nd==1)


        x = np.asarray(img)     # asarray changes to (height,width,channels) == (rows,cols,channels)
        x = np.rot90(x)         # rotate to get back the image coordinate system (width,height,channels)
                                # if we want to plot it with scipy or matplotlib we need to rotate it back

        if self.use_diff:
            x = denoise_wavelet(x, multichannel=True, convert2ycbcr=True) * 255      

#        print(x.shape)
        if self.crop_image:
            # image cropping
            x_new = np.zeros((self.divy*self.divx,Nx,Ny,Nd))
            for j in range(self.divy):
                for i in range(self.divx):
                    # idx = j+i*self.divy
                    idx = i+j*self.divx
                    ii = self.divx - i - 1
                    jj = self.divy - j - 1
                    jj = j
                    x_new[idx,:,:,:] = x[ii*Nx:(ii+1)*Nx ,jj*Ny:(jj+1)*Ny]

            x = x_new
        else:
            x = x.reshape((1,x.shape[0],x.shape[1],x.shape[2]))
            
        return x

    def load_data(self):
        # do some prelimenary verification if the dataset is correct
        # then load each dataset
        
        if isinstance(self.dataframe,str):
            dataset_df = pd.read_csv(self.dataframe)
        else:
            dataset_df = self.dataframe.copy()

        dataset_df = dataset_df.drop_duplicates('start_time')                      # make sure we have each item only once
        dataset_df['image_labels']  = dataset_df['image_labels'].map(eval)         # need to recreate the lists in the labels column
        dataset_df['start_time']    = pd.to_datetime(dataset_df['start_time'],utc=True)
        dataset_df['end_time']      = pd.to_datetime(dataset_df['end_time'],utc=True)

        # we should check that each event has the same length
        length = [(dataset_df.iloc[i]['end_time']-dataset_df.iloc[i]['start_time']).total_seconds() for i in range(len(dataset_df))]
        length = np.array(length)
        self.print_msg(length[0])

        # TODO: change this to a better comparision for desired length. don't make it hardcoded
        dataset_df = dataset_df.iloc[length == length[0]]
        # assert np.sum(length == length[0]) == num_items, "The microseismic data is inconsistent"
        # calculate num items and storage requirements
        num_items = len(dataset_df)
        self.num_items = num_items

        # the user might preset the labels, otherwise we are going to retrieve them
        if not self.labels:
            labels = []
            for element_labels in dataset_df['image_labels']:
                for label_name in element_labels:
                    if label_name not in labels:
                        labels.append(label_name)

            # If there is no element in the labels list, create a None element otherwise we wont be able to generate the dataset
            # if there is any other label remove none, because "not any label" is none
            if not labels:
                labels= ['none']
            elif len(labels)>1 and 'none' in labels:
                labels.remove('none')
            elif len(labels)>1 and 'None' in labels:
                labels.remove('None')

            self.labels = labels
        
        label_ids = {}
        for idx,label in enumerate(self.labels):
            label_ids[label]=idx
        
        self.print_msg(self.labels)
        self.print_msg(label_ids)
        self.label_ids = label_ids
        self.num_labels = len(self.labels)


        ##### IMAGE: get storage requirements  #####
        # load an example image and infer how much space we need to allocate
        xtmp = self.load_image_patches(self.data_dir + dataset_df.iloc[0]['image_id'])

        if self.crop_image:
            self.shape = (num_items*self.divy*self.divx,xtmp.shape[1],xtmp.shape[2],xtmp.shape[3])
        else:
            self.shape = (num_items,xtmp.shape[1],xtmp.shape[2],xtmp.shape[3])

        # allocate memmap file
        X = np.memmap(self.tmp_dir + 'X_%s.mmap'%self.name,mode='w+',dtype=self.dtype, shape=self.shape)
        y = np.memmap(self.tmp_dir + 'y_%s.mmap'%self.name,mode='w+',dtype=np.bool_, shape=(self.shape[0],self.num_labels))

        # store the dataset so we fetch more information about timestamps later
        self.timestamps = dataset_df


        for i in tqdm(range(len(self.timestamps))):
            item = self.timestamps.iloc[i]
            start_time = item.start_time
            end_time = item.end_time

            # self.print_msg(i, '/', len(self.timestamps), start_time,end_time,item['image_labels'])
            # self.print_msg(item['image_id'])
            if not os.path.isfile(self.data_dir + item['image_id']):
                continue
            # load image and store in tmp memmap file
            x = self.load_image_patches(self.data_dir + item['image_id'])

            if self.use_diff:
                x_prev = self.load_image_patches(self.data_dir + item['image_previous'])
                try:
                    x_next = self.load_image_patches(self.data_dir + item['image_next'])
                except:
                    x_next = np.zeros(x_prev.shape)

            if self.use_diff:
                # The following calculates the difference from the current image to the next and the difference from the current image to the previous image
                # These two new images reflect the changes in our current image. We can create a mask by selecting the minimum of each file the *new* image sections
                # in our current image are reflected in changes from and to the current image.
                diff = np.minimum(np.abs(x - x_prev), np.abs(x - x_next))
                # diff = 0.2989 * diff[:,:,0] + 0.5870 * diff[:,:,1] + 0.1140 * diff[:,:,2]

                use_max = True
                if use_max:
                    # get the per pixel maximum from each color channel 
                    diff0 = np.maximum(diff[...,0],diff[...,1])
                    diff = np.maximum(diff0,diff[...,2])
                else:
                    diff = np.sum(diff,axis=-1)


                # add gaussian blur to the image
                # diff = scipy.ndimage.filters.gaussian_filter(diff, sigma=5)

                kernel = np.ones((3,3))
                o=0.4
                kernel = [[o,o,o],[o,1,o],[o,o,o]]
                diff = scipy.signal.convolve2d(diff[:,:],kernel,mode='same')
                

                # # normalize it
                # diff_max = np.max(diff)
                # diff = diff/diff_max



                diff = diff.reshape((self.shape[1],self.shape[2],1))

                if np.isnan(np.sum(diff)):
                    self.print_msg('Warning: Errors while calculating the image')
                    diff = np.ones(diff.shape)

                # print(diff.shape)
                # print(np.concatenate((x,diff),axis=2).shape)
                x = np.concatenate((x,diff),axis=-1)

            if np.isnan(np.sum(x)):
                warnings.warn('Something went wrong loading the image. Setting image to a black image')
                x = np.zeros(x.shape)



            y0 = np.zeros((x.shape[0],self.num_labels))
            for label in item['image_labels']:
                if label in self.labels and label != 'none' and label != 'tba':      # tba = to be annotated -> will be ignored
                    if not self.crop_image:
                        sample_mask = np.ones((x.shape[0],),dtype=np.bool)
                    else:
                        if 'image_has_bb' in item:
                            has_bb = item['image_has_bb']
                        else:
                            has_bb = False
                        sample_mask = self.get_sample_mask(item['start_time'],label,has_bb)
                    y0[sample_mask,label_ids[label]] = 1

            L = x.shape[0]

            X[i*L:(i+1)*L] = x
            y[i*L:(i+1)*L] = y0
        
    def get_sample_mask(self,start_time,label,has_bb=False):
        if not has_bb or self.bounding_boxes is None:
            return np.ones((self.divx*self.divy,),dtype=np.bool)

        sample_mask = np.zeros((self.divx*self.divy,),dtype=np.bool)
        
        # print(start_time)
        bbs = self.bounding_boxes
        bbs = bbs[bbs['start_time']==start_time]
        bbs = bbs[bbs['label']==label]
        if bbs.empty:
            return np.ones((self.divx*self.divy,),dtype=np.bool)
        for i in range(self.divx):
            for j in range(self.divy):
                idx = i+j*self.divx
                x_min = i * self.img_width/self.divx + 1
                y_min = j * self.img_height/self.divy + 1
                x_max = (i+1) * self.img_width/self.divx
                y_max = (j+1) * self.img_height/self.divy

                for bidx in range(len(bbs)):
                    bb = bbs.iloc[bidx]
                    x_min_bb, x_max_bb = int(bb['x_min']), int(bb['x_max'])
                    y_min_bb, y_max_bb = int(bb['y_min']), int(bb['y_max'])
                    # check if they intersect
                    if not (x_min_bb > x_max or
                        x_max_bb < x_min or
                        y_min_bb > y_max or
                        y_max_bb < y_min):
                        # print(x_min,x_max,y_min,y_max)
                        # print(x_min_bb,x_max_bb,y_min_bb,y_max_bb)
                        # print(idx)
                        sample_mask[idx] = True
        return sample_mask

    def update_labels(self,filename, column='image_labels'):
        """ Load a file containing labels with at least (start_time, image_labels)
            Loop through all samples in the dataset and check for each sample if the file contains
            an entry. Then load the label from the label-column given by the column argument.
        """

        label_df = pd.read_csv(filename)
        label_df['start_time']    = pd.to_datetime(label_df['start_time'],utc=True)
        if column not in label_df.columns:
            return

        mask = label_df[column].str.contains("\[\]")             # find all empty lists (have not been annotated)
        label_df = label_df[~mask]                             # get all annotated rows
        label_df[column]  = label_df[column].map(eval)         # need to recreate the lists in the labels column
        label_df.set_index('start_time',inplace=True)

        y = np.memmap(self.tmp_dir + 'y_%s.mmap'%self.name,mode='r+',dtype=np.bool_, shape=(self.shape[0],self.num_labels))

        for i in range(self.shape[0]):
            item = self.timestamps.iloc[i]
            start_time = item['start_time']

            if start_time in label_df.index:
                # print(start_time)
                y[i] = 0
                for label in label_df.loc[start_time,column]:
                    if label in self.label_ids and label != 'none' and label != 'tba':      # tba = to be annotated -> will be ignored
                        y[i][self.label_ids[label]] = 1
                    

class matterhorn_dataset(generic_dataset):

    def __init__(self,tmp_dir,path=None,name='matterhorn',params=None,restore_from_disk=True, labels = None,**kwargs):
        self.restore_from_disk = restore_from_disk
        self.path = path
        self.labels = labels
        super().__init__(tmp_dir,name,params,restore_from_disk)

    def init_parameters(self,params):
        if isinstance(params,str):
            try:
                params = load_params(params)
            except:
                raise IOError('Error reading file: ' % params)

        if params is None:
            params = {}
            # params['dataframe'] = self.datadir + 'annotations/annotated_segments.csv'
            assert self.path != None, 'Please provide either path to the dataset or a params dict with a *datadir* entry containing the path '
            params['datadir']   = self.path


        if 'dataframe' not in params:
            params['dataframe'] = params['datadir'] + 'annotations/train_only.csv'

        if self.labels is not None:
            labels_microseismic = self.labels[0]
            labels_image = self.labels[1]

        if isinstance(params['dataframe'],str):
            self.dataframe = pd.read_csv(params['dataframe'])
        else:
            self.dataframe = params['dataframe']
            
        # shuffle rows
        # self.dataframe = self.dataframe.sample(frac=1).reset_index(drop=True)
        # self.dataframe = self.dataframe[:64]
        params['dataframe'] = self.dataframe

        self.ratio = 0.75

        self.microseismic_dataset = microseismic_dataset(self.tmp_dir,name='%s_microseismic'%self.name,params=params,restore_from_disk=self.restore_from_disk,labels=labels_microseismic)
        self.image_dataset = image_dataset(self.tmp_dir,name='%s_image'%self.name,params=params,restore_from_disk=self.restore_from_disk,labels=labels_image)
        print('============================================================================')
        if not self.microseismic_dataset.data_loaded or not self.image_dataset.data_loaded:
        # if not self.image_dataset.data_loaded:
            print('Reloading matterhorn data')
            self.microseismic_dataset = microseismic_dataset(self.tmp_dir,name='%s_microseismic'%self.name,params=params,restore_from_disk=False,labels=labels_microseismic)
            self.image_dataset = image_dataset(self.tmp_dir,name='%s_image'%self.name,params=params,restore_from_disk=False,labels=labels_image)


    def get_timestamps(self,dataset='all'):
        ratio = self.ratio
        if dataset == 'train':
            train_idx = int(self.shape[0] * ratio)
            return  self.image_dataset.timestamps[:train_idx]
        elif dataset == 'test':
            train_idx = int(self.shape[0] * ratio)
            return self.image_dataset.timestamps[train_idx:]
        elif dataset == 'all':
            return self.image_dataset.timestamps

    def get_data(self,dataset='all',reload=False):
        if not self.microseismic_dataset.data_loaded or not self.image_dataset.data_loaded or reload:
            self.microseismic_dataset.dataframe = self.dataframe
            self.image_dataset.dataframe = self.dataframe

        X_ms,y_ms   = self.microseismic_dataset.get_data('all',reload)
        X_img,y_img = self.image_dataset.get_data('all',reload)

        assert self.microseismic_dataset.shape[0] == self.image_dataset.shape[0], 'error inconsistent dataset'

        # print(self.microseismic_dataset.shape,self.image_dataset.shape)

        ratio = self.ratio
        if dataset in ['train_ms','test_ms','all_ms']:
            self.shape          = self.microseismic_dataset.shape
            self.labels         = self.microseismic_dataset.labels
            self.label_ids      = self.microseismic_dataset.label_ids
            self.num_labels     = self.microseismic_dataset.num_labels
            if dataset == 'train_ms':
                train_idx = int(self.shape[0] * ratio)
                return  X_ms[:train_idx], y_ms[:train_idx]
            elif dataset == 'test_ms':
                train_idx = int(self.shape[0] * ratio)
                return X_ms[train_idx:], y_ms[train_idx:]
            elif dataset == 'all_ms':
                return X_ms, y_ms
        elif dataset in ['train_img','test_img','all_img']:
            self.shape          = self.image_dataset.shape
            self.labels         = self.image_dataset.labels
            self.label_ids      = self.image_dataset.label_ids
            self.num_labels     = self.image_dataset.num_labels
            if dataset == 'train_img':
                train_idx = int(self.shape[0] * ratio)
                return  X_img[:train_idx], y_img[:train_idx]
            elif dataset == 'test_img':
                train_idx = int(self.shape[0] * ratio)
                return X_img[train_idx:], y_img[train_idx:]
            elif dataset == 'all_img':
                return X_img, y_img
        elif dataset == 'all':
            labels = self.microseismic_dataset.labels + self.image_dataset.labels
            num_samples = y_ms.shape[0]
            self.labels = np.unique(labels)
            self.label_ids = {}
            for idx,label in enumerate(self.labels):
                self.label_ids[label]=idx

            y = np.zeros((num_samples,len(self.labels)))
            for i, label in enumerate(self.labels):
                if label in self.microseismic_dataset.labels:
                    y[:,i] = np.logical_or(y[:,i],y_ms[:,self.microseismic_dataset.label_ids[label]])
                if label in self.image_dataset.labels:
                    y[:,i] = np.logical_or(y[:,i],y_img[:,self.image_dataset.label_ids[label]])
            return X_ms, X_img, y
        else:
            assert False, "Error: Unknown dataset type. Possible candidates are: train_ms, test_ms, train_img, all_ms, test_img, all_img"