本文整理汇总了Python中obspy.core.event.Catalog类的典型用法代码示例。如果您正苦于以下问题:Python Catalog类的具体用法?Python Catalog怎么用?Python Catalog使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Catalog类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: read_phase
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: export_picks
def export_picks(self,
filename,
start_trace=None,
end_trace=None,
format="NLLOC_OBS",
debug=False,
**kwargs):
"""
"""
event_list = []
for trace in self.traces[start_trace:end_trace]:
event_list.extend([Event(picks=[pick]) for pick in trace.events])
# Export to desired format
if format == 'NLLOC_OBS':
basename, ext = os.path.splitext(filename)
for event in event_list:
ts = event.picks[0].time.strftime("%Y%m%d%H%M%S%f")
event_filename = "%s_%s%s" % (basename, ts, ext)
if debug:
print "Generating event file {}".format(event_filename)
event.write(event_filename, format=format)
else:
event_catalog = Catalog(event_list)
if debug:
print "Generating event file {}".format(filename)
event_catalog.write(filename, format=format, **kwargs)
示例3: _deserialize
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
示例4: test_countAndLen
def test_countAndLen(self):
"""
Tests the count and __len__ methods of the Catalog object.
"""
# empty catalog without events
catalog = Catalog()
self.assertEqual(len(catalog), 0)
self.assertEqual(catalog.count(), 0)
# catalog with events
catalog = read_events()
self.assertEqual(len(catalog), 3)
self.assertEqual(catalog.count(), 3)
示例5: parse_files
def parse_files(fnames):
"""Parses all given files for seiscomp xml"""
j = 0
out = Catalog()
for i, fname in enumerate(fnames):
print('read ' + fname)
out += readSeisComPEventXML0_6(fname)
if (i + 1) % 100 == 0 or i == len(fnames) - 1:
out_fname = str(j) + '.xml'
print('write %d events to %s\n' % (len(out), out_fname))
out.write(out_fname, 'QUAKEML')
out = Catalog()
j += 1
示例6: detections_to_catalog
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
示例7: catalog
def catalog(self):
"""
Add existing Event to a Catalog
"""
c = Catalog(events=[self.event])
c.creation_info = CreationInfo(
creation_time = UTCDateTime(),
agency_id = self.agency,
version = self.event.creation_info.version,
)
c.resource_id = self._rid(c)
return c
示例8: append_cmt_to_catalog
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
示例9: get_catalog
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
示例10: test_focal_mechanism_write_read
def test_focal_mechanism_write_read(self):
"""
Test for a bug in reading a FocalMechanism without MomentTensor from
QuakeML file. Makes sure that FocalMechanism.moment_tensor stays None
if no MomentTensor is in the file.
"""
memfile = io.BytesIO()
# create virtually empty FocalMechanism
fm = FocalMechanism()
event = Event(focal_mechanisms=[fm])
cat = Catalog(events=[event])
cat.write(memfile, format="QUAKEML", validate=True)
# now read again, and make sure there's no stub MomentTensor, but
# rather `None`
memfile.seek(0)
cat = read_events(memfile, format="QUAKEML")
self.assertEqual(cat[0].focal_mechanisms[0].moment_tensor, None)
示例11: _deserialize
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
示例12: test_seishub
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)
示例13: test_append
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])
示例14: test_issue_2339
def test_issue_2339(self):
"""
Make sure an empty EventDescription object does not prevent a catalog
from being saved to disk and re-read, while still being equal.
"""
# create a catalog with an empty event description
empty_description = EventDescription()
cat1 = Catalog(events=[read_events()[0]])
cat1[0].event_descriptions.append(empty_description)
# serialize the catalog using quakeml and re-read
bio = io.BytesIO()
cat1.write(bio, 'quakeml')
bio.seek(0)
cat2 = read_events(bio)
# the text of the empty EventDescription instances should be equal
text1 = cat1[0].event_descriptions[-1].text
text2 = cat2[0].event_descriptions[-1].text
self.assertEqual(text1, text2)
# the two catalogs should be equal
self.assertEqual(cat1, cat2)
示例15: test_avoid_empty_stub_elements
def test_avoid_empty_stub_elements(self):
"""
Test for a bug in reading QuakeML. Makes sure that some subelements do
not get assigned stub elements, but rather stay None.
"""
# Test 1: Test subelements of moment_tensor
memfile = io.BytesIO()
# create virtually empty FocalMechanism
mt = MomentTensor(derived_origin_id='smi:local/abc')
fm = FocalMechanism(moment_tensor=mt)
event = Event(focal_mechanisms=[fm])
cat = Catalog(events=[event])
cat.write(memfile, format="QUAKEML", validate=True)
# now read again, and make sure there's no stub subelements on
# MomentTensor, but rather `None`
memfile.seek(0)
cat = read_events(memfile, format="QUAKEML")
self.assertEqual(cat[0].focal_mechanisms[0].moment_tensor.tensor, None)
self.assertEqual(
cat[0].focal_mechanisms[0].moment_tensor.source_time_function,
None)
# Test 2: Test subelements of focal_mechanism
memfile = io.BytesIO()
# create virtually empty FocalMechanism
fm = FocalMechanism()
event = Event(focal_mechanisms=[fm])
cat = Catalog(events=[event])
cat.write(memfile, format="QUAKEML", validate=True)
# now read again, and make sure there's no stub MomentTensor, but
# rather `None`
memfile.seek(0)
cat = read_events(memfile, format="QUAKEML")
self.assertEqual(cat[0].focal_mechanisms[0].nodal_planes, None)
self.assertEqual(cat[0].focal_mechanisms[0].principal_axes, None)