本文整理汇总了Python中obspy.core.event.Event.preferred_origin_id方法的典型用法代码示例。如果您正苦于以下问题:Python Event.preferred_origin_id方法的具体用法?Python Event.preferred_origin_id怎么用?Python Event.preferred_origin_id使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类obspy.core.event.Event
的用法示例。
在下文中一共展示了Event.preferred_origin_id方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _deserialize
# 需要导入模块: from obspy.core.event import Event [as 别名]
# 或者: from obspy.core.event.Event import preferred_origin_id [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
示例2: _deserialize
# 需要导入模块: from obspy.core.event import Event [as 别名]
# 或者: from obspy.core.event.Event import preferred_origin_id [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
示例3: _parse_event
# 需要导入模块: from obspy.core.event import Event [as 别名]
# 或者: from obspy.core.event.Event import preferred_origin_id [as 别名]
def _parse_event(self, first_line):
"""
Parse an event.
:type first_line: str
:param first_line: First line of an event block, which contains
the event id.
:rtype: :class:`~obspy.core.event.event.Event`
:return: The parsed event or None.
"""
event_id = first_line[5:].strip()
# Skip event without id
if not event_id:
self._warn('Missing event id')
return None
event = Event()
origin, origin_res_id = self._parse_origin(event)
# Skip event without origin
if not origin:
return None
line = self._skip_empty_lines()
self._parse_region_name(line, event)
self._parse_arrivals(event, origin, origin_res_id)
# Origin ResourceIdentifier should be set at the end, when
# Arrivals are already set.
origin.resource_id = origin_res_id
event.origins.append(origin)
event.preferred_origin_id = origin.resource_id.id
# Must be done after the origin parsing
event.creation_info = self._get_creation_info()
public_id = "event/%s" % event_id
event.resource_id = self._get_res_id(public_id)
event.scope_resource_ids()
return event
示例4: _read_single_hypocenter
# 需要导入模块: from obspy.core.event import Event [as 别名]
# 或者: from obspy.core.event.Event import preferred_origin_id [as 别名]
def _read_single_hypocenter(lines, coordinate_converter, original_picks):
"""
Given a list of lines (starting with a 'NLLOC' line and ending with a
'END_NLLOC' line), parse them into an Event.
"""
try:
# some paranoid checks..
assert lines[0].startswith("NLLOC ")
assert lines[-1].startswith("END_NLLOC")
for line in lines[1:-1]:
assert not line.startswith("NLLOC ")
assert not line.startswith("END_NLLOC")
except Exception:
msg = ("This should not have happened, please report this as a bug at "
"https://github.com/obspy/obspy/issues.")
raise Exception(msg)
indices_phases = [None, None]
for i, line in enumerate(lines):
if line.startswith("PHASE "):
indices_phases[0] = i
elif line.startswith("END_PHASE"):
indices_phases[1] = i
# extract PHASES lines (if any)
if any(indices_phases):
if not all(indices_phases):
msg = ("NLLOC HYP file seems corrupt, 'PHASE' block is corrupt.")
raise RuntimeError(msg)
i1, i2 = indices_phases
lines, phases_lines = lines[:i1] + lines[i2 + 1:], lines[i1 + 1:i2]
else:
phases_lines = []
lines = dict([line.split(None, 1) for line in lines[:-1]])
line = lines["SIGNATURE"]
line = line.rstrip().split('"')[1]
signature, version, date, time = line.rsplit(" ", 3)
# new NLLoc > 6.0 seems to add prefix 'run:' before date
if date.startswith('run:'):
date = date[4:]
signature = signature.strip()
creation_time = UTCDateTime.strptime(date + time, str("%d%b%Y%Hh%Mm%S"))
if coordinate_converter:
# maximum likelihood origin location in km info line
line = lines["HYPOCENTER"]
x, y, z = coordinate_converter(*map(float, line.split()[1:7:2]))
else:
# maximum likelihood origin location lon lat info line
line = lines["GEOGRAPHIC"]
y, x, z = map(float, line.split()[8:13:2])
# maximum likelihood origin time info line
line = lines["GEOGRAPHIC"]
year, mon, day, hour, min = map(int, line.split()[1:6])
seconds = float(line.split()[6])
time = UTCDateTime(year, mon, day, hour, min, seconds, strict=False)
# distribution statistics line
line = lines["STATISTICS"]
covariance_xx = float(line.split()[7])
covariance_yy = float(line.split()[13])
covariance_zz = float(line.split()[17])
stats_info_string = str(
"Note: Depth/Latitude/Longitude errors are calculated from covariance "
"matrix as 1D marginal (Lon/Lat errors as great circle degrees) "
"while OriginUncertainty min/max horizontal errors are calculated "
"from 2D error ellipsoid and are therefore seemingly higher compared "
"to 1D errors. Error estimates can be reconstructed from the "
"following original NonLinLoc error statistics line:\nSTATISTICS " +
lines["STATISTICS"])
# goto location quality info line
line = lines["QML_OriginQuality"].split()
(assoc_phase_count, used_phase_count, assoc_station_count,
used_station_count, depth_phase_count) = map(int, line[1:11:2])
stderr, az_gap, sec_az_gap = map(float, line[11:17:2])
gt_level = line[17]
min_dist, max_dist, med_dist = map(float, line[19:25:2])
# goto location quality info line
line = lines["QML_OriginUncertainty"]
if "COMMENT" in lines:
comment = lines["COMMENT"].strip()
comment = comment.strip('\'"')
comment = comment.strip()
hor_unc, min_hor_unc, max_hor_unc, hor_unc_azim = \
map(float, line.split()[1:9:2])
# assign origin info
event = Event()
o = Origin()
event.origins = [o]
event.preferred_origin_id = o.resource_id
#.........这里部分代码省略.........
示例5: _read_ndk
# 需要导入模块: from obspy.core.event import Event [as 别名]
# 或者: from obspy.core.event.Event import preferred_origin_id [as 别名]
#.........这里部分代码省略.........
comments=[Comment(text="Hypocenter catalog: %s" %
record["hypocenter_reference_catalog"],
force_resource_id=False)]
)
ref_origin.comments[0].resource_id = _get_resource_id(
record["cmt_event_name"], "comment", tag="ref_origin")
ref_origin.resource_id = _get_resource_id(record["cmt_event_name"],
"origin", tag="reforigin")
cmt_origin = Origin(
force_resource_id=False,
longitude=record["centroid_longitude"],
longitude_errors={
"uncertainty": record["centroid_longitude_error"]},
latitude=record["centroid_latitude"],
latitude_errors={
"uncertainty": record["centroid_latitude_error"]},
# Convert to m.
depth=record["centroid_depth_in_km"] * 1000.0,
depth_errors={
"uncertainty": record["centroid_depth_in_km_error"] * 1000},
time=ref_origin["time"] + record["centroid_time"],
time_errors={"uncertainty": record["centroid_time_error"]},
depth_type=record["type_of_centroid_depth"],
origin_type="centroid",
time_fixed=False,
epicenter_fixed=False,
creation_info=creation_info.copy()
)
cmt_origin.resource_id = _get_resource_id(record["cmt_event_name"],
"origin",
tag="cmtorigin")
event.origins = [ref_origin, cmt_origin]
event.preferred_origin_id = cmt_origin.resource_id.id
# Create the magnitude object.
mag = Magnitude(
force_resource_id=False,
mag=round(record["Mw"], 2),
magnitude_type="Mwc",
origin_id=cmt_origin.resource_id,
creation_info=creation_info.copy()
)
mag.resource_id = _get_resource_id(record["cmt_event_name"],
"magnitude", tag="moment_mag")
event.magnitudes = [mag]
event.preferred_magnitude_id = mag.resource_id.id
# Add the reported mb, MS magnitudes as additional magnitude objects.
event.magnitudes.append(Magnitude(
force_resource_id=False,
mag=record["mb"],
magnitude_type="mb",
comments=[Comment(
force_resource_id=False,
text="Reported magnitude in NDK file. Most likely 'mb'."
)]
))
event.magnitudes[-1].comments[-1].resource_id = _get_resource_id(
record["cmt_event_name"], "comment", tag="mb_magnitude")
event.magnitudes[-1].resource_id = _get_resource_id(
record["cmt_event_name"], "magnitude", tag="mb")
event.magnitudes.append(Magnitude(
force_resource_id=False,
mag=record["MS"],
示例6: _readheader
# 需要导入模块: from obspy.core.event import Event [as 别名]
# 或者: from obspy.core.event.Event import preferred_origin_id [as 别名]
def _readheader(f):
"""
Internal header reader.
:type f: file
:param f: File open in read-mode.
:returns: :class:`~obspy.core.event.event.Event`
"""
f.seek(0)
# Base populate to allow for empty parts of file
new_event = Event()
topline = _get_headline(f=f)
if not topline:
raise NordicParsingError('No header found, or incorrect '
'formatting: corrupt s-file')
try:
sfile_seconds = int(topline[16:18])
if sfile_seconds == 60:
sfile_seconds = 0
add_seconds = 60
else:
add_seconds = 0
new_event.origins.append(Origin())
new_event.origins[0].time = UTCDateTime(int(topline[1:5]),
int(topline[6:8]),
int(topline[8:10]),
int(topline[11:13]),
int(topline[13:15]),
sfile_seconds,
int(topline[19:20]) *
100000)\
+ add_seconds
except:
NordicParsingError("Couldn't read a date from sfile")
# new_event.loc_mod_ind=topline[20]
new_event.event_descriptions.append(EventDescription())
new_event.event_descriptions[0].text = topline[21:23]
# new_event.ev_id=topline[22]
try:
new_event.origins[0].latitude = float(topline[23:30])
new_event.origins[0].longitude = float(topline[31:38])
new_event.origins[0].depth = float(topline[39:43]) * 1000
except ValueError:
# The origin 'requires' a lat & long
new_event.origins[0].latitude = None
new_event.origins[0].longitude = None
new_event.origins[0].depth = None
# new_event.depth_ind = topline[44]
# new_event.loc_ind = topline[45]
new_event.creation_info = CreationInfo(agency_id=topline[45:48].strip())
ksta = Comment(text='Number of stations=' + topline[49:51].strip())
new_event.origins[0].comments.append(ksta)
if _float_conv(topline[51:55]) is not None:
new_event.origins[0].time_errors['Time_Residual_RMS'] = \
_float_conv(topline[51:55])
# Read in magnitudes if they are there.
for index in [59, 67, 75]:
if not topline[index].isspace():
new_event.magnitudes.append(Magnitude())
new_event.magnitudes[-1].mag = _float_conv(
topline[index - 3:index])
new_event.magnitudes[-1].magnitude_type = \
_nortoevmag(topline[index])
new_event.magnitudes[-1].creation_info = \
CreationInfo(agency_id=topline[index + 1:index + 4].strip())
new_event.magnitudes[-1].origin_id = new_event.origins[0].\
resource_id
# Set the useful things like preferred magnitude and preferred origin
new_event.preferred_origin_id = new_event.origins[0].resource_id
try:
# Select moment first, then local, then
mag_filter = ['MW', 'Mw', 'ML', 'Ml', 'MB', 'Mb',
'MS', 'Ms', 'MC', 'Mc']
_magnitudes = [(m.magnitude_type, m.resource_id)
for m in new_event.magnitudes]
preferred_magnitude = sorted(_magnitudes,
key=lambda x: mag_filter.index(x[0]))[0]
new_event.preferred_magnitude_id = preferred_magnitude[1]
except (ValueError, IndexError):
# If there is a magnitude not specified in filter
try:
new_event.preferred_magnitude_id = new_event.magnitudes[0].\
resource_id
except IndexError:
pass
return new_event
示例7: __read_single_fnetmt_entry
# 需要导入模块: from obspy.core.event import Event [as 别名]
# 或者: from obspy.core.event.Event import preferred_origin_id [as 别名]
def __read_single_fnetmt_entry(line, **kwargs):
"""
Reads a single F-net moment tensor solution to a
:class:`~obspy.core.event.Event` object.
:param line: String containing moment tensor information.
:type line: str.
"""
a = line.split()
try:
ot = UTCDateTime().strptime(a[0], '%Y/%m/%d,%H:%M:%S.%f')
except ValueError:
ot = UTCDateTime().strptime(a[0], '%Y/%m/%d,%H:%M:%S')
lat, lon, depjma, magjma = map(float, a[1:5])
depjma *= 1000
region = a[5]
strike = tuple(map(int, a[6].split(';')))
dip = tuple(map(int, a[7].split(';')))
rake = tuple(map(int, a[8].split(';')))
mo = float(a[9])
depmt = float(a[10]) * 1000
magmt = float(a[11])
var_red = float(a[12])
mxx, mxy, mxz, myy, myz, mzz, unit = map(float, a[13:20])
event_name = util.gen_sc3_id(ot)
e = Event(event_type="earthquake")
e.resource_id = _get_resource_id(event_name, 'event')
# Standard JMA solution
o_jma = Origin(time=ot, latitude=lat, longitude=lon,
depth=depjma, depth_type="from location",
region=region)
o_jma.resource_id = _get_resource_id(event_name,
'origin', 'JMA')
m_jma = Magnitude(mag=magjma, magnitude_type='ML',
origin_id=o_jma.resource_id)
m_jma.resource_id = _get_resource_id(event_name,
'magnitude', 'JMA')
# MT solution
o_mt = Origin(time=ot, latitude=lat, longitude=lon,
depth=depmt, region=region,
depth_type="from moment tensor inversion")
o_mt.resource_id = _get_resource_id(event_name,
'origin', 'MT')
m_mt = Magnitude(mag=magmt, magnitude_type='Mw',
origin_id=o_mt.resource_id)
m_mt.resource_id = _get_resource_id(event_name,
'magnitude', 'MT')
foc_mec = FocalMechanism(triggering_origin_id=o_jma.resource_id)
foc_mec.resource_id = _get_resource_id(event_name,
"focal_mechanism")
nod1 = NodalPlane(strike=strike[0], dip=dip[0], rake=rake[0])
nod2 = NodalPlane(strike=strike[1], dip=dip[1], rake=rake[1])
nod = NodalPlanes(nodal_plane_1=nod1, nodal_plane_2=nod2)
foc_mec.nodal_planes = nod
tensor = Tensor(m_rr=mxx, m_tt=myy, m_pp=mzz, m_rt=mxy, m_rp=mxz, m_tp=myz)
cm = Comment(text="Basis system: North,East,Down (Jost and \
Herrmann 1989")
cm.resource_id = _get_resource_id(event_name, 'comment', 'mt')
mt = MomentTensor(derived_origin_id=o_mt.resource_id,
moment_magnitude_id=m_mt.resource_id,
scalar_moment=mo, comments=[cm],
tensor=tensor, variance_reduction=var_red)
mt.resource_id = _get_resource_id(event_name,
'moment_tensor')
foc_mec.moment_tensor = mt
e.origins = [o_jma, o_mt]
e.magnitudes = [m_jma, m_mt]
e.focal_mechanisms = [foc_mec]
e.preferred_magnitude_id = m_mt.resource_id.id
e.preferred_origin_id = o_mt.resource_id.id
e.preferred_focal_mechanism_id = foc_mec.resource_id.id
return e
示例8: __read_single_cmtsolution
# 需要导入模块: from obspy.core.event import Event [as 别名]
# 或者: from obspy.core.event.Event import preferred_origin_id [as 别名]
#.........这里部分代码省略.........
"depth", "m_rr", "m_tt", "m_pp", "m_rt", "m_rp", "m_tp"]
cmt_values = {_i: float(buf.readline().strip().split()[-1])
for _i in values}
# Moment magnitude calculation in dyne * cm.
m_0 = 1.0 / math.sqrt(2.0) * math.sqrt(
cmt_values["m_rr"] ** 2 +
cmt_values["m_tt"] ** 2 +
cmt_values["m_pp"] ** 2 +
2.0 * cmt_values["m_rt"] ** 2 +
2.0 * cmt_values["m_rp"] ** 2 +
2.0 * cmt_values["m_tp"] ** 2)
m_w = 2.0 / 3.0 * (math.log10(m_0) - 16.1)
# Convert to meters.
cmt_values["depth"] *= 1000.0
# Convert to Newton meter.
values = ["m_rr", "m_tt", "m_pp", "m_rt", "m_rp", "m_tp"]
for value in values:
cmt_values[value] /= 1E7
cmt_origin = Origin(
resource_id=_get_resource_id(event_name, "origin", tag="cmt"),
time=origin_time + cmt_values["time_shift"],
longitude=cmt_values["longitude"],
latitude=cmt_values["latitude"],
depth=cmt_values["depth"],
origin_type="centroid",
# Could rarely be different than the epicentral region.
region=_fe.get_region(longitude=cmt_values["longitude"],
latitude=cmt_values["latitude"])
# No evaluation status as it could be any of several and the file
# format does not provide that information.
)
cmt_mag = Magnitude(
resource_id=_get_resource_id(event_name, "magnitude", tag="mw"),
# Round to 2 digits.
mag=round(m_w, 2),
magnitude_type="mw",
origin_id=cmt_origin.resource_id
)
foc_mec = FocalMechanism(
resource_id=_get_resource_id(event_name, "focal_mechanism"),
# The preliminary origin most likely triggered the focal mechanism
# determination.
triggering_origin_id=preliminary_origin.resource_id
)
tensor = Tensor(
m_rr=cmt_values["m_rr"],
m_pp=cmt_values["m_pp"],
m_tt=cmt_values["m_tt"],
m_rt=cmt_values["m_rt"],
m_rp=cmt_values["m_rp"],
m_tp=cmt_values["m_tp"]
)
# Source time function is a triangle, according to the SPECFEM manual.
stf = SourceTimeFunction(
type="triangle",
# The duration is twice the half duration.
duration=2.0 * cmt_values["half_duration"]
)
mt = MomentTensor(
resource_id=_get_resource_id(event_name, "moment_tensor"),
derived_origin_id=cmt_origin.resource_id,
moment_magnitude_id=cmt_mag.resource_id,
# Convert to Nm.
scalar_moment=m_0 / 1E7,
tensor=tensor,
source_time_function=stf
)
# Assemble everything.
foc_mec.moment_tensor = mt
ev = Event(resource_id=_get_resource_id(event_name, "event"),
event_type="earthquake")
ev.event_descriptions.append(EventDescription(text=event_name,
type="earthquake name"))
ev.comments.append(Comment(
text="Hypocenter catalog: %s" % hypocenter_catalog,
force_resource_id=False))
ev.origins.append(cmt_origin)
ev.origins.append(preliminary_origin)
ev.magnitudes.append(cmt_mag)
ev.magnitudes.append(preliminary_bw_magnitude)
ev.magnitudes.append(preliminary_sw_magnitude)
ev.focal_mechanisms.append(foc_mec)
# Set the preferred items.
ev.preferred_origin_id = cmt_origin.resource_id.id
ev.preferred_magnitude_id = cmt_mag.resource_id.id
ev.preferred_focal_mechanism_id = foc_mec.resource_id.id
return ev
示例9: readheader
# 需要导入模块: from obspy.core.event import Event [as 别名]
# 或者: from obspy.core.event.Event import preferred_origin_id [as 别名]
#.........这里部分代码省略.........
f.seek(0)
for line in f:
if line[79] in [' ', '1']:
topline = line
break
if line[79] == '7':
raise IOError('No header found, corrupt s-file?')
try:
sfile_seconds = int(topline[16:18])
if sfile_seconds == 60:
sfile_seconds = 0
add_seconds = 60
else:
add_seconds = 0
new_event.origins.append(Origin())
new_event.origins[0].time = UTCDateTime(int(topline[1:5]),
int(topline[6:8]),
int(topline[8:10]),
int(topline[11:13]),
int(topline[13:15]),
sfile_seconds,
int(topline[19:20]) *
100000)\
+ add_seconds
except:
warnings.warn("Couldn't read a date from sfile: " + sfile)
new_event.origins.append(Origin(time=UTCDateTime(0)))
# new_event.loc_mod_ind=topline[20]
new_event.event_descriptions.append(EventDescription())
new_event.event_descriptions[0].text = topline[21:23]
# new_event.ev_id=topline[22]
if not _float_conv(topline[23:30]) == 999:
new_event.origins[0].latitude = _float_conv(topline[23:30])
new_event.origins[0].longitude = _float_conv(topline[31:38])
new_event.origins[0].depth = _float_conv(topline[39:43]) * 1000
else:
# The origin 'requires' a lat & long
new_event.origins[0].latitude = float('NaN')
new_event.origins[0].longitude = float('NaN')
new_event.origins[0].depth = float('NaN')
# new_event.depth_ind = topline[44]
# new_event.loc_ind = topline[45]
new_event.creation_info = CreationInfo(agency_id=topline[45:48].
strip())
ksta = Comment(text='Number of stations=' +
topline[49:51].strip())
new_event.origins[0].comments.append(ksta)
# new_event.origins[0].nsta??? = _int_conv(topline[49:51])
if not _float_conv(topline[51:55]) == 999:
new_event.origins[0].time_errors['Time_Residual_RMS'] = \
_float_conv(topline[51:55])
# Read in magnitudes if they are there.
if len(topline[59].strip()) > 0:
new_event.magnitudes.append(Magnitude())
new_event.magnitudes[0].mag = _float_conv(topline[56:59])
new_event.magnitudes[0].magnitude_type = topline[59]
new_event.magnitudes[0].creation_info = \
CreationInfo(agency_id=topline[60:63].strip())
new_event.magnitudes[0].origin_id = new_event.origins[0].\
resource_id
if len(topline[67].strip()) > 0:
new_event.magnitudes.append(Magnitude())
new_event.magnitudes[1].mag = _float_conv(topline[64:67])
new_event.magnitudes[1].magnitude_type = topline[67]
new_event.magnitudes[1].creation_info = \
CreationInfo(agency_id=topline[68:71].strip())
new_event.magnitudes[1].origin_id = new_event.origins[0].\
resource_id
if len(topline[75].strip()) > 0:
new_event.magnitudes.append(Magnitude())
new_event.magnitudes[2].mag = _float_conv(topline[72:75])
new_event.magnitudes[2].magnitude_type = topline[75]
new_event.magnitudes[2].creation_info = \
CreationInfo(agency_id=topline[76:79].strip())
new_event.magnitudes[2].origin_id = new_event.origins[0].\
resource_id
f.close()
# convert the nordic notation of magnitude to more general notation
for _magnitude in new_event.magnitudes:
_magnitude.magnitude_type = _nortoevmag(_magnitude.magnitude_type)
# Set the useful things like preferred magnitude and preferred origin
new_event.preferred_origin_id = str(new_event.origins[0].resource_id)
if len(new_event.magnitudes) > 1:
try:
# Select moment first, then local, then
mag_filter = ['MW', 'Mw', 'ML', 'Ml', 'MB', 'Mb',
'MS', 'Ms', 'Mc', 'MC']
_magnitudes = [(m.magnitude_type, m.resource_id)
for m in new_event.magnitudes]
preferred_magnitude = sorted(_magnitudes,
key=lambda x: mag_filter.index(x[0]))
new_event.preferred_magnitude_id = str(preferred_magnitude[0][1])
except ValueError:
# If there is a magnitude not specified in filter
new_event.preferred_magnitude_id =\
str(new_event.magnitudes[0].resource_id)
elif len(new_event.magnitudes) == 1:
new_event.preferred_magnitude_id =\
str(new_event.magnitudes[0].resource_id)
return new_event
示例10: outputOBSPY
# 需要导入模块: from obspy.core.event import Event [as 别名]
# 或者: from obspy.core.event.Event import preferred_origin_id [as 别名]
def outputOBSPY(hp, event=None, only_fm_picks=False):
"""
Make an Event which includes the current focal mechanism information from HASH
Use the 'only_fm_picks' flag to only include the picks HASH used for the FocalMechanism.
This flag will replace the 'picks' and 'arrivals' lists of existing events with new ones.
Inputs
-------
hp : hashpy.HashPype instance
event : obspy.core.event.Event
only_fm_picks : bool of whether to overwrite the picks/arrivals lists
Returns
-------
obspy.core.event.Event
Event will be new if no event was input, FocalMech added to existing event
"""
# Returns new (or updates existing) Event with HASH solution
n = hp.npol
if event is None:
event = Event(focal_mechanisms=[], picks=[], origins=[])
origin = Origin(arrivals=[])
origin.time = UTCDateTime(hp.tstamp)
origin.latitude = hp.qlat
origin.longitude = hp.qlon
origin.depth = hp.qdep
origin.creation_info = CreationInfo(version=hp.icusp)
origin.resource_id = ResourceIdentifier('smi:hash/Origin/{0}'.format(hp.icusp))
for _i in range(n):
p = Pick()
p.creation_info = CreationInfo(version=hp.arid[_i])
p.resource_id = ResourceIdentifier('smi:hash/Pick/{0}'.format(p.creation_info.version))
p.waveform_id = WaveformStreamID(network_code=hp.snet[_i], station_code=hp.sname[_i], channel_code=hp.scomp[_i])
if hp.p_pol[_i] > 0:
p.polarity = 'positive'
else:
p.polarity = 'negative'
a = Arrival()
a.creation_info = CreationInfo(version=hp.arid[_i])
a.resource_id = ResourceIdentifier('smi:hash/Arrival/{0}'.format(p.creation_info.version))
a.azimuth = hp.p_azi_mc[_i,0]
a.takeoff_angle = 180. - hp.p_the_mc[_i,0]
a.pick_id = p.resource_id
origin.arrivals.append(a)
event.picks.append(p)
event.origins.append(origin)
event.preferred_origin_id = str(origin.resource_id)
else: # just update the changes
origin = event.preferred_origin()
picks = []
arrivals = []
for _i in range(n):
ind = hp.p_index[_i]
a = origin.arrivals[ind]
p = a.pick_id.getReferredObject()
a.takeoff_angle = hp.p_the_mc[_i,0]
picks.append(p)
arrivals.append(a)
if only_fm_picks:
origin.arrivals = arrivals
event.picks = picks
# Use me double couple calculator and populate planes/axes etc
x = hp._best_quality_index
# Put all the mechanisms into the 'focal_mechanisms' list, mark "best" as preferred
for s in range(hp.nmult):
dc = DoubleCouple([hp.str_avg[s], hp.dip_avg[s], hp.rak_avg[s]])
ax = dc.axis
focal_mech = FocalMechanism()
focal_mech.creation_info = CreationInfo(creation_time=UTCDateTime(), author=hp.author)
focal_mech.triggering_origin_id = origin.resource_id
focal_mech.resource_id = ResourceIdentifier('smi:hash/FocalMechanism/{0}/{1}'.format(hp.icusp, s+1))
focal_mech.method_id = ResourceIdentifier('HASH')
focal_mech.nodal_planes = NodalPlanes()
focal_mech.nodal_planes.nodal_plane_1 = NodalPlane(*dc.plane1)
focal_mech.nodal_planes.nodal_plane_2 = NodalPlane(*dc.plane2)
focal_mech.principal_axes = PrincipalAxes()
focal_mech.principal_axes.t_axis = Axis(azimuth=ax['T']['azimuth'], plunge=ax['T']['dip'])
focal_mech.principal_axes.p_axis = Axis(azimuth=ax['P']['azimuth'], plunge=ax['P']['dip'])
focal_mech.station_polarity_count = n
focal_mech.azimuthal_gap = hp.magap
focal_mech.misfit = hp.mfrac[s]
focal_mech.station_distribution_ratio = hp.stdr[s]
focal_mech.comments.append(
Comment(hp.qual[s], resource_id=ResourceIdentifier(str(focal_mech.resource_id) + '/comment/quality'))
)
#----------------------------------------
event.focal_mechanisms.append(focal_mech)
if s == x:
event.preferred_focal_mechanism_id = str(focal_mech.resource_id)
return event
示例11: sdxtoquakeml
# 需要导入模块: from obspy.core.event import Event [as 别名]
# 或者: from obspy.core.event.Event import preferred_origin_id [as 别名]
#.........这里部分代码省略.........
evaluation_mode="manual",
evaluation_status="confirmed",
method_id=ResourceIdentifier(id="SDX_hypo71"),
creation_info=CreationInfo(
creation_time=creation_time, author=author,
agency_id=agency_id),
quality=OriginQuality(
associated_phase_count=num_arrivals,
used_phase_count=num_arrivals,
associated_station_count=num_arrivals_p,
used_station_count=num_arrivals_p,
azimuthal_gap=max_az_gap,
minimum_distance=min_dist,
maximum_distance=max_dist,
median_distance=med_dist))
event.origins.append(origin)
sdx_file.close()
# Skip event if no computed origin
if found_origin is False:
print("No origin found ... skipping event")
continue
# Get pick details, append to pick and arrival objects
sdx_file = open(sdx_file_path, "r")
found_pick = False
for line in sdx_file:
if line.rstrip() == "pick":
found_pick = True
sdxpick = list(islice(sdx_file, 15))
pick_time = UTCDateTime(
"{:}T{:}".format(sdxpick[1][0:10].replace(".", "-"),
sdxpick[1][11:23]))
network = sdxpick[2].split()[0]
station = sdxpick[2].split()[1]
location = sdxpick[2].split()[2]
if "NOT_SET" in location:
location = ""
channel = sdxpick[2].split()[3]
onset = sdxpick[8].split()[0]
if onset == "0":
pickonset = "emergent"
elif onset == "1":
pickonset = "impulsive"
elif onset == "2":
pickonset = "questionable"
phase = sdxpick[9].split()[0]
polarity = sdxpick[10].split()[0]
if polarity == "0":
pol = "positive"
elif polarity == "1":
pol = "negative"
elif polarity == "2":
pol = "undecidable"
weight = int(sdxpick[11].split()[0])
creation_time = UTCDateTime(
"{:}T{:}".format(sdxpick[14].split()[6][0:10]
.replace(".", "-"),
sdxpick[14].split()[6][11:23]))
pick = Pick(time=pick_time,
waveform_id=WaveformStreamID(
network_code=network, station_code=station,
location_code=location, channel_code=channel),
time_errors=time_uncertainties[weight],
evaluation_mode="manual",
evaluation_status="confirmed", onset=pickonset,
phase_hint=phase, polarity=pol,
method_id=ResourceIdentifier(id="SDX"),
creation_info=CreationInfo(
creation_time=creation_time))
event.picks.append(pick)
# Compute azimuth, distance, append to arrival object
for i in range(0, len(stations)):
if stations[i][0] == station:
azimuth = (gps2dist_azimuth(evt_lat, evt_lon,
stations[i][1],
stations[i][2])[1])
dist_deg = locations2degrees(evt_lat, evt_lon,
stations[i][1],
stations[i][2])
arrival = Arrival(phase=phase,
pick_id=pick.resource_id,
azimuth=azimuth, distance=dist_deg,
time_weight=1.00)
event.origins[0].arrivals.append(arrival)
# Skip event if no picks
if found_pick is False:
print("No picks found ... skipping event")
continue
# Set preferred origin and append event to catalogue
event.preferred_origin_id = event.origins[0].resource_id
cat.events.append(event)
sdx_file.close()
cat.write(out_xml, format="QUAKEML")
示例12: _internal_read_single_scardec
# 需要导入模块: from obspy.core.event import Event [as 别名]
# 或者: from obspy.core.event.Event import preferred_origin_id [as 别名]
#.........这里部分代码省略.........
origin_type="centroid",
region=_fe.get_region(longitude=longitude,
latitude=latitude)
)
cmt_mag = Magnitude(
resource_id=_get_resource_id(event_name, "magnitude", tag="mw"),
mag=moment_mag,
magnitude_type="mw",
origin_id=cmt_origin.resource_id
)
nod1 = NodalPlane(strike=strike1, dip=dip1, rake=rake1)
nod2 = NodalPlane(strike=strike2, dip=dip2, rake=rake2)
nod = NodalPlanes(nodal_plane_1=nod1, nodal_plane_2=nod2)
foc_mec = FocalMechanism(
resource_id=_get_resource_id(event_name, "focal_mechanism"),
nodal_planes=nod
)
dip1 *= np.pi / 180.
rake1 *= np.pi / 180.
strike1 *= np.pi / 180.
mxx = - scalar_moment * ((np.sin(dip1) * np.cos(rake1) *
np.sin(2 * strike1)) +
(np.sin(2 * dip1) * np.sin(rake1) *
np.sin(2 * strike1)))
mxy = scalar_moment * ((np.sin(dip1) * np.cos(rake1) *
np.cos(2 * strike1)) +
(np.sin(2 * dip1) * np.sin(rake1) *
np.sin(2 * strike1) * 0.5))
myy = scalar_moment * ((np.sin(dip1) * np.cos(rake1) *
np.sin(2 * strike1)) -
(np.sin(2 * dip1) * np.sin(rake1) *
np.cos(2 * strike1)))
mxz = - scalar_moment * ((np.cos(dip1) * np.cos(rake1) *
np.cos(strike1)) +
(np.cos(2 * dip1) * np.sin(rake1) *
np.sin(strike1)))
myz = - scalar_moment * ((np.cos(dip1) * np.cos(rake1) *
np.sin(strike1)) -
(np.cos(2 * dip1) * np.sin(rake1) *
np.cos(strike1)))
mzz = scalar_moment * (np.sin(2 * dip1) * np.sin(rake1))
tensor = Tensor(m_rr=mxx, m_tt=myy, m_pp=mzz, m_rt=mxy, m_rp=mxz, m_tp=myz)
cm = [Comment(text="Basis system: North,East,Down \
(Jost and Herrmann 1989)")]
cm[0].resource_id = _get_resource_id(event_name, 'comment', 'mt')
cm.append(Comment(text="MT derived from focal mechanism, therefore \
constrained to pure double couple.",
force_resource_id=False))
# Write moment rate function
extra = {'moment_rate': {'value': stf_mr,
'namespace': r"http://test.org/xmlns/0.1"},
'dt': {'value': dt,
'namespace': r"http://test.org/xmlns/0.1"},
'offset': {'value': offset,
'namespace': r"http://test.org/xmlns/0.1"}
}
# Source time function
stf = SourceTimeFunction(type="unknown")
stf.extra = extra
mt = MomentTensor(
resource_id=_get_resource_id(event_name, "moment_tensor"),
derived_origin_id=cmt_origin.resource_id,
moment_magnitude_id=cmt_mag.resource_id,
scalar_moment=scalar_moment,
tensor=tensor,
source_time_function=stf,
comments=cm
)
# Assemble everything.
foc_mec.moment_tensor = mt
ev = Event(resource_id=_get_resource_id(event_name, "event"),
event_type="earthquake")
ev.event_descriptions.append(EventDescription(text=event_name,
type="earthquake name"))
ev.comments.append(Comment(
text="Hypocenter catalog: SCARDEC",
force_resource_id=False))
ev.origins.append(cmt_origin)
ev.magnitudes.append(cmt_mag)
ev.focal_mechanisms.append(foc_mec)
# Set the preferred items.
ev.preferred_origin_id = cmt_origin.resource_id.id
ev.preferred_magnitude_id = cmt_mag.resource_id.id
ev.preferred_focal_mechanism_id = foc_mec.resource_id.id
return ev