-
Notifications
You must be signed in to change notification settings - Fork 86
/
match_filter.py
4065 lines (3590 loc) · 158 KB
/
match_filter.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/python
"""
Functions for network matched-filter detection of seismic data.
Designed to cross-correlate templates generated by template_gen function
with data and output the detections. The central component of this is
the match_template function from the openCV image processing package. This
is a highly optimized and accurate normalized cross-correlation routine.
The details of this code can be found here: `OpenCV object detection
<http://docs.opencv.org/2.4/modules/imgproc/doc/object_detection.html>`_
:copyright:
EQcorrscan developers.
:license:
GNU Lesser General Public License, Version 3
(https://www.gnu.org/copyleft/lesser.html)
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
import cv2
import warnings
import ast
import os
import time
import copy
import getpass
import re
import tarfile
import shutil
import tempfile
import glob
from multiprocessing import Pool, cpu_count
from collections import Counter
from obspy import Trace, Catalog, UTCDateTime, Stream, read, read_events
from obspy.core.event import Event, Pick, CreationInfo, ResourceIdentifier
from obspy.core.event import Comment, WaveformStreamID
from eqcorrscan.utils.timer import Timer
from eqcorrscan.utils.findpeaks import find_peaks2_short, decluster
from eqcorrscan.utils.plotting import cumulative_detections
from eqcorrscan.utils.pre_processing import dayproc, shortproc
from eqcorrscan.utils.catalog_utils import _get_origin
from eqcorrscan.core import template_gen
from eqcorrscan.core.lag_calc import lag_calc
class MatchFilterError(Exception):
"""
Default error for match-filter errors.
"""
def __init__(self, value):
"""
Raise error.
.. rubric:: Example
>>> MatchFilterError('This raises an error')
This raises an error
"""
self.value = value
def __repr__(self):
"""
Print the value of the error.
.. rubric:: Example
>>> print(MatchFilterError('Error').__repr__())
Error
"""
return self.value
def __str__(self):
"""
Print the error in a pretty way.
.. rubric:: Example
>>> print(MatchFilterError('Error'))
Error
"""
return self.value
class Party(object):
"""
Container for multiple Family objects.
"""
def __init__(self, families=None):
"""Instantiate the Party object."""
self.families = []
if isinstance(families, Family):
families = [families]
if families:
self.families.extend(families)
def __repr__(self):
"""
Print short info about the Party.
:return: str
.. rubric:: Example
>>> print(Party())
Party of 0 Families.
"""
print_str = ('Party of %s Families.' % len(self.families))
return print_str
def __iadd__(self, other):
"""
Method for in-place addition '+='. Uses the Party.__add__() method.
:type other: `Party`
:param other: Another party to merge with the current family.
:return: Works in place on self.
.. rubric:: Example
>>> party_a = Party(families=[Family(template=Template(name='a'),
... detections=[])])
>>> party_b = Party(families=[Family(template=Template(name='b'),
... detections=[])])
>>> party_a += party_b
>>> print(party_a)
Party of 2 Families.
"""
return self.__add__(other)
def __add__(self, other):
"""
Method for addition '+'.
:type other: `Party` or `Family`
:param other: Another party to merge with the current family.
:return: Works in place on self.
.. Note:: Works in place on party, will alter this original party.
.. rubric:: Example
Addition of two parties together:
>>> party_a = Party(families=[Family(template=Template(name='a'),
... detections=[])])
>>> party_b = Party(families=[Family(template=Template(name='b'),
... detections=[])])
>>> party_c = party_a + party_b
>>> print(party_c)
Party of 2 Families.
Addition of a family to a party:
>>> party_a = Party(families=[Family(template=Template(name='a'),
... detections=[])])
>>> family_b = Family(template=Template(name='b'), detections=[])
>>> party_c = party_a + family_b
>>> print(party_c)
Party of 2 Families.
Addition of a party with some families using the same templates:
>>> party_a = Party(families=[Family(template=Template(name='a'),
... detections=[])])
>>> party_b = Party(families=[Family(template=Template(name='a'),
... detections=[])])
>>> party_c = party_a + party_b
>>> print(party_c)
Party of 1 Families.
Addition of non Family or Party objects is not allows:
>>> party_a = Party(families=[Family(template=Template(name='a'))])
>>> misc = 1.0
>>> party_c = party_a + misc # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
NotImplementedError: Ambiguous add, only allowed Party or Family \
additions
"""
if isinstance(other, Family):
families = [other]
elif isinstance(other, Party):
families = other.families
else:
raise NotImplementedError(
'Ambiguous add, only allowed Party or Family additions.')
added = False
for oth_fam in families:
for fam in self.families:
if fam.template == oth_fam.template:
fam += oth_fam
added = True
if not added:
self.families.append(oth_fam)
return self
def __eq__(self, other):
"""
Equality testing, rich comparison '=='.
:param other: Another object.
:return: bool
.. rubric:: Example
Compare equal Parties:
>>> party_a = Party(families=[Family(template=Template(name='a'))])
>>> party_b = Party(families=[Family(template=Template(name='a'))])
>>> party_a == party_b
True
Compare Parties with different templates:
>>> party_a = Party(families=[Family(template=Template(name='a'))])
>>> party_b = Party(families=[Family(template=Template(name='b'))])
>>> party_a == party_b
False
Compare a Party with a Family:
>>> party = Party(families=[Family(template=Template(name='a'))])
>>> family = Family(template=Template(name='a'))
>>> party == family
False
"""
if not isinstance(other, Party):
return False
for family, oth_fam in zip(self.sort().families,
other.sort().families):
if family != oth_fam:
return False
else:
return True
def __ne__(self, other):
"""
Rich comparison operator '!='.
:param other: other object
:return: bool
.. rubric:: Example
Compare two equal Parties:
>>> party_a = Party(families=[Family(template=Template(name='a'))])
>>> party_b = Party(families=[Family(template=Template(name='a'))])
>>> party_a != party_b
False
"""
return not self.__eq__(other)
def __getitem__(self, index):
"""
Get families from the Party. Can accept either an index or slice.
:param index: Family number or slice.
:return: Party (if a slice is given) or a single Family
.. rubric:: Example
Extract a single family:
>>> party = Party(families=[Family(template=Template(name='a')),
... Family(template=Template(name='b')),
... Family(template=Template(name='c'))])
>>> party[1]
Family of 0 detections from template b
Extract a list of families by giving a slice:
>>> party = Party(families=[Family(template=Template(name='a')),
... Family(template=Template(name='b')),
... Family(template=Template(name='c'))])
>>> party[1:]
Party of 2 Families.
"""
if isinstance(index, slice):
return self.__class__(families=self.families.__getitem__(index))
else:
return self.families.__getitem__(index)
def __len__(self):
"""
Get total number of detections in Party.
:return: length, int
.. rubric:: Example
>>> party = Party(families=[Family(template=Template(name='a')),
... Family(template=Template(name='b'))])
>>> len(party)
0
"""
length = 0
for family in self.families:
length += len(family)
return length
def sort(self):
"""
Sort the families by template name.
.. rubric:: Example
>>> party = Party(families=[Family(template=Template(name='b')),
... Family(template=Template(name='a'))])
>>> party[0]
Family of 0 detections from template b
>>> party.sort()[0]
Family of 0 detections from template a
"""
self.families.sort(key=lambda x: x.template.name)
return self
def plot(self, plot_grouped=False):
"""
Plot the cumulative detections in time.
:type plot_grouped: bool
:param plot_grouped:
Whether to plot all families together (plot_grouped=True), or each
as a separate line.
.. Example::
>>> Party().read().plot(plot_grouped=True) # doctest: +SKIP
.. plot::
from eqcorrscan.core.match_filter import Party
Party().read().plot(plot_grouped=True)
"""
all_dets = []
for fam in self.families:
all_dets.extend(fam.detections)
cumulative_detections(detections=all_dets, plot_grouped=plot_grouped)
def rethreshold(self, new_threshold, new_threshold_type='MAD'):
"""
Remove detections from the Party that are below a new threshold.
Note, threshold can only be set higher.
.. Warning::
Works in place on Party.
:type new_threshold: float
:param new_threshold: New threshold level
:type new_threshold_type: str
:param new_threshold_type: Either 'MAD', 'absolute' or 'av_chan_corr'
.. rubric:: Example
Using the MAD threshold on detections made using the MAD threshold:
>>> party = Party().read()
>>> len(party)
4
>>> party = party.rethreshold(10.0)
>>> len(party)
4
>>> # Note that all detections are self detections
Using the absolute thresholding method on the same Party:
>>> party = Party().read().rethreshold(6.0, 'absolute')
>>> len(party)
1
Using the av_chan_corr method on the same Party:
>>> party = Party().read().rethreshold(0.9, 'av_chan_corr')
>>> len(party)
4
"""
for family in self.families:
for d in family.detections:
if new_threshold_type == 'MAD' and d.threshold_type == 'MAD':
new_thresh = (d.threshold /
d.threshold_input) * new_threshold
elif new_threshold_type == 'MAD' and d.threshold_type != 'MAD':
raise MatchFilterError(
'Cannot recalculate MAD level, '
'use another threshold type')
elif new_threshold_type == 'absolute':
new_thresh = new_threshold
elif new_threshold_type == 'av_chan_corr':
new_thresh = new_threshold * d.no_chans
else:
raise MatchFilterError(
'new_threshold_type %s is not recognised' %
str(new_threshold_type))
if d.detect_val < new_thresh:
family.detections.remove(d)
family.catalog = Catalog([d.event for d in family])
return self
def decluster(self, trig_int, timing='detect'):
"""
De-cluster a Party of detections by enforcing a detection separation.
De-clustering occurs between events detected by different (or the same)
templates. If multiple detections occur within trig_int then the
detection with the highest average single-channel correlation
(calculated as the cross-correlation sum / number of channels used in
detection) will be maintained.
:type trig_int: float
:param trig_int: Minimum detection separation in seconds.
:type timing: str
:param timing:
Either 'detect' or 'origin' to decluster based on either the
detection time or the origin time.
.. Warning::
Works in place on object, if you need to keep the original safe
then run this on a copy of the object!
.. rubric:: Example
>>> party = Party().read()
>>> len(party)
4
>>> declustered = party.decluster(20)
>>> len(party)
3
"""
all_detections = []
for fam in self.families:
all_detections.extend(fam.detections)
if timing == 'detect':
detect_info = [(d.detect_time, d.detect_val)
for d in all_detections]
elif timing == 'origin':
detect_info = [(_get_origin(d.event).time, d.detect_val)
for d in all_detections]
else:
raise MatchFilterError('timing is not detect or origin')
min_det = sorted([d[0] for d in detect_info])[0]
detect_info = [(d[1], _total_microsec(d[0].datetime, min_det.datetime))
for d in detect_info]
peaks_out, inds_out = decluster(
peaks=detect_info, trig_int=trig_int * 10**6, return_ind=True)
# Trig_int must be converted from seconds to micro-seconds
declustered_detections = [all_detections[ind] for ind in inds_out]
# Convert this list into families
template_names = list(set([d.template_name
for d in declustered_detections]))
new_families = []
for template_name in template_names:
template = [fam.template for fam in self.families
if fam.template.name == template_name][0]
new_families.append(Family(
template=template,
detections=[d for d in declustered_detections
if d.template_name == template_name],
catalog=Catalog([d.event for d in declustered_detections
if d.template_name == template_name])))
self.families = new_families
return self
def copy(self):
"""
Returns a copy of the Party.
:return: Copy of party
.. rubric:: Example
>>> party = Party(families=[Family(template=Template(name='a'))])
>>> party_b = party.copy()
>>> party == party_b
True
"""
return copy.deepcopy(self)
def write(self, filename, format='tar'):
"""
Write Family out, select output format.
:type format: str
:param format:
One of either 'tar', 'csv', or any obspy supported
catalog output. See note below on formats
:type filename: str
:param filename: Path to write file to.
.. NOTE::
csv format will write out detection objects, all other
outputs will write the catalog. These cannot be rebuilt into
a Family object. The only format that can be read back into
Family objects is the 'tar' type.
.. NOTE::
We recommend writing to the 'tar' format, which will write out
all the template information (wavefiles as miniseed and metadata)
alongside the detections and store these in a tar archive. This
is readable by other programs and maintains all information
required for further study.
.. rubric:: Example
>>> party = Party().read()
>>> party.write('test_tar_write', format='tar')
Writing family 0
Writing family 1
Writing family 2
Writing family 3
Party of 4 Families.
>>> party.write('test_csv_write.csv', format='csv')
Party of 4 Families.
>>> party.write('test_quakeml.ml', format='quakeml')
Party of 4 Families.
"""
if format.lower() == 'csv':
if os.path.isfile(filename):
raise MatchFilterError(
'Will not overwrite existing file: %s' % filename)
for family in self.families:
for detection in family.detections:
detection.write(fname=filename, append=True)
elif format.lower() == 'tar':
if os.path.isdir(filename) or os.path.isfile(filename):
raise IOError('Will not overwrite existing file: %s'
% filename)
os.makedirs(filename)
Tribe([f.template for f in self.families]).write(
filename=filename, compress=False)
all_cat = Catalog()
for family in self.families:
all_cat += family.catalog
if not len(all_cat) == 0:
all_cat.write(filename + os.sep + 'catalog.xml',
format='QUAKEML')
for i, family in enumerate(self.families):
print('Writing family %i' % i)
_write_family(
family=family, filename=filename + os.sep +
family.template.name + '_detections.csv')
with tarfile.open(filename + '.tgz', "w:gz") as tar:
tar.add(filename, arcname=os.path.basename(filename))
shutil.rmtree(filename)
else:
warnings.warn('Writing only the catalog component, metadata '
'will not be preserved')
self.get_catalog().write(filename=filename, format=format)
return self
def read(self, filename=None):
"""
Read a Party from a file.
:type filename: str
:param filename: File to read from
.. rubric:: Example
>>> Party().read()
Party of 4 Families.
"""
if filename is None:
# If there is no filename given, then read the example.
filename = os.path.join(os.path.dirname(__file__),
'..', 'tests', 'test_data',
'test_party.tgz')
# First work out how many templates there are and get them.
tribe = Tribe()
with tarfile.open(filename, "r:*") as arc:
temp_dir = tempfile.mkdtemp()
arc.extractall(path=temp_dir, members=_safemembers(arc))
party_dir = glob.glob(temp_dir + os.sep + '*')[0]
tribe._read_from_folder(dirname=party_dir)
# Read in families here!
if os.path.isfile(party_dir + os.sep + 'catalog.xml'):
all_cat = read_events(party_dir + os.sep + 'catalog.xml')
else:
all_cat = Catalog()
for family_file in glob.glob(party_dir + os.sep + '*_detections.csv'):
template = [t for t in tribe
if t.name == family_file.split(os.sep)[-1].
split('_detections.csv')[0]]
if len(template) == 0:
raise MatchFilterError(
'Missing template for detection file: ' + family_file)
family = Family(template=template[0])
family.detections.extend(_read_family(family_file, all_cat))
family.catalog = Catalog([d.event for d in family.detections])
self.families.append(family)
shutil.rmtree(temp_dir)
return self
def lag_calc(self, stream, pre_processed, shift_len=0.2, min_cc=0.4,
horizontal_chans=['E', 'N', '1', '2'], vertical_chans=['Z'],
cores=1, interpolate=False, plot=False, parallel=True,
debug=0):
"""
Compute picks based on cross-correlation alignment.
:type stream: obspy.core.stream.Stream
:param stream:
All the data needed to cut from - can be a gappy Stream.
:type pre_processed: bool
:param pre_processed:
Whether the stream has been pre-processed or not to match the
templates. See note below.
:type shift_len: float
:param shift_len:
Shift length allowed for the pick in seconds, will be plus/minus
this amount - default=0.2
:type min_cc: float
:param min_cc:
Minimum cross-correlation value to be considered a pick,
default=0.4.
:type horizontal_chans: list
:param horizontal_chans:
List of channel endings for horizontal-channels, on which S-picks
will be made.
:type vertical_chans: list
:param vertical_chans:
List of channel endings for vertical-channels, on which P-picks
will be made.
:type cores: int
:param cores:
Number of cores to use in parallel processing, defaults to one.
:type interpolate: bool
:param interpolate:
Interpolate the correlation function to achieve sub-sample
precision.
:type plot: bool
:param plot:
To generate a plot for every detection or not, defaults to False
:type parallel: bool
:param parallel: Turn parallel processing on or off.
:type debug: int
:param debug: Debug output level, 0-5 with 5 being the most output.
:returns:
Catalog of events with picks. No origin information is included.
These events can then be written out via
:func:`obspy.core.event.Catalog.write`, or to Nordic Sfiles using
:func:`eqcorrscan.utils.sfile_util.eventtosfile` and located
externally.
:rtype: obspy.core.event.Catalog
.. Note::
Note on pre-processing: You can provide a pre-processed stream,
which may be beneficial for detections over large time periods
(the stream can have gaps, which reduces memory usage). However,
in this case the processing steps are not checked, so you must
ensure that all the template in the Party have the same sampling
rate and filtering as the stream.
If pre-processing has not be done then the data will be processed
according to the parameters in the templates, in this case
templates will be grouped by processing parameters and run with
similarly processed data. In this case, all templates do not have
to have the same processing parameters.
.. Note::
Picks are corrected for the template pre-pick time.
"""
catalog = Catalog()
template_groups = [[]]
detection_groups = [[]]
for master in self.families:
master_chans = [(tr.stats.station,
tr.stats.channel) for tr in master.template.st]
if len(master_chans) > len(set(master_chans)):
warnings.warn(master.template.name +
' has duplicate channels, will not use this '
'template for lag-calc as this is not coded')
continue
for group in template_groups:
if master.template in group:
break
else:
new_group = [master.template.copy()]
new_det_group = copy.deepcopy(master.detections)
for slave in self.families:
if master.template.same_processing(slave.template) and\
master.template != slave.template:
slave_chans = [
(tr.stats.station,
tr.stats.channel) for tr in slave.template.st]
if len(slave_chans) > len(set(slave_chans)):
continue
else:
new_group.append(slave.template.copy())
new_det_group.extend(
copy.deepcopy(slave.detections))
template_groups.append(new_group)
detection_groups.append(new_det_group)
# template_groups will contain an empty first list
for group, det_group in zip(template_groups, detection_groups):
if len(group) == 0:
template_groups.remove(group)
detection_groups.remove(det_group)
# Process the data for each group and time-chunk
for group, det_group in zip(template_groups, detection_groups):
if not pre_processed:
processed_streams = _group_process(
template_group=group, cores=cores, parallel=parallel,
stream=stream.copy(), debug=debug)
processed_stream = Stream()
for p in processed_streams:
processed_stream += p
processed_stream.merge()
else:
processed_stream = stream
print(stream)
temp_cat = lag_calc(
detections=det_group, detect_data=processed_stream,
template_names=[t.name for t in group],
templates=[t.st for t in group],
shift_len=shift_len, min_cc=min_cc,
horizontal_chans=horizontal_chans,
vertical_chans=vertical_chans, cores=cores,
interpolate=interpolate, plot=plot,
parallel=parallel, debug=debug)
for event in temp_cat:
det = [d for d in det_group
if str(d.id) == str(event.resource_id)][0]
pre_pick = [t for t in group
if t.name == det.template_name][0].prepick
for pick in event.picks:
pick.time += pre_pick
catalog += temp_cat
return catalog
def get_catalog(self):
"""
Get an obspy catalog object from the party.
:returns: :class:`obspy.core.event.Catalog`
.. rubric:: Example
>>> party = Party().read()
>>> cat = party.get_catalog()
>>> print(len(cat))
4
"""
catalog = Catalog()
for fam in self.families:
catalog += fam.catalog
return catalog
def min_chans(self, min_chans):
"""
Remove detections with fewer channels used than min_chans
:type min_chans: int
:param min_chans: Minimum number of channels to allow a detection.
:return: Party
.. Note:: Works in place on Party.
.. rubric:: Example
>>> party = Party().read()
>>> print(len(party))
4
>>> party = party.min_chans(5)
>>> print(len(party))
1
"""
declustered = Party()
for family in self.families:
fam = Family(family.template)
for d in family.detections:
if d.no_chans > min_chans:
fam.detections.append(d)
declustered.families.append(fam)
self.families = declustered.families
return self
class Family(object):
"""
Container for Detection objects from a single template.
:type template: eqcorrscan.core.match_filter.Template
:param template: The template used to detect the family
:type detections: list
:param detections: list of Detection objects
:type catalog: obspy.core.event.Catalog
:param catalog:
Catalog of detections, with information for the individual detections.
"""
def __init__(self, template, detections=None, catalog=None):
"""Instantiation of Family object."""
self.template = template
self.detections = []
self.catalog = Catalog()
if isinstance(detections, Detection):
detections = [detections]
if isinstance(catalog, Event):
catalog = Catalog(catalog)
if detections:
self.detections.extend(detections)
if catalog:
self.catalog.extend(catalog)
def __repr__(self):
"""
Print method on Family.
:return: str
.. rubric:: Example
>>> family = Family(template=Template(name='a'))
>>> print(family)
Family of 0 detections from template a
"""
print_str = ('Family of %s detections from template %s' %
(len(self.detections), self.template.name))
return print_str
def __add__(self, other):
"""
Extend method. Used for '+'
.. rubric:: Example
>>> family_a = Family(template=Template(name='a'))
>>> family_b = Family(template=Template(name='a'))
>>> family_c = family_a + family_b
>>> print(family_c)
Family of 0 detections from template a
Can only extend family with the family of detections from the same
template:
>>> family_a = Family(template=Template(name='a'))
>>> family_b = Family(template=Template(name='b'))
>>> family_c = family_a + family_b # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
NotImplementedError: Templates do not match
Can extend by adding a detection from the same template.
>>> family_a = Family(template=Template(name='a'))
>>> detection = Detection(
... template_name='a', detect_time=UTCDateTime(), no_chans=5,
... detect_val=2.5, threshold=1.23, typeofdet='corr',
... threshold_type='MAD', threshold_input=8.0)
>>> family = family_a + detection
>>> print(family)
Family of 1 detections from template a
Will not work if detections are made using a different Template.
>>> family_a = Family(template=Template(name='a'))
>>> detection = Detection(
... template_name='b', detect_time=UTCDateTime(), no_chans=5,
... detect_val=2.5, threshold=1.23, typeofdet='corr',
... threshold_type='MAD', threshold_input=8.0)
>>> family = family_a + detection # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
NotImplementedError: Templates do not match
Can not extent a family with a list, or another object.
>>> family_a = Family(template=Template(name='a'))
>>> family = family_a + ['albert'] # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
NotImplementedError: Can only extend with a Detection of Family object.
"""
if isinstance(other, Family):
if other.template == self.template:
self.detections.extend(other.detections)
try:
self.catalog += other.catalog
except TypeError:
pass
else:
raise NotImplementedError('Templates do not match')
elif isinstance(other, Detection) and other.template_name \
== self.template.name:
self.detections.append(other)
try:
self.catalog += other.event
except TypeError:
pass
elif isinstance(other, Detection):
raise NotImplementedError('Template do not match')
else:
raise NotImplementedError('Can only extend with a Detection or '
'Family object.')
return self
def __iadd__(self, other):
"""
Rich method '+='
.. rubric:: Example
>>> family_a = Family(template=Template(name='a'))
>>> family_b = Family(template=Template(name='a'))
>>> family_a += family_b
>>> print(family_a)
Family of 0 detections from template a
"""
return self.__add__(other)
def __eq__(self, other):
"""
Check equality, rich comparison operator '=='
.. rubric:: Example
>>> family_a = Family(template=Template(name='a'), detections=[])
>>> family_b = Family(template=Template(name='a'), detections=[])
>>> family_a == family_b
True
>>> family_c = Family(template=Template(name='b'))
>>> family_c == family_a
False
Test if families are equal without the same detections
>>> family_a = Family(
... template=Template(name='a'), detections=[
... Detection(template_name='a', detect_time=UTCDateTime(0),
... no_chans=8, detect_val=4.2, threshold=1.2,
... typeofdet='corr', threshold_type='MAD',
... threshold_input=8.0)])
>>> family_b = Family(
... template=Template(name='a'), detections=[
... Detection(template_name='a', detect_time=UTCDateTime(0) + 10,
... no_chans=8, detect_val=4.2, threshold=1.2,
... typeofdet='corr', threshold_type='MAD',
... threshold_input=8.0)])
>>> family_a == family_b
False
>>> family_c = Family(
... template=Template(name='a'), detections=[
... Detection(template_name='a', detect_time=UTCDateTime(0),
... no_chans=8, detect_val=4.2, threshold=1.2,
... typeofdet='corr', threshold_type='MAD',
... threshold_input=8.0),
... Detection(template_name='a', detect_time=UTCDateTime(0) + 10,
... no_chans=8, detect_val=4.5, threshold=1.2,
... typeofdet='corr', threshold_type='MAD',
... threshold_input=8.0)])
>>> family_a == family_c
False
"""
if not self.template == other.template:
return False
if len(self.detections) != len(other.detections):
return False
if len(self.detections) != 0 and len(other.detections) != 0:
for det, other_det in zip(self.sort().detections,
other.sort().detections):
if det != other_det:
return False
# currently not checking for catalog...
if len(self.catalog) != len(other.catalog):
return False
return True
def __ne__(self, other):
"""
Rich comparison operator '!='
.. rubric:: Example
>>> family_a = Family(
... template=Template(name='a'), detections=[
... Detection(template_name='a', detect_time=UTCDateTime(0),
... no_chans=8, detect_val=4.2, threshold=1.2,
... typeofdet='corr', threshold_type='MAD',
... threshold_input=8.0)])
>>> family_b = Family(
... template=Template(name='a'), detections=[
... Detection(template_name='a', detect_time=UTCDateTime(),
... no_chans=8, detect_val=4.2, threshold=1.2,
... typeofdet='corr', threshold_type='MAD',
... threshold_input=8.0)])