Skip to content

Commit 5dcfbfb

Browse files
author
Mike Hearne
authored
Merge pull request #127 from mhearne-usgs/magfix
Moved get all mags functionality into utils module.
2 parents e5438e1 + db069fd commit 5dcfbfb

2 files changed

Lines changed: 90 additions & 66 deletions

File tree

bin/getmags

Lines changed: 12 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -3,59 +3,16 @@ import argparse
33
import sys
44

55
from libcomcat.search import search, count
6-
from libcomcat.utils import get_detail_data_frame, get_summary_data_frame, maketime
7-
from impactutils.time.ancient_time import HistoricTime
6+
from libcomcat.utils import (maketime, get_all_mags)
87
from obspy.clients.fdsn import Client
98
import pandas as pd
109

1110

12-
class CustomFormatter(argparse.ArgumentDefaultsHelpFormatter, argparse.RawDescriptionHelpFormatter):
11+
class CustomFormatter(argparse.ArgumentDefaultsHelpFormatter,
12+
argparse.RawDescriptionHelpFormatter):
1313
pass
1414

1515

16-
def get_mag_src(mag):
17-
"""Try to find the best magnitude source from a Magnitude object.
18-
19-
Note: This can be difficult, as there is a great deal of variance
20-
in how magnitude information is submitted in QuakeML within ComCat.
21-
22-
Args:
23-
mag (obspy Magnitude): Magnitude object from obspy.
24-
Returns:
25-
str: String indicating the most likely source of the magnitude solution.
26-
27-
"""
28-
if mag.creation_info is not None and mag.creation_info.agency_id is not None:
29-
magsrc = mag.creation_info.agency_id.lower()
30-
else:
31-
has_gcmt = mag.resource_id.id.lower().find('gcmt') > -1
32-
has_at = mag.resource_id.id.lower().find('at') > -1
33-
has_pt = mag.resource_id.id.lower().find('pt') > -1
34-
has_ak = (mag.resource_id.id.lower().find('ak') > -1 or
35-
mag.resource_id.id.lower().find('alaska') > -1)
36-
has_pr = mag.resource_id.id.lower().find('pr') > -1
37-
has_dup = mag.resource_id.id.lower().find('duputel') > -1
38-
has_us = mag.resource_id.id.lower().find('us') > -1
39-
if has_gcmt:
40-
magsrc = 'gcmt'
41-
elif has_dup:
42-
magsrc = 'duputel'
43-
elif has_at:
44-
magsrc = 'at'
45-
elif has_pt:
46-
magsrc = 'pt'
47-
elif has_ak:
48-
magsrc = 'ak'
49-
elif has_pr:
50-
magsrc = 'pr'
51-
elif has_us:
52-
magsrc = 'us'
53-
else:
54-
magsrc = 'unknown'
55-
56-
return magsrc
57-
58-
5916
def get_parser():
6017
desc = '''Download epicenter and all contributed magnitudes in line format (csv, tab, etc.).
6118
@@ -186,7 +143,6 @@ def main():
186143
# create a dataframe with these columns - we'll add more later
187144
df = pd.DataFrame(columns=['id', 'time', 'lat', 'lon', 'depth',
188145
'location', 'url', 'hypo_src'])
189-
client = Client('USGS')
190146
ievent = 1
191147

192148
for event in events:
@@ -208,24 +164,14 @@ def main():
208164
print('Parsing event %s (%i of %i) - %i origins' % tpl)
209165
ievent += 1
210166
errors = []
167+
mags = {}
211168
for eid in id_list:
212-
try:
213-
obsevent = client.get_events(eventid=eid).events[0]
214-
except Exception as e:
215-
msg = 'Failed to download data for event %s. Skipping.' % eid
216-
errors.append(msg)
217-
for mag in obsevent.magnitudes:
218-
magvalue = mag.mag
219-
magtype = mag.magnitude_type
220-
magsrc = get_mag_src(mag)
221-
if magsrc == 'unknown' and args.verbose:
222-
print('Unable to determine magnitude source from %s' % eid)
223-
colname = '%s-%s' % (magsrc, magtype)
224-
if colname in row:
225-
# print('Duplicate column %s for event %s - skipping' % (colname,event.id))
226-
continue
227-
row[colname] = magvalue
228-
imag += 1
169+
magtypes, msg = get_all_mags(eid)
170+
if args.verbose and len(msg):
171+
print(msg)
172+
mags.update(magtypes)
173+
imag += 1
174+
row = pd.concat([row, pd.Series(mags)])
229175
df = df.append(row, ignore_index=True)
230176

231177
if len(errors):
@@ -234,9 +180,9 @@ def main():
234180
print('\t%s' % error)
235181

236182
if args.format == 'excel':
237-
df.to_excel(args.filename)
183+
df.to_excel(args.filename, index=False)
238184
else:
239-
df.to_csv(args.filename)
185+
df.to_csv(args.filename, index=False)
240186
print('%i records saved to %s.' % (len(df), args.filename))
241187
sys.exit(0)
242188

libcomcat/utils.py

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
import numpy as np
1111
import pandas as pd
1212
from obspy.io.quakeml.core import Unpickler
13+
from obspy.clients.fdsn import Client
1314
from impactutils.time.ancient_time import HistoricTime
1415
from openpyxl import load_workbook
1516

@@ -22,6 +23,83 @@
2223
DATEFMT = '%Y-%m-%d'
2324

2425

26+
def get_mag_src(mag):
27+
"""Try to find the best magnitude source from a Magnitude object.
28+
29+
Note: This can be difficult, as there is a great deal of variance
30+
in how magnitude information is submitted in QuakeML within ComCat.
31+
32+
Args:
33+
mag (obspy Magnitude): Magnitude object from obspy.
34+
Returns:
35+
str: String indicating the most likely source of the
36+
magnitude solution.
37+
38+
"""
39+
c1 = mag.creation_info is not None
40+
if c1:
41+
c2 = mag.creation_info.agency_id is not None
42+
else:
43+
c2 = False
44+
if c2:
45+
magsrc = mag.creation_info.agency_id.lower()
46+
else:
47+
has_gcmt = mag.resource_id.id.lower().find('gcmt') > -1
48+
has_at = mag.resource_id.id.lower().find('at') > -1
49+
has_pt = mag.resource_id.id.lower().find('pt') > -1
50+
has_ak = (mag.resource_id.id.lower().find('ak') > -1 or
51+
mag.resource_id.id.lower().find('alaska') > -1)
52+
has_pr = mag.resource_id.id.lower().find('pr') > -1
53+
has_dup = mag.resource_id.id.lower().find('duputel') > -1
54+
has_us = mag.resource_id.id.lower().find('us') > -1
55+
if has_gcmt:
56+
magsrc = 'gcmt'
57+
elif has_dup:
58+
magsrc = 'duputel'
59+
elif has_at:
60+
magsrc = 'at'
61+
elif has_pt:
62+
magsrc = 'pt'
63+
elif has_ak:
64+
magsrc = 'ak'
65+
elif has_pr:
66+
magsrc = 'pr'
67+
elif has_us:
68+
magsrc = 'us'
69+
else:
70+
magsrc = 'unknown'
71+
72+
return magsrc
73+
74+
75+
def get_all_mags(eventid):
76+
"""Get all magnitudes for a given event ID.
77+
78+
Args:
79+
eventid (str): ComCat Event ID.
80+
Returns:
81+
dict: Dictionary where keys are "magsrc-magtype" and values
82+
are magnitude value.
83+
84+
"""
85+
row = {}
86+
msg = ''
87+
client = Client('USGS')
88+
try:
89+
obsevent = client.get_events(eventid=eventid).events[0]
90+
except Exception as e:
91+
msg = 'Failed to download event %s, error "%s".' % (eventid, str(e))
92+
for mag in obsevent.magnitudes:
93+
magvalue = mag.mag
94+
magtype = mag.magnitude_type
95+
magsrc = get_mag_src(mag)
96+
colname = '%s-%s' % (magsrc, magtype)
97+
if colname in row:
98+
continue
99+
row[colname] = magvalue
100+
return (row, msg)
101+
102+
25103
def read_phases(filename):
26104
"""Read a phase file CSV or Excel file into data structures.
27105

0 commit comments

Comments
 (0)