本文整理汇总了Python中obspy.core.event.Catalog.append方法的典型用法代码示例。如果您正苦于以下问题:Python Catalog.append方法的具体用法?Python Catalog.append怎么用?Python Catalog.append使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类obspy.core.event.Catalog
的用法示例。
在下文中一共展示了Catalog.append方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: read_phase
# 需要导入模块: from obspy.core.event import Catalog [as 别名]
# 或者: from obspy.core.event.Catalog import append [as 别名]
def read_phase(ph_file):
"""
Read hypoDD phase files into Obspy catalog class.
:type ph_file: str
:param ph_file: Phase file to read event info from.
:returns: obspy.core.event.catlog
>>> from obspy.core.event.catalog import Catalog
>>> catalog = read_phase('eqcorrscan/tests/test_data/tunnel.phase')
>>> isinstance(catalog, Catalog)
True
"""
from obspy.core.event import Catalog
ph_catalog = Catalog()
f = open(ph_file, 'r')
# Topline of each event is marked by # in position 0
for line in f:
if line[0] == '#':
if 'event_text' not in locals():
event_text = {'header': line.rstrip(),
'picks': []}
else:
ph_catalog.append(_phase_to_event(event_text))
event_text = {'header': line.rstrip(),
'picks': []}
else:
event_text['picks'].append(line.rstrip())
ph_catalog.append(_phase_to_event(event_text))
return ph_catalog
示例2: _deserialize
# 需要导入模块: from obspy.core.event import Catalog [as 别名]
# 或者: from obspy.core.event.Catalog import append [as 别名]
def _deserialize(self, zmap_str):
catalog = Catalog()
for row in zmap_str.split('\n'):
if len(row) == 0:
continue
origin = Origin()
event = Event(origins=[origin])
event.preferred_origin_id = origin.resource_id.id
# Begin value extraction
columns = row.split('\t', 13)[:13] # ignore extra columns
values = dict(zip(_STD_ZMAP_COLUMNS + _EXT_ZMAP_COLUMNS, columns))
# Extract origin
origin.longitude = self._str2num(values.get('lon'))
origin.latitude = self._str2num(values.get('lat'))
depth = self._str2num(values.get('depth'))
if depth is not None:
origin.depth = depth * 1000.0
z_err = self._str2num(values.get('z_err'))
if z_err is not None:
origin.depth_errors.uncertainty = z_err * 1000.0
h_err = self._str2num(values.get('h_err'))
if h_err is not None:
ou = OriginUncertainty()
ou.horizontal_uncertainty = h_err
ou.preferred_description = 'horizontal uncertainty'
origin.origin_uncertainty = ou
year = self._str2num(values.get('year'))
if year is not None:
t_fields = ['year', 'month', 'day', 'hour', 'minute', 'second']
comps = [self._str2num(values.get(f)) for f in t_fields]
if year % 1 != 0:
origin.time = self._decyear2utc(year)
elif any(v > 0 for v in comps[1:]):
# no seconds involved
if len(comps) < 6:
utc_args = [int(v) for v in comps if v is not None]
# we also have to handle seconds
else:
utc_args = [int(v) if v is not None else 0
for v in comps[:-1]]
# just leave float seconds as is
utc_args.append(comps[-1])
origin.time = UTCDateTime(*utc_args)
mag = self._str2num(values.get('mag'))
# Extract magnitude
if mag is not None:
magnitude = Magnitude(mag=mag)
m_err = self._str2num(values.get('m_err'))
magnitude.mag_errors.uncertainty = m_err
event.magnitudes.append(magnitude)
event.preferred_magnitude_id = magnitude.resource_id.id
event.scope_resource_ids()
catalog.append(event)
return catalog
示例3: detections_to_catalog
# 需要导入模块: from obspy.core.event import Catalog [as 别名]
# 或者: from obspy.core.event.Catalog import append [as 别名]
def detections_to_catalog(detections):
r"""Helper to convert from list of detections to obspy catalog.
:type detections: list
:param detections: list of eqcorrscan.core.match_filter.detection
:returns: obspy.core.event.Catalog
"""
from obspy.core.event import Catalog
catalog = Catalog()
for detection in detections:
catalog.append(detection.event)
return catalog
示例4: append_cmt_to_catalog
# 需要导入模块: from obspy.core.event import Catalog [as 别名]
# 或者: from obspy.core.event.Catalog import append [as 别名]
def append_cmt_to_catalog(event_origin, cmt_to_add, tag="new_cmt",
author="Princeton GATG",
change_preferred_id=True):
"""
Add cmt to event. The cmt.resource_id will be appened tag to avoid
tag duplication problem in event.
:param event: the event that you want to add cmt in.
:type event: str, obspy.core.event.Event or obspy.core.event.Catalog
:param cmt: the cmt that you want to add to event.
:type event: str, obspy.core.event.Event or obspy.core.event.Catalog
:param change_preferred_id: change all preferred_id to the new added cmt
:type change_preferred_id: bool
:return: obspy.Catalog
"""
event = _parse_event(event_origin)
cmt_event = _parse_event(cmt_to_add)
if not isinstance(tag, str):
raise TypeError("tag(%s) should be type of str" % type(tag))
if not isinstance(author, str):
raise TypeError("author(%s) should be type of str" % type(author))
# User defined creation information
creation_info = CreationInfo(author=author, version=tag)
# add cmt origin
cmt_origin = prepare_cmt_origin(cmt_event, tag, creation_info)
event.origins.append(cmt_origin)
# add cmt magnitude
cmt_mag = prepare_cmt_mag(cmt_event, tag, cmt_origin.resource_id,
creation_info)
event.magnitudes.append(cmt_mag)
# add cmt focal mechanism
cmt_focal = prepare_cmt_focal(cmt_event, tag, cmt_origin.resource_id,
cmt_mag.resource_id, creation_info)
event.focal_mechanisms.append(cmt_focal)
# change preferred id if needed
if change_preferred_id:
event.preferred_origin_id = str(cmt_origin.resource_id)
event.preferred_magnitude_id = str(cmt_mag.resource_id)
event.preferred_focal_mechanism_id = str(cmt_focal.resource_id)
_validator(event, cmt_origin, cmt_mag, cmt_focal)
new_cat = Catalog()
new_cat.append(event)
return new_cat
示例5: get_catalog
# 需要导入模块: from obspy.core.event import Catalog [as 别名]
# 或者: from obspy.core.event.Catalog import append [as 别名]
def get_catalog(detections):
"""
Generate an obspy catalog from detections of DETECTION class.
:type detections: list
:param detections: list of eqcorrscan.core.match_filter.DETECTION
:returns: obspy.core.event.Catalog
"""
from obspy.core.event import Catalog
catalog = Catalog()
for detection in detections:
catalog.append(detection.event)
return catalog
示例6: _deserialize
# 需要导入模块: from obspy.core.event import Catalog [as 别名]
# 或者: from obspy.core.event.Catalog import append [as 别名]
def _deserialize(self):
catalog = Catalog()
res_id = '/'.join((res_id_prefix,
self.filename.replace(':', '/')))\
.replace('\\', '/').replace('//', '/')
catalog.resource_id = ResourceIdentifier(id=res_id)
catalog.description = 'Created from NEIC PDE mchedr format'
catalog.comments = ''
catalog.creation_info = CreationInfo(creation_time=UTCDateTime())
for line in self.fh.readlines():
# XXX: ugly, probably we should do everything in byte strings
# here? Is the pde / mchedr format unicode aware?
line = line.decode()
record_id = line[0:2]
if record_id == 'HY':
event = self._parse_record_hy(line)
catalog.append(event)
elif record_id == 'P ':
pick, arrival = self._parse_record_p(line, event)
elif record_id == 'E ':
self._parse_record_e(line, event)
elif record_id == 'L ':
self._parse_record_l(line, event)
elif record_id == 'A ':
self._parse_record_a(line, event)
elif record_id == 'C ':
self._parse_record_c(line, event)
elif record_id == 'AH':
self._parse_record_ah(line, event)
elif record_id == 'AE':
self._parse_record_ae(line, event)
elif record_id == 'Dp':
focal_mechanism = self._parse_record_dp(line, event)
elif record_id == 'Dt':
self._parse_record_dt(line, focal_mechanism)
elif record_id == 'Da':
self._parse_record_da(line, focal_mechanism)
elif record_id == 'Dc':
self._parse_record_dc(line, focal_mechanism)
elif record_id == 'M ':
self._parse_record_m(line, event, pick)
elif record_id == 'S ':
self._parse_record_s(line, event, pick, arrival)
self.fh.close()
# strip extra whitespaces from event comments
for event in catalog:
for comment in event.comments:
comment.text = comment.text.strip()
event.scope_resource_ids()
return catalog
示例7: _deserialize
# 需要导入模块: from obspy.core.event import Catalog [as 别名]
# 或者: from obspy.core.event.Catalog import append [as 别名]
def _deserialize(self):
catalog = Catalog()
res_id = "/".join((res_id_prefix, self.filename))
catalog.resource_id = ResourceIdentifier(id=res_id)
catalog.description = "Created from NEIC PDE mchedr format"
catalog.comments = ""
catalog.creation_info = CreationInfo(creation_time=UTCDateTime())
for line in self.fh.readlines():
# XXX: ugly, probably we should do everything in byte strings
# here? Is the pde / mchedr format unicode aware?
line = line.decode()
record_id = line[0:2]
if record_id == "HY":
event = self._parseRecordHY(line)
catalog.append(event)
elif record_id == "P ":
pick, arrival = self._parseRecordP(line, event)
elif record_id == "E ":
self._parseRecordE(line, event)
elif record_id == "L ":
self._parseRecordL(line, event)
elif record_id == "A ":
self._parseRecordA(line, event)
elif record_id == "C ":
self._parseRecordC(line, event)
elif record_id == "AH":
self._parseRecordAH(line, event)
elif record_id == "AE":
self._parseRecordAE(line, event)
elif record_id == "Dp":
focal_mechanism = self._parseRecordDp(line, event)
elif record_id == "Dt":
self._parseRecordDt(line, focal_mechanism)
elif record_id == "Da":
self._parseRecordDa(line, focal_mechanism)
elif record_id == "Dc":
self._parseRecordDc(line, focal_mechanism)
elif record_id == "M ":
self._parseRecordM(line, event, pick)
elif record_id == "S ":
self._parseRecordS(line, event, pick, arrival)
self.fh.close()
# strip extra whitespaces from event comments
for event in catalog:
for comment in event.comments:
comment.text = comment.text.strip()
return catalog
示例8: _deserialize
# 需要导入模块: from obspy.core.event import Catalog [as 别名]
# 或者: from obspy.core.event.Catalog import append [as 别名]
def _deserialize(self, zmap_str):
catalog = Catalog()
for row in zmap_str.split("\n"):
if len(row) == 0:
continue
origin = Origin()
event = Event(origins=[origin])
event.preferred_origin_id = origin.resource_id.id
# Begin value extraction
columns = row.split("\t", 13)[:13] # ignore extra columns
values = dict(zip(_STD_ZMAP_COLUMNS + _EXT_ZMAP_COLUMNS, columns))
# Extract origin
origin.longitude = self._str2num(values.get("lon"))
origin.latitude = self._str2num(values.get("lat"))
depth = self._str2num(values.get("depth"))
if depth is not None:
origin.depth = depth * 1000.0
z_err = self._str2num(values.get("z_err"))
if z_err is not None:
origin.depth_errors.uncertainty = z_err * 1000.0
h_err = self._str2num(values.get("h_err"))
if h_err is not None:
ou = OriginUncertainty()
ou.horizontal_uncertainty = h_err
ou.preferred_description = "horizontal uncertainty"
origin.origin_uncertainty = ou
year = self._str2num(values.get("year"))
if year is not None:
t_fields = ["year", "month", "day", "hour", "minute", "second"]
comps = [self._str2num(values.get(f)) for f in t_fields]
if year % 1 != 0:
origin.time = self._decyear2utc(year)
elif any(v > 0 for v in comps[1:]):
utc_args = [int(v) for v in comps if v is not None]
origin.time = UTCDateTime(*utc_args)
mag = self._str2num(values.get("mag"))
# Extract magnitude
if mag is not None:
magnitude = Magnitude(mag=mag)
m_err = self._str2num(values.get("m_err"))
magnitude.mag_errors.uncertainty = m_err
event.magnitudes.append(magnitude)
event.preferred_magnitude_id = magnitude.resource_id.id
catalog.append(event)
return catalog
示例9: test_seishub
# 需要导入模块: from obspy.core.event import Catalog [as 别名]
# 或者: from obspy.core.event.Catalog import append [as 别名]
def test_seishub(self):
"""Test the seishub method, use obspy default seishub client."""
from obspy.core.event import Catalog, Event, Origin, Pick
from obspy.core.event import WaveformStreamID
from obspy import UTCDateTime
import warnings
from future import standard_library
with standard_library.hooks():
from urllib.request import URLError
t = UTCDateTime(2009, 9, 3)
test_cat = Catalog()
test_cat.append(Event())
test_cat[0].origins.append(Origin())
test_cat[0].origins[0].time = t
test_cat[0].origins[0].latitude = 45
test_cat[0].origins[0].longitude = 45
test_cat[0].origins[0].depth = 5000
test_cat[0].\
picks.append(Pick(waveform_id=WaveformStreamID(station_code='MANZ',
channel_code='EHZ',
network_code='BW'),
phase_hint='PG', time=t + 2000))
test_cat[0].\
picks.append(Pick(waveform_id=WaveformStreamID(station_code='MANZ',
channel_code='EHN',
network_code='BW'),
phase_hint='SG', time=t + 2005))
test_cat[0].\
picks.append(Pick(waveform_id=WaveformStreamID(station_code='MANZ',
channel_code='EHE',
network_code='BW'),
phase_hint='SG', time=t + 2005.5))
test_url = 'http://teide.geophysik.uni-muenchen.de:8080'
try:
template = from_seishub(test_cat, url=test_url, lowcut=1.0,
highcut=5.0, samp_rate=20, filt_order=4,
length=3, prepick=0.5, swin='all')
except URLError:
warnings.warn('Timed out connection to seishub')
if 'template' in locals():
self.assertEqual(len(template), 3)
示例10: test_append
# 需要导入模块: from obspy.core.event import Catalog [as 别名]
# 或者: from obspy.core.event.Catalog import append [as 别名]
def test_append(self):
"""
Tests the append method of the Catalog object.
"""
# 1 - create catalog and add a few events
catalog = Catalog()
event1 = Event()
event2 = Event()
self.assertEqual(len(catalog), 0)
catalog.append(event1)
self.assertEqual(len(catalog), 1)
self.assertEqual(catalog.events, [event1])
catalog.append(event2)
self.assertEqual(len(catalog), 2)
self.assertEqual(catalog.events, [event1, event2])
# 2 - adding objects other as Event should fails
self.assertRaises(TypeError, catalog.append, str)
self.assertRaises(TypeError, catalog.append, Catalog)
self.assertRaises(TypeError, catalog.append, [event1])
示例11: convert_dmteventfile
# 需要导入模块: from obspy.core.event import Catalog [as 别名]
# 或者: from obspy.core.event.Catalog import append [as 别名]
def convert_dmteventfile():
eventsfile1 = os.path.join(conf.dmt_path, 'EVENT', 'event_list')
eventsfile2 = os.path.join(conf.dmt_path, 'EVENT', 'events.xml')
with open(eventsfile1) as f:
events1 = pickle.load(f)
events2 = Catalog()
for ev in events1:
orkw = {'time': ev['datetime'],
'latitude': ev['latitude'],
'longitude': ev['longitude'],
'depth': ev['depth']}
magkw = {'mag': ev['magnitude'],
'magnitude_type': ev['magnitude_type']}
evdesargs = (ev['flynn_region'], 'Flinn-Engdahl region')
evkw = {'resource_id': ev['event_id'],
'event_type': 'earthquake',
'creation_info': CreationInfo(author=ev['author']),
'event_descriptions': [EventDescription(*evdesargs)],
'origins': [Origin(**orkw)],
'magnitudes': [Magnitude(**magkw)]}
events2.append(Event(**evkw))
events2.write(eventsfile2, 'QUAKEML')
示例12: sfiles_to_event
# 需要导入模块: from obspy.core.event import Catalog [as 别名]
# 或者: from obspy.core.event.Catalog import append [as 别名]
def sfiles_to_event(sfile_list):
"""
Function to write out an event.dat file of the events
:type sfile_list: list
:param sfile_list: List of s-files to sort and put into the database
:returns: List of tuples of event ID (int) and Sfile name
"""
from obspy.core.event import Catalog
event_list = []
sort_list = [(sfile_util.readheader(sfile).origins[0].time, sfile)
for sfile in sfile_list]
sort_list.sort(key=lambda tup: tup[0])
sfile_list = [sfile[1] for sfile in sort_list]
catalog = Catalog()
for i, sfile in enumerate(sfile_list):
event_list.append((i, sfile))
catalog.append(sfile_util.readheader(sfile))
# Hand off to sister function
write_event(catalog)
return event_list
示例13: event_to_quakeml
# 需要导入模块: from obspy.core.event import Catalog [as 别名]
# 或者: from obspy.core.event.Catalog import append [as 别名]
def event_to_quakeml(event, filename):
"""
Write one of those events to QuakeML.
"""
# Create all objects.
cat = Catalog()
ev = Event()
org = Origin()
mag = Magnitude()
fm = FocalMechanism()
mt = MomentTensor()
t = Tensor()
# Link them together.
cat.append(ev)
ev.origins.append(org)
ev.magnitudes.append(mag)
ev.focal_mechanisms.append(fm)
fm.moment_tensor = mt
mt.tensor = t
# Fill values
ev.resource_id = "smi:inversion/%s" % str(event["identifier"])
org.time = event["time"]
org.longitude = event["longitude"]
org.latitude = event["latitude"]
org.depth = event["depth_in_km"] * 1000
mag.mag = event["Mw"]
mag.magnitude_type = "Mw"
t.m_rr = event["Mrr"]
t.m_tt = event["Mpp"]
t.m_pp = event["Mtt"]
t.m_rt = event["Mrt"]
t.m_rp = event["Mrp"]
t.m_tp = event["Mtp"]
cat.write(filename, format="quakeml")
示例14: request_gcmt
# 需要导入模块: from obspy.core.event import Catalog [as 别名]
# 或者: from obspy.core.event.Catalog import append [as 别名]
def request_gcmt(starttime, endtime, minmagnitude=None, mindepth=None, maxdepth=None, minlatitude=None, maxlatitude=None, minlongitude=None, maxlongitude=None):
import mechanize
from mechanize import Browser
import re
"""
Description
I am using mechanize. My attempt is just preliminary, for the current globalcmt.org site.
"""
#Split numbers and text
r = re.compile("([a-zA-Z]+)([0-9]+)")
br = Browser()
br.open('http://www.globalcmt.org/CMTsearch.html')
#Site has just one form
br.select_form(nr=0)
br.form['yr'] = str(starttime.year)
br.form['mo'] = str(starttime.month)
br.form['day'] = str(starttime.day)
br.form['oyr'] = str(endtime.year)
br.form['omo'] = str(endtime.month)
br.form['oday'] = str(endtime.day)
br.form['list'] = ['4']
br.form['itype'] = ['ymd']
br.form['otype'] = ['ymd']
if minmagnitude: br.form['lmw'] = str(minmagnitude)
if minlatitude : br.form['llat'] = str(minlatitude)
if maxlatitude : br.form['ulat'] = str(maxlatitude)
if minlongitude: br.form['llon'] = str(minlongitude)
if maxlongitude: br.form['ulon'] = str(maxlongitude)
if mindepth : br.form['lhd'] = str(mindepth)
if maxdepth : br.form['uhd'] = str(maxdepth)
print("Submitting parameters to globalcmt.")
req = br.submit()
print("Retrieving data, creating catalog.")
data = []
for line in req:
data.append(line)
data_chunked = _chunking_list(keyword='\n', list=data)
origins = []
magnitudes = []
tensor = []
for line in data_chunked:
for element in line:
if 'event name' in element:
for content in element:
org = line[1].split()
year = int(r.match(org[0]).groups()[1])
mon = int(org[1])
day = int(org[2])
hour = int(org[3])
minute = int(org[4])
sec_temp = int(org[5].split('.')[0])
msec_temp = int(org[5].split('.')[1])
origins_temp = UTCDateTime(year, mon, day, hour, minute, sec_temp, msec_temp)
#adding time shift located in line[3]
origin = origins_temp + float(line[3].split()[2])
magnitude = float(line[1].split()[10])
latitude = float(line[5].split()[1])
longitude = float(line[6].split()[1])
depth = 1000. * float(line[7].split()[1])
m_rr = float(line[8].split()[1])
m_tt = float(line[9].split()[1])
m_pp = float(line[10].split()[1])
m_rt = float(line[11].split()[1])
m_rp = float(line[12].split()[1])
m_tp = float(line[13].split()[1])
magnitudes.append( ("Mw", magnitude) )
origins.append( (latitude, longitude, depth, origin) )
tensor.append( (m_rr, m_tt, m_pp, m_rt, m_rp, m_tp) )
cat = Catalog()
for mag, org, ten in zip(magnitudes, origins, tensor):
# Create magnitude object.
magnitude = Magnitude()
magnitude.magnitude_type = mag[0]
magnitude.mag = mag[1]
# Write origin object.
origin = Origin()
origin.latitude = org[0]
origin.longitude = org[1]
origin.depth = org[2]
origin.time = org[3]
# Create event object and append to catalog object.
event = Event()
event.magnitudes.append(magnitude)
event.origins.append(origin)
#.........这里部分代码省略.........
示例15: match_filter
# 需要导入模块: from obspy.core.event import Catalog [as 别名]
# 或者: from obspy.core.event.Catalog import append [as 别名]
#.........这里部分代码省略.........
from obspy.core.event import Event, Pick, CreationInfo, ResourceIdentifier
from obspy.core.event import Comment, WaveformStreamID
import time
if arg_check:
# Check the arguments to be nice - if arguments wrong type the parallel
# output for the error won't be useful
if not type(template_names) == list:
raise IOError('template_names must be of type: list')
if not type(template_list) == list:
raise IOError('templates must be of type: list')
for template in template_list:
if not type(template) == Stream:
msg = 'template in template_list must be of type: ' +\
'obspy.core.stream.Stream'
raise IOError(msg)
if not type(st) == Stream:
msg = 'st must be of type: obspy.core.stream.Stream'
raise IOError(msg)
if threshold_type not in ['MAD', 'absolute', 'av_chan_corr']:
msg = 'threshold_type must be one of: MAD, absolute, av_chan_corr'
raise IOError(msg)
# Copy the stream here because we will muck about with it
stream = st.copy()
templates = copy.deepcopy(template_list)
# Debug option to confirm that the channel names match those in the
# templates
if debug >= 2:
template_stachan = []
data_stachan = []
for template in templates:
for tr in template:
template_stachan.append(tr.stats.station + '.' +
tr.stats.channel)
for tr in stream:
data_stachan.append(tr.stats.station + '.' + tr.stats.channel)
template_stachan = list(set(template_stachan))
data_stachan = list(set(data_stachan))
if debug >= 3:
print('I have template info for these stations:')
print(template_stachan)
print('I have daylong data for these stations:')
print(data_stachan)
# Perform a check that the daylong vectors are daylong
for tr in stream:
if not tr.stats.sampling_rate * 86400 == tr.stats.npts:
msg = ' '.join(['Data are not daylong for', tr.stats.station,
tr.stats.channel])
raise ValueError(msg)
# Perform check that all template lengths are internally consistent
for i, temp in enumerate(template_list):
if len(set([tr.stats.npts for tr in temp])) > 1:
msg = 'Template %s contains traces of differing length!! THIS \
WILL CAUSE ISSUES' % template_names[i]
raise ValueError(msg)
# Call the _template_loop function to do all the correlation work
outtic = time.clock()
# Edit here from previous, stable, but slow match_filter
# Would be worth testing without an if statement, but with every station in
# the possible template stations having data, but for those without real
# data make the data NaN to return NaN ccc_sum
# Note: this works
if debug >= 2:
print('Ensuring all template channels have matches in daylong data')
template_stachan = []