-
Notifications
You must be signed in to change notification settings - Fork 0
/
eqcatalog.py
7328 lines (6541 loc) · 230 KB
/
eqcatalog.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
# -*- coding: iso-Latin-1 -*-
"""
Module for processing earthquake catalogs.
====================================================
Author: Kris Vanneste, Royal Observatory of Belgium.
Date: May 2008.
Required modules:
Third-party:
matplotlib / pylab
numpy
scipy
ogr
ROB:
mapping.MIPython
users.kris.Seismo.db.seismodb
"""
from __future__ import absolute_import, division, print_function, unicode_literals
try:
## Python 2
basestring
except:
## Python 3
basestring = str
## Import standard python modules
import os
import sys
import platform
import datetime
import json
from collections import OrderedDict
## Import third-party modules
import numpy as np
import matplotlib
if platform.uname()[1] == "seissrv3":
## Kludge because matplotlib is broken on seissrv3.
matplotlib.use('AGG')
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import pylab
from matplotlib.font_manager import FontProperties
from matplotlib.ticker import MultipleLocator, MaxNLocator
## Import ROB modules
import mapping.geotools.geodetic as geodetic
## Import package submodules
from .eqrecord import LocalEarthquake
from .completeness import Completeness
from . import time as timelib
# TODO: re-implement interface with (Hazard) Modelers' Toolkit
class EQCatalog(object):
"""
Class defining a collection of local earthquakes.
:param eq_list:
List containing instances of :class:`LocalEarthquake`
:param start_date:
instance of :class:`np.datetime64` or :class:`datetime.datetime`,
start datetime of catalog
(default: None = datetime of oldest earthquake in catalog)
:param end_date:
instance of :class:`np.datetime64` or :class:`datetime.datetime`,
end datetme of catalog
(default: None = datetime of youngest earthquake in catalog)
:param region:
(lon0, lon1, lat0, lat1) tuple with geographic coordinates of
bounding box
(default: None)
:param name:
String, catalog name
(default: "")
:param default_Mrelations:
dict, mapping Mtype (str) to Mrelations (ordered dicts,
in turn mapping Mtype to name of magnitude conversion relations):
default conversion relations for different magnitude types
(default: {})
:param default_completeness:
instance of :class:`Completeness`, default catalog completeness
(default: None)
"""
def __init__(self, eq_list, start_date=None, end_date=None, region=None,
name="", default_Mrelations={}, default_completeness=None):
self.eq_list = eq_list[:]
Tmin, Tmax = self.Tminmax()
if not start_date:
self.start_date = Tmin
else:
self.start_date = timelib.as_np_datetime(start_date, unit='ms')
if not end_date:
self.end_date = Tmax
else:
self.end_date = timelib.as_np_datetime(end_date, unit='ms')
self.region = region
self.name = name
self.default_Mrelations = default_Mrelations
self.default_completeness = default_completeness
def __repr__(self):
txt = '<EQCatalog "%s" | %s - %s | n=%d>'
txt %= (self.name, self.start_date, self.end_date, len(self))
return txt
def __len__(self):
"""
Return number of earthquakes in collection.
"""
return len(self.eq_list)
def __iter__(self):
return self.eq_list.__iter__()
def __getitem__(self, item):
"""
Indexing --> instance of :class:`LocalEarthquake`
Slicing / Index array --> instance of :class:`EQCatalog`
"""
if isinstance(item, (int, np.integer)):
return self.eq_list.__getitem__(item)
elif isinstance(item, slice):
return EQCatalog(self.eq_list.__getitem__(item), start_date=self.start_date,
end_date=self.end_date, region=self.region,
name=self.name + " %s" % item,
default_Mrelations=self.default_Mrelations,
default_completeness=self.default_completeness)
elif isinstance(item, (list, np.ndarray)):
## item can contain indexes or bool
eq_list = []
if len(item):
idxs = np.arange(len(self))
idxs = idxs[np.asarray(item)]
for idx in idxs:
eq_list.append(self.eq_list[idx])
return EQCatalog(eq_list, start_date=self.start_date, end_date=self.end_date,
region=self.region, name=self.name + " %s" % item,
default_Mrelations=self.default_Mrelations,
default_completeness=self.default_completeness)
def __contains__(self, eq):
"""
Determine whether or not given earthquake is in catalog
(based on its ID)
:param eq:
instance of :class:`LocalEarthquake`
:return:
bool
"""
assert isinstance(eq, LocalEarthquake)
return eq.ID in self.get_ids()
def __eq__(self, other_catalog):
return sorted(self.get_ids()) == sorted(other_catalog.get_ids())
def __add__(self, other_catalog):
return self.get_union(other_catalog)
def __sub__(self, other_catalog):
return self.get_difference(other_catalog)
def append(self, eq):
"""
Append earthquake to catalog
:param eq:
instance of :class:`LocalEarthquake`
"""
self.eq_list.append(eq)
def copy(self):
"""
Copy catalog
:return:
instance of :class:`EQCatalog`
"""
eq_list = [eq.copy() for eq in self]
start_date, end_date = self.start_date, self.end_date
region = self.region
name = self.name
default_Mrelations = self.default_Mrelations
default_completeness = self.default_completeness
return self.__class__(eq_list, start_date=start_date, end_date=end_date,
region=region, name=name,
default_Mrelations=default_Mrelations,
default_completeness=default_completeness)
@property
def lons(self):
return self.get_longitudes()
@property
def lats(self):
return self.get_latitudes()
@property
def mags(self):
return self.get_magnitudes()
## Methods related to earthquake IDs
def get_ids(self):
"""
Return earthquake IDs
:return:
list of strings or integers
"""
return [eq.ID for eq in self]
def get_unique_ids(self):
"""
Return unqiue earthquake IDs
"""
return np.unique(self.get_ids())
def has_unique_ids(self):
"""
Determine whether or not earthquakes in catalog have unique IDs
:return:
bool
"""
num_unique_ids = len(self.get_unique_ids())
if num_unique_ids == len(self):
return True
else:
return False
def index(self, id):
"""
Get index of event with given ID
:param id:
int or str, earthquake ID
:return:
int, index in catalog
"""
str_ids = list(map(str, self.get_ids()))
try:
idx = str_ids.index(str(id))
except ValueError:
return None
else:
return idx
def get_event_by_id(self, id):
"""
Extract event with given ID
:param id:
int or str, earthquake ID
:return:
instance of :class:`LocalEarthquake`
"""
idx = self.index(id)
if idx is not None:
return self.__getitem__(idx)
def get_duplicate_idxs(self):
"""
Determine indexes of duplicate earthquakes in catalog
:return:
int array, indexes of duplicates
"""
ids = self.get_ids()
unique_ids, duplicate_idxs = [], []
for i, id in enumerate(ids):
if not id in unique_ids:
unique_ids.append(id)
else:
duplicate_idxs.append(i)
return duplicate_idxs
def remove_duplicates(self):
"""
Return catalog with duplicates removed
:return:
instance of :class:`EQCatalog`
"""
duplicate_idxs = self.get_duplicate_idxs()
return self.remove_events_by_index(duplicate_idxs)
def remove_events_by_index(self, idxs):
"""
Return catalog with earthquakes corresponding to indexes removed
:param idxs:
int list or array, indexes of earthquakes to be removed
:return:
instance of :class:`EQCatalog`
"""
all_idxs = np.arange(len(self))
remaining_idxs = set(all_idxs) - set(idxs)
remaining_idxs = np.array(sorted(remaining_idxs))
return self.__getitem__(remaining_idxs)
def remove_events_by_id(self, IDs):
"""
Return catalog with earthquakes with given IDs removed
:param IDs:
list of ints or strings, IDs of earthquakes to be removed
:return:
instance of :class:`EQCatalog`
"""
idxs = []
for ID in IDs:
idxs.append(self.index(ID))
return self.remove_events_by_index(idxs)
def get_union(self, other_catalog, name=None):
"""
Return catalog of all events in catalog and in other catalog
(without duplicates)
:param other_catalog:
instance of :class:`EQCatalog`
:param name:
str, name of resulting catalog
(default: None, will generate name automatically)
:return:
instance of :class:`EQCatalog`
"""
assert isinstance(other_catalog, EQCatalog)
ids = set(self.get_ids())
other_ids = set(other_catalog.get_ids())
union = list(ids.union(other_ids))
cat1 = self.subselect(attr_val=('ID', union))
cat2 = other_catalog.subselect(attr_val=('ID', union))
if name is None:
name = "Union(%s, %s)" % (self.name, other_catalog.name)
return concatenate_catalogs([cat1, cat2], name=name)
# TODO: set catalog start and end dates!
def get_intersection(self, other_catalog, name=None):
"""
Return catalog of events that are both in catalog and in
other catalog
:param other_catalog:
instance of :class:`EQCatalog`
:param name:
str, name of resulting catalog
(default: None, will generate name automatically)
:return:
instance of :class:`EQCatalog`
"""
assert isinstance(other_catalog, EQCatalog)
ids = set(self.get_ids())
other_ids = set(other_catalog.get_ids())
intersection = list(ids.intersection(other_ids))
catalog = self.subselect(attr_val=('ID', intersection))
if name is None:
name = "Intersection(%s, %s)" % (self.name, other_catalog.name)
catalog.name = name
return catalog
def get_difference(self, other_catalog, name=None):
"""
Return catalog of events that are in catalog but not in
other catalog
:param other_catalog:
instance of :class:`EQCatalog`
:param name:
str, name of resulting catalog
(default: None, will generate name automatically)
:return:
instance of :class:`EQCatalog`
"""
assert isinstance(other_catalog, EQCatalog)
ids = set(self.get_ids())
other_ids = set(other_catalog.get_ids())
diff = list(ids - other_ids)
catalog = self.subselect(attr_val=('ID', diff))
if name is None:
name = "Difference(%s, %s)" % (self.name, other_catalog.name)
catalog.name = name
return catalog
def get_symmetric_difference(self, other_catalog, name=None):
"""
Return catalog of events that are only in catalog or in
other catalog
:param other_catalog:
instance of :class:`EQCatalog`
:param name:
str, name of resulting catalog
(default: None, will generate name automatically)
:return:
instance of :class:`EQCatalog`
"""
assert isinstance(other_catalog, EQCatalog)
ids = set(self.get_ids())
other_ids = set(other_catalog.get_ids())
symdiff = list(ids.symmetric_difference(other_ids))
cat1 = self.subselect(attr_val=('ID', symdiff))
cat2 = other_catalog.subselect(attr_val=('ID', symdiff))
if name is None:
name = "Symmetric Difference(%s, %s)" % (self.name, other_catalog.name)
return concatenate_catalogs([cat1, cat2], name=name)
def print_info(self, as_html=False):
"""
Print some useful information about the catalog.
:param as_html:
bool, whether to return HTML or to print plain text
(default: False)
:return:
str or instance of :class:`PrettyTable`
"""
try:
from prettytable import PrettyTable
except:
has_prettytable = False
else:
has_prettytable = True
tab = PrettyTable(["Parameter", "Value"])
rows = []
rows.append(["Catalog name", self.name])
rows.append(["Earthquake number", "%d" % len(self)])
rows.append(["Start time", "%s" % self.start_date])
rows.append(["End time", "%s" % self.end_date])
lonmin, lonmax = self.lon_minmax()
rows.append(["Longitude bounds", "%.4f / %.4f" % (lonmin, lonmax)])
latmin, latmax = self.lat_minmax()
rows.append(["Latitude bounds", "%.4f / %.4f" % (latmin, latmax)])
depth_min, depth_max = self.depth_minmax()
rows.append(["Depth range", "%.1f / %.1f km" % (depth_min, depth_max)])
for Mtype, count in self.get_Mtype_counts().items():
mags = self.get_magnitudes(Mtype=Mtype, Mrelation={})
mags = mags[np.isfinite(mags)]
if len(mags):
if mags.min() == 0:
mags = mags[mags > 0]
rows.append([Mtype,
"n=%d, min=%.1f, max=%.1f" % (count, mags.min(), mags.max())])
etype_num_dict = self.count_num_by_event_type()
etype_str = ', '.join(["%s (n=%d)" % (etype, etype_num_dict[etype])
for etype in etype_num_dict])
rows.append(["Event types", etype_str])
if has_prettytable:
for row in rows:
tab.add_row(row)
if as_html:
return tab.get_html_string()
else:
print(tab)
return tab
else:
for row in tab:
print(' :\t'.join(row))
def get_formatted_table(self, max_name_width=30, lonlat_decimals=3,
depth_decimals=1, mag_decimals=1,
padding_width=1, include_err=False):
"""
Return formatted table of earthquakes in catalog.
:param max_name_width:
int, max. width for 'name' column
(default: 30)
:param lonlat_decimals:
int, number of decimals for longitudes and latitudes
(default: 3)
:param depth_decimals:
int, number of decimals for depths
(default: 1)
:param mag_decimals:
int, number of decimals for magnitudes
(default: 1)
:param include_err:
bool, whether or not to include uncertainties in table, if present
(default: False)
:return:
instance of :class:`PrettyTable`
"""
import prettytable as pt
def remove_nan_values(ar):
return [val if not np.isnan(val) else '' for val in ar]
tab = pt.PrettyTable()
tab.add_column('ID', self.get_ids(), align='r', valign='m')
tab.add_column('Date', [eq.date for eq in self], valign='m')
tab.add_column('Time', [eq.time for eq in self], valign='m')
names = [eq.name for eq in self]
if sum([len(name) for name in names]):
tab.add_column('Name', names, valign='m')
lons = remove_nan_values(self.get_longitudes())
tab.add_column('Lon', lons, align='r', valign='m')
lats = remove_nan_values(self.get_latitudes())
tab.add_column('Lat', lats, align='r', valign='m')
depths = remove_nan_values(self.get_depths())
tab.add_column('Z', depths, align='r', valign='m')
Mtypes = self.get_Mtypes()
for Mtype in Mtypes:
#mags = self.get_magnitudes(Mtype, Mrelation={})
mags = np.array([eq.mag.get(Mtype, np.nan) for eq in self])
if not np.isnan(mags).all():
mags = remove_nan_values(mags)
tab.add_column(Mtype, mags, align='r', valign='m')
if include_err:
for unc_type in ('errt', 'errh', 'errz', 'errM'):
err = [getattr(eq, unc_type) for eq in self]
if not np.isnan(err).all():
err = remove_nan_values(err)
tab.add_column(unc_type, err)
intensities = self.get_max_intensities()
if not ((intensities == 0).all() or np.isnan(intensities).all()):
intensities = remove_nan_values(intensities)
tab.add_column('Imax', intensities, align='r', valign='m')
event_types = [eq.event_type for eq in self]
if len(set(event_types)) > min(1, len(self)-1):
tab.add_column('Type', event_types, valign='m')
agencies = [eq.agency for eq in self]
if len(set(agencies)) > min(1, len(self)-1):
tab.add_column('Agency', agencies, valign='m')
tab.padding_width = padding_width
tab.max_width['Name'] = max_name_width
tab.float_format['Lon'] = tab.float_format['Lat'] = '.%d' % lonlat_decimals
tab.float_format['Z'] = '.%d' % depth_decimals
tab.float_format['errt'] = '.1'
tab.float_format['errh'] = '.1'
tab.float_format['errz'] = '.1'
tab.float_format['errM'] = '.1'
for Mtype in Mtypes:
if Mtype in tab.field_names:
tab.float_format[Mtype] = '.%d' % mag_decimals
return tab
def get_formatted_list(self, as_html=False, max_name_width=30,
lonlat_decimals=3, depth_decimals=1, mag_decimals=1,
padding_width=1, include_err=False):
"""
Return string representing formatted table of earthquakes
in catalog.
:param as_html:
bool, whether to return HTML or to print plain text
(default: False)
:param max_name_width:
:param lonlat_decimals:
:param depth_decimals:
:param mag_decimals:
:param include_err:
see :meth:`get_formatted_table`
:return:
str
"""
tab = self.get_formatted_table(max_name_width=max_name_width,
lonlat_decimals=lonlat_decimals, depth_decimals=depth_decimals,
mag_decimals=mag_decimals, padding_width=padding_width,
include_err=include_err)
if as_html:
return tab.get_html_string()
else:
return tab.get_string()
def print_list(self, out_file=None, max_name_width=30, lonlat_decimals=3,
depth_decimals=1, mag_decimals=1, padding_width=1,
include_err=False):
"""
Print list of earthquakes in catalog
:param out_file:
str, full path to output file
If extension starts with .htm, the list is exported in HTML
format, else plain text
(default: None, will print list to screen)
:param max_name_width:
:param lonlat_decimals:
:param depth_decimals:
:param mag_decimals:
:param include_err:
see :meth:`get_formatted_list`
:return:
None or str if :param:`as_html` is True
"""
try:
from prettytable import PrettyTable
except:
from pprint import pprint
has_prettytable = False
else:
has_prettytable = True
if has_prettytable:
tab = self.get_formatted_table(max_name_width=max_name_width,
lonlat_decimals=lonlat_decimals, depth_decimals=depth_decimals,
mag_decimals=mag_decimals, padding_width=padding_width,
include_err=include_err)
if out_file:
of = open(out_file, 'w')
if os.path.splitext(out_file)[-1].lower()[:4] == '.htm':
of.write(tab.get_html_string())
else:
of.write(tab.get_string())
of.close()
else:
print(tab)
else:
pass
"""
try:
from prettytable import PrettyTable
except:
has_prettytable = False
else:
has_prettytable = True
col_names = ["ID", "Date", "Time", "Name", "Lon", "Lat", "Depth",
"ML", "MS", "MW"]
if has_prettytable:
tab = PrettyTable(col_names)
else:
tab = [col_names]
for eq in self.eq_list:
row = [str(eq.ID), str(eq.date), str(eq.time), eq.name,
"%.4f" % eq.lon, "%.4f" % eq.lat, "%.1f" % eq.depth,
"%.1f" % eq.ML, "%.1f" % eq.MS, "%.1f" % eq.MW]
if has_prettytable:
tab.add_row(row)
else:
tab.append(row)
if has_prettytable:
if as_html:
return tab.get_html_string()
else:
print(tab)
return tab
else:
for row in tab:
print('\t'.join(row))
"""
@classmethod
def from_json(cls, s):
"""
Generate instance of :class:`EQCatalog` from a json string
:param s:
String, json format
"""
dct = json.loads(s)
if len(dct) == 1:
class_name = dct.keys()[0]
if class_name == "__EQCatalog__":
return cls.from_dict(dct[class_name])
@classmethod
def from_dict(cls, dct):
"""
Generate instance of :class:`EQCatalog` from a dictionary
:param dct:
Dictionary
"""
if 'eq_list' in dct:
dct['eq_list'] = [LocalEarthquake.from_dict(d["__LocalEarthquake__"])
for d in dct['eq_list']]
return EQCatalog(**dct)
def dump_json(self):
"""
Generate json string
"""
def json_handler(obj):
if isinstance(obj, LocalEarthquake):
key = '__%s__' % obj.__class__.__name__
dct = {key: obj.__dict__}
return dct
elif isinstance(obj, (datetime.time, datetime.date)):
return repr(obj)
elif isinstance(obj, np.datetime64):
return str(obj)
else:
return obj.__dict__
key = '__%s__' % self.__class__.__name__
dct = {key: self.__dict__}
return json.dumps(dct, default=json_handler)
## Methods related to event_type
def get_event_types(self):
"""
Return list of event types for all earthquakes in catalog
"""
return [eq.event_type for eq in self]
def get_unique_event_types(self):
"""
Return list of unique event types in catalog
"""
return sorted(set(self.get_event_types()))
def count_num_by_event_type(self):
"""
Count number of events for each event type
:return:
dict, mapping event type (str) to number of events (int)
"""
etype_num_dict = {}
for eq in self:
etype = eq.event_type
if not etype in etype_num_dict:
etype_num_dict[etype] = 1
else:
etype_num_dict[etype] += 1
return etype_num_dict
## Time methods
@property
def start_year(self):
return int(timelib.to_year(self.start_date))
@property
def end_year(self):
return int(timelib.to_year(self.end_date))
def get_datetimes(self):
"""
Return list of datetimes for all earthquakes in catalog
"""
return np.array([eq.datetime for eq in self])
def get_years(self):
"""
Return array of integer years for all earthquakes in catalog
"""
return timelib.to_year(self.get_datetimes())
def get_fractional_years(self):
"""
Return array with fractional years for all earthquakes in catalog
"""
years = timelib.to_fractional_year(self.get_datetimes())
return years
def Tminmax(self, Mmax=None, Mtype="MW", Mrelation={}):
"""
Return tuple with oldest date and youngest date in catalog.
:param Mmax:
Float, maximum magnitude. Useful to check completeness periods.
:param Mtype:
String, magnitude type: "ML", "MS" or "MW" (default: "MW")
:param Mrelation:
{str: str} dict, mapping name of magnitude conversion relation
to magnitude type ("MW", "MS" or "ML")
(default: {})
"""
datetimes = self.get_datetimes()
if Mmax != None:
Mags = self.get_magnitudes(Mtype=Mtype, Mrelation=Mrelation)
datetimes = datetimes[np.where(Mags < Mmax)]
try:
return (datetimes.min(), datetimes.max())
except ValueError:
return (None, None)
def get_time_delta(self, from_events=False):
"""
Return duration of catalog as timedelta object
:param from_events:
bool, if True, compute time between first and last event
else use start and end date of catalog
(default: False)
:return:
instance of :class:`np.timedelta64`
"""
if from_events:
Tmin, Tmax = self.Tminmax()
else:
Tmin, Tmax = self.start_date, self.end_date
return Tmax - Tmin
def get_time_deltas(self, start_datetime=None):
"""
Return time difference between a start time and each event.
:param start_datetime:
instance of :class:`np.datetime64` or :class:`datetime.datetime`,
start time
(default: None, will take the start time of the catalog)
:return:
array with instances of :class:`np.timedelta64`
"""
if not start_datetime:
start_datetime = self.start_date
return self.get_datetimes() - start_datetime
def get_inter_event_times(self, unit='D'):
"""
Return time interval in fractions of specified unit between each
subsequent event
:param unit:
str, one of 'Y', 'W', 'D', 'h', 'm', 's', 'ms', 'us'
(year|week|day|hour|minute|second|millisecond|microsecond)
(default: 'D')
:return:
float array, inter-event times
"""
sorted_catalog = self.get_sorted()
date_times = sorted_catalog.get_datetimes()
time_deltas = np.diff(date_times)
return timelib.fractional_time_delta(time_deltas, unit=unit)
def timespan(self, unit='Y'):
"""
Return total time span of catalog as fraction of specified unit
:param unit:
str, one of 'Y', 'W', 'D', 'h', 'm', 's', 'ms', 'us'
(year|week|day|hour|minute|second|millisecond|microsecond)
(default: 'Y')
"""
start_date, end_date = self.start_date, self.end_date
return timelib.timespan(start_date, end_date, unit=unit)
## Magnitude / moment methods
def get_magnitudes(self, Mtype="MW", Mrelation={}):
"""
Return array of magnitudes for all earthquakes in catalog
:param Mtype:
String, magnitude type: "ML", "MS" or "MW" (default: "MW")
:param Mrelation:
{str: str} dict, mapping name of magnitude conversion relation
to magnitude type ("MW", "MS" or "ML")
(default: {}, will select the default relation for the
given Mtype in :prop:`default_Mrelations`)
:return:
1-D numpy float array, earthquake magnitudes
"""
# TODO: it should also be possible to get magnitudes without any conversion...
if not Mrelation:
Mrelation = self.default_Mrelations.get(Mtype, {})
Mags = [eq.get_or_convert_mag(Mtype, Mrelation) for eq in self]
return np.array(Mags)
def Mminmax(self, Mtype="MW", Mrelation={}):
"""
Return tuple with minimum and maximum magnitude in catalog.
:param Mtype:
String, magnitude type: "ML", "MS" or "MW" (default: "MW")
:param Mrelation:
{str: str} dict, mapping name of magnitude conversion relation
to magnitude type ("MW", "MS" or "ML")
(default: {})
"""
Mags = self.get_magnitudes(Mtype=Mtype, Mrelation=Mrelation)
return (np.nanmin(Mags), np.nanmax(Mags))
def get_Mmin(self, Mtype="MW", Mrelation={}):
"""
Compute minimum magnitude in catalog
:param Mtype:
String, magnitude type: "MW", "MS" or "ML" (default: "MW")
:param Mrelation":
{str: str} dict, mapping name of magnitude conversion relation
to magnitude type ("MW", "MS" or "ML")
(default: {})
:return:
Float, maximum observed magnitude
"""
return np.nanmin(self.get_magnitudes(Mtype, Mrelation))
def get_Mmax(self, Mtype="MW", Mrelation={}):
"""
Compute maximum magnitude in catalog
:param Mtype:
String, magnitude type: "MW", "MS" or "ML" (default: "MW")
:param Mrelation":
{str: str} dict, mapping name of magnitude conversion relation
to magnitude type ("MW", "MS" or "ML")
(default: {})
:return:
Float, maximum observed magnitude
"""
if len(self) > 0:
Mmax = np.nanmax(self.get_magnitudes(Mtype, Mrelation))
else:
Mmax = np.nan
return Mmax
def convert_magnitudes(self, Mtype="MW", Mrelation={}):
"""
Convert magnitude to given magnitude type and store in
earthquake objects.
:param Mtype:
:param Mrelation:
see :meth:`get_magnitudes`
"""
mags = self.get_magnitudes(Mtype, Mrelation)
for eq, mag in zip(self.eq_list, mags):
eq.set_mag(Mtype, mag)
def get_magnitude_uncertainties(self, min_uncertainty=0.3):
"""
Return array with magnitude uncertainties
:param min_uncertainty:
Float, minimum uncertainty that will be used to replace zero
and nan values. If None, no values will be replaced.
(default: 0.3)
:return:
1-D numpy float array, magnitude uncertainties
"""
Mag_uncertainties = np.array([eq.errM for eq in self])
if not min_uncertainty is None:
Mag_uncertainties[Mag_uncertainties == 0] = min_uncertainty
Mag_uncertainties[np.isnan(Mag_uncertainties)] = min_uncertainty
return Mag_uncertainties
def get_Mtypes(self):
"""
Obtain list of magnitude types in catalog.
:return:
list of strings
"""
Mtypes = set()
for eq in self:
Mtypes.update(eq.get_Mtypes())
return list(Mtypes)
def get_Mtype_counts(self):
"""
Obtain number of earthquakes for each magnitude type in catalog
:return:
dict, mapping magnitude types to integers
"""
from itertools import combinations
Mtype_counts = {}
for eq in self:
eq_Mtypes = eq.get_Mtypes()
for Mtype in eq_Mtypes:
if Mtype in Mtype_counts:
Mtype_counts[Mtype] += 1
else: