"""
Pisces Client mirrors the ObsPy FDSN Client interface.
"""
import builtins
import logging
import os
import warnings
from functools import cached_property
import sqlalchemy as sa
from obspy import Stream, UTCDateTime
from obspy.core.event.header import EventType
from sqlalchemy.orm import Session
from pisces.query import (
filter_arrivals,
filter_events,
filter_magnitudes,
filter_networks,
filter_responses,
filter_stations,
filter_waveforms,
)
from .catalog import KBCORE_EVENT_TYPE, catalog
from .inventory import build_inventory
from .stream import availability, extent, stream
log = logging.getLogger(__name__)
def _None_if_none(*values):
return None if all(val is None for val in values) else values
[docs]
def origins_to_fdsntext(origins, header=False):
"""Convert a SQLAlchemy Origin instances to FDSN event text.
#EventID | Time | Latitude | Longitude | Depth/km | Author | Catalog | Contributor | ContributorID | MagType | Magnitude | MagAuthor | EventLocationName
#origin.orid|origin.time|origin.lat|origin.lon|origin.depth|netmag.auth|netmag.auth|netmag.auth|netmag.magtype|netmag.magnitude|sregion.srname or event.evname
#origin.orid|origin.time|origin.lat|origin.lon|origin.depth|origin.auth|origin.auth|origin.auth|('ml','ms','mb')|origin.('ml','ms','mb')|sregion.srname or event.evname
header_string = '#EventID|Time|Latitude|Longitude|Depth/km|Author|Catalog|Contributor|ContributorID|MagType|Magnitude|MagAuthor|EventLocationName'
"""
header_string = "EventID | Time | Latitude | Longitude | Depth/km | Author | Catalog | Contributor | ContributorID | MagType | Magnitude | MagAuthor | EventLocationName"
# this needs to get MagType in there
origin_columns = (
"orid",
"time",
"lat",
"lon",
"depth",
"auth",
"auth",
"auth",
"orid",
"mb",
"mb",
"auth",
"grn",
)
rows = [
"|".join(str(getattr(origin, column, "-"))
for column in origin_columns)
for origin in origins
]
if header:
out = [header_string] + rows
else:
out = rows
return os.linesep.join(out)
def _etype(eventtype):
""" Convert QML eventtype string to KBCore etype string.
Both input and output may be comma-separated.
Input may contain duplicate eventtypes, but output contains no duplicate etypes.
"""
# may be multiple eventtypes, which may correspond to multiple KB Core etypes
etype_set = set()
for e in eventtype.split(','):
ietypes = KBCORE_EVENT_TYPE.get(e, e).split(',')
etype_set.update({*ietypes})
# etype = ','.join(etype_set) # rejoin the unique set with commas
# rejoin the unique set with commas, predictable order for tests
etype = sorted(etype_set)
return etype[0] if len(etype) == 1 else etype
def _evid_list(eventid):
""" Turn (possibly comma-separated) string event IDs into integer evid list.
Raises
------
TypeError : input must be one of ``{int, str, list, tuple}``
"""
# py3.10+
match type(eventid):
case builtins.int:
evids = [eventid]
case builtins.str:
evids = [int(e) for e in eventid.split(",")]
case _:
msg = f"eventid must be an int, str, list, or tuple. received: {type(eventid)}."
raise TypeError(msg)
return evids
[docs]
class Client:
"""
Basic database request client.
"""
def __init__(self, dburl_or_session, **tables):
"""
FDSN-style client interface to a SQL database using a CSS3.0-style schema.
Parameters
----------
dburl_or_session : str or sqlalchemy.orm.Session instance
RFC-1738-complient database URL string of the form:
'<backend>://[<user>[:<password>]@]<server>:<port>/<instance>'
or a pre-configured SQLAlchemy Session instance
tables : one or more str or Pisces table class
Examples
--------
>>> client = Client('sqlite:///local/path/to/mydb.sqlite')
>>> client = Client('sqlite:////full/path/to/mydb.sqlite', site='mysite')
>>> client = Client('oracle://scott:tiger@dbserver.somewhere.com:8080/mydb')
>>> client = Client(session)
>>> from myschema import Origin, Site
>>> client = Client(session, origin=Origin, site=Site)
>>> from pisces import crud
>>> tables = crud.make_tables('origin', 'site', owner='global')
>>> client = Client(session, **tables)
"""
if isinstance(dburl_or_session, str):
engine = sa.create_engine(dburl_or_session)
session = Session(engine)
else:
session = dburl_or_session
# this is just a test, will fail early if the connection is misconfigured
# session.bind.connect();
self.session = session
self.tables = tables
def __repr__(self):
repr_str = "<Client({!r})>"
return repr_str.format(self.session.bind.url)
[docs]
@cached_property # >= py3.8
def contributors(self):
""" Sorted list of distinct origin authors (Origin.auth) """
Origin = self.tables['origin']
return self.session.query(Origin.auth).distinct().order_by(Origin.auth).all()
[docs]
@cached_property # >= py3.8
def magnitude_types(self):
""" Sorted list of distinct Netmag.magtype """
Netmag = self.tables['netmag']
return self.session.query(Netmag.magtype).distinct().order_by(Netmag.magtype).all()
[docs]
def get_events(
self,
starttime: UTCDateTime = None,
endtime: UTCDateTime = None,
minlatitude: float | None = None,
maxlatitude: float | None = None,
minlongitude: float | None = None,
maxlongitude: float | None = None,
latitude: float | None = None,
longitude: float | None = None,
minradius: float | None = None,
maxradius: float | None = None,
mindepth: float | None = None,
maxdepth: float | None = None,
minmagnitude: float | None = None,
maxmagnitude: float | None = None,
magnitudetype: str | None = None,
eventtype: str | None = None,
includeallorigins: bool = True,
includeallmagnitudes: bool = False,
includearrivals: bool = False,
preferred_magnitude: tuple = ("mb", "mw", "ms"),
eventid: str | None = None,
limit: int | None = None,
offset: int | None = None,
orderby: bool | None = None,
contributor: str | None = None,
updatedafter: UTCDateTime = None,
asquery: bool = False,
**kwargs,
):
"""
Query event data.
>>> cat = client.get_events(eventid=609301)
The return value is a :class:`~obspy.core.event.Catalog` object
which can contain any number of events.
>>> t1 = UTCDateTime("2001-01-07T00:00:00")
>>> t2 = UTCDateTime("2001-01-07T03:00:00")
>>> cat = client.get_events(starttime=t1, endtime=t2, minmagnitude=4,
... contributor="ISC")
>>> print(cat)
3 Event(s) in Catalog:
2001-01-07T02:55:59.290000Z | +9.801, +76.548 | 4.9 mb
2001-01-07T02:35:35.170000Z | -21.291, -68.308 | 4.4 mb
2001-01-07T00:09:25.630000Z | +22.946, -107.011 | 4.0 mb
starttime : obspy.UTCDateTime, optional [Origin]
Limit to events on or after the specified start time.
endtime : obspy.UTCDateTime optional [Origin]
Limit to events on or before the specified end time.
minlatitude : float, optional [Origin]
Limit to events with a latitude larger than the specified minimum.
maxlatitude : float, optional [Origin]
Limit to events with a latitude smaller than the specified
maximum.
minlongitude : float, optional [Origin]
Limit to events with a longitude larger than the specified
minimum.
maxlongitude : float, optional [Origin]
Limit to events with a longitude smaller than the specified
maximum.
latitude : float, optional [Origin]
Specify the latitude to be used for a radius search.
Not currently implemented.
longitude : float, optional [Origin]
Specify the longitude to the used for a radius search.
Not currently implemented.
minradius : float, optional [Origin]
Limit to events within the specified minimum number of degrees
from the geographic point defined by the latitude and longitude
parameters.
Not currently implemented.
maxradius : float, optional [Origin]
Limit to events within the specified maximum number of degrees
from the geographic point defined by the latitude and longitude
parameters.
Not currently implemented.
mindepth : float, optional [Origin]
Limit to events with depth, in kilometers, larger than the
specified minimum.
maxdepth : float, optional [Origin]
Limit to events with depth, in kilometers, smaller than the
specified maximum.
minmagnitude : float, optional [Origin, Netmag]
Limit to events with a magnitude larger than the specified minimum.
maxmagnitude : float, optional [Origin, Netmag]
Limit to events with a magnitude smaller than the specified maximum.
magnitudetype : str, optional [Origin, Netmag]
Specify a magnitude type to use for testing the minimum and maximum limits. If not
provided, any magnitude range constraints are applied to all magnitude types. Netmag
table is required for magnitudes other than 'ml', 'mb', or 'ms'.
Wildcards are accepted.
eventtype: str, optional [Origin]
Limit to events with a specified event type. Multiple types are comma-separated
e.g., `"earthquake,quarry blast"`. Allowed values are from QuakeML.
See `obspy.core.event.header.EventType` for a list of allowed event types.
includeallorigins : bool, optional (Origin [, Event])
Include all matching origins. Non-preferred origins are retained
even without Netmag rows, but then have no QuakeML magnitudes.
Default is True.
includeallmagnitudes : bool, optional [Netmag]
Include all Netmag rows. When False (default), include only the
preferred magnitude for the event's preferred origin.
preferred_magnitude : tuple of str, optional
Network magnitude types in preferred order, case-insensitive. Defaults to
``("mb", "mw", "ms")``.
includearrivals : bool, optional [Assoc, Arrival]
Specify if phase arrivals should be included. Default is False.
eventid : str or int, optional [Event | Origin]
Select a specific event by ID (evid), or comma-separated list of IDs.
e.g. 1234 or '1234,5678'. If provided, all other parameters are ignored.
limit : int, optional [not yet implemented]k
Limit the results to the specified number of events.
offset : int, optional [not yet implemented]
Return results starting at the event count specified, starting at 1.
orderby : str, optional [Origin]
Order the result by time or magnitude with the following possibilities:
* time: order by origin descending time [not yet implemented]
* time-asc: order by origin ascending time [not yet implemented]
* magnitude: order by descending magnitude [ignored]
KB Core events doen't have a preferred magnitude, so sorting is ignored.
* magnitude-asc: order by ascending magnitude [ignored]
See above.
catalog : str, optional [ignored]
KB Core tables have no concept of a catalog. This parameter is ignored.
See 'contributor' below.
contributor : str, optional [Origin]
Limit to events contributed by a specified contributor.
Matches strings inside the 'auth' field in the Origin table. Catalog sources
are embedded within this field, so add them here with wildcards, like '*ISC*'.
updatedafter : obspy.UTCDateTime, optional [Origin]
Limit to events updated after the specified time.
KB Core doesn't keep track of updates, so this parameter filters Origin.lddate,
the date the origin was added to the database.
asquery : bool
Return the raw SQLAlchemy query instead of direct results.
Returns
-------
result : obspy.Catalog or sqlalchemy.orm.Query instance
Raises
------
ValueError
Missing or improper inputs.
"""
try:
Origin = self.tables["origin"]
Event = self.tables["event"] # needed for QuakeML output
Netmag = self.tables["netmag"]
except KeyError:
msg = "Event, Origin, and Netmag tables required."
raise ValueError(msg)
Arrival = self.tables.get("arrival", None)
Assoc = self.tables.get("assoc", None)
# Stamag = self.tables.get("stamag", None)
# characterize which inputs were provided
timeparams = any([starttime, endtime])
boxparams = any([minlongitude, maxlongitude, minlatitude, maxlatitude])
radialparams = any([latitude, longitude, minradius, maxradius])
magparams = any([minmagnitude, maxmagnitude, magnitudetype])
# check for nonsense inputs
if eventid and (magparams or boxparams or radialparams or timeparams):
msg = "If eventid is specified, no other parameters are used."
warnings.warn(msg)
if boxparams and radialparams:
msg = "Incompatible inputs: using both lat/lon and radius ranges not allowed"
raise ValueError(msg)
# TODO: Are some of these checks already in the respective
# filter_[events, arrivals, magnitudes] functions?
if includearrivals and (not Arrival or not Assoc):
msg = "Arrival and Assoc tables required for includeallarrivals."
raise ValueError(msg)
if orderby and orderby not in ("time", "time-asc", "magnitude", "magnitude-asc"):
msg = "orderby must be one of ('time', 'time-asc', 'magnitude', 'magnitude-asc')"
raise ValueError(msg)
if eventtype and any(e.lower() not in EventType for e in eventtype.split(',')):
msg = f"eventtype '{eventtype}' not recognized. choose from {list(KBCORE_EVENT_TYPE.keys())}"
raise ValueError(msg)
# normalize inputs for event query functions
times = _None_if_none(starttime, endtime)
region = _None_if_none(minlongitude, maxlongitude,
minlatitude, maxlatitude)
radius = _None_if_none(latitude, longitude, minradius, maxradius)
depth = _None_if_none(mindepth, maxdepth)
prefor = not includeallorigins
magnitudetype = 'all' if magparams and not magnitudetype else magnitudetype
magnitudes = {magnitudetype: (
minmagnitude, maxmagnitude)} if magparams else {}
auth = contributor
etype = _etype(eventtype) if eventtype else None
evid = _evid_list(eventid) if eventid else None
# build the query (finally)
# geographic / categorical stuff
q = self.session.query(Event, Origin).select_from(Event).join(
Origin, Event.evid == Origin.evid
)
q = filter_events(q,
region=region,
times=times,
depth=depth,
evid=evid,
prefor=prefor,
auth=auth,
etype=etype,
)
# [(event, origin)] expected structure
if updatedafter:
q = q.filter(Origin.lddate > updatedafter)
# Netmag is optional for unfiltered event requests. Origins remain in the
# Catalog without magnitudes when no corresponding Netmag row exists.
mag_filter_requested = bool(magnitudes)
if mag_filter_requested:
q = q.add_entity(Netmag)
q = filter_magnitudes(q, **magnitudes)
elif includeallmagnitudes:
q = q.outerjoin(
Netmag,
sa.and_(Netmag.evid == Event.evid, Netmag.orid == Origin.orid),
).add_entity(Netmag)
else:
preferred_types = tuple(magtype.casefold() for magtype in preferred_magnitude)
priority = sa.case(
*[(sa.func.lower(Netmag.magtype) == magtype, rank)
for rank, magtype in enumerate(preferred_types, start=1)],
else_=len(preferred_types) + 1,
)
preferred = (
self.session.query(
Event.evid.label("evid"),
Netmag.orid.label("orid"),
Netmag.magid.label("magid"),
sa.func.row_number().over(
partition_by=Event.evid,
order_by=priority,
).label("rank"),
)
.select_from(Netmag)
.join(Event, Netmag.evid == Event.evid)
.filter(Netmag.orid == Event.prefor)
.filter(sa.func.lower(Netmag.magtype).in_(preferred_types))
.subquery()
)
preferred = self.session.query(
preferred.c.evid, preferred.c.orid, preferred.c.magid
).filter(preferred.c.rank == 1).subquery()
q = q.outerjoin(
preferred, sa.and_(preferred.c.evid == Event.evid,
preferred.c.orid == Origin.orid)
).outerjoin(Netmag, Netmag.magid == preferred.c.magid).add_entity(Netmag)
# [(event, origin, netmag or None)] expected structure
# arrival stuff
if includearrivals:
# XXX: potential cartesian join with Netmag stuff
q = q.add_entity(Assoc).add_entity(Arrival)
q = filter_arrivals(q)
# [(event, origin, netmag, assoc, arrival)]
# XXX: implement proper preferred origin sorting, limit, offset
# if orderby == "time":
# q = q.order_by(Origin.time.desc())
# elif orderby == "time-asc":
# q = q.order_by(Origin.time.asc())
# elif orderby == "magnitude":
# q = q.order_by(Netmag.magnitude.desc())
# elif orderby == "magnitude-asc":
# q = q.order_by(Netmag.magnitude.asc())
# TODO: how to offset/limit just the Event.evids? use itertools sorted, groupby, islice?
# .limit/offset on an ordered subquery?
# q = q.limit(limit) if limit else q
# q = q.offset(offset) if offset else q
if asquery:
result = q
else:
result = catalog(q)
return result
[docs]
def get_stations(
self,
starttime: UTCDateTime = None,
endtime: UTCDateTime = None,
startbefore: UTCDateTime = None,
startafter: UTCDateTime = None,
endbefore: UTCDateTime = None,
endafter: UTCDateTime = None,
network: str | None = None,
station: str | None = None,
channel: str | None = None,
minlatitude: float | None = None,
maxlatitude: float | None = None,
minlongitude: float | None = None,
maxlongitude: float | None = None,
latitude: float | None = None,
longitude: float | None = None,
minradius: float | None = None,
maxradius: float | None = None,
level: str = "station",
# includerestricted: bool = None,
# includeavailability: bool = None,
updatedafter: UTCDateTime = None,
matchtimeseries: bool | None = None,
filename: str | None = None,
format: str = "xml",
asquery: bool = False,
**kwargs
):
"""Build a station metadata query or Inventory.
Parameters
----------
starttime, endtime : UTCDateTime, optional
Filter metadata epochs overlapping the requested interval. Network-level
queries filter Affiliation epochs; station-level queries filter Site,
Sitechan, and response epochs in their respective tables.
network, station, channel : str, optional
Comma-separated codes or ``*``/``?`` wildcard patterns.
minlatitude, maxlatitude, minlongitude, maxlongitude : float, optional
Rectangular geographic bounds applied to Site rows.
level : str, optional
One of ``{"network", "station", "channel", "response"}``.
Metadata detail level. Defaults to ``"station"``.
asquery : bool, optional
Return the SQLAlchemy query instead of building an ObsPy Inventory.
Returns
-------
sqlalchemy.orm.Query or obspy.core.inventory.Inventory
The SQLAlchemy query when ``asquery=True``; otherwise the requested
station metadata as an Inventory.
Raises
------
ValueError
If ``level`` is invalid or the tables required for that level are absent.
"""
# startbefore : .UTCDateTime
# Limit to metadata epochs starting before specified time.
# startafter : UTCDateTime
# Limit to metadata epochs starting after specified time.
# endbefore : UTCDateTime
# Limit to metadata epochs ending before specified time.
# endafter : UTCDateTime
# Limit to metadata epochs ending after specified time.
# latitude : float
# Specify the latitude to be used for a radius search. Accepted for
# FDSN compatibility but currently ignored.
# longitude : float
# Specify the longitude to be used for a radius search. Accepted for
# FDSN compatibility but currently ignored.
# minradius : float
# Limit results to stations within the specified minimum number of
# degrees from the geographic point defined by the latitude and
# longitude parameters. Accepted for FDSN compatibility but currently
# ignored.
# maxradius : float
# Limit results to stations within the specified maximum number of
# degrees from the geographic point defined by the latitude and
# longitude parameters. Accepted for FDSN compatibility but currently
# ignored.
# includerestricted : bool
# Specify if results should include information for restricted stations.
# includeavailability : bool
# Specify if results should include information about time series data availability.
# updatedafter : UTCDateTime
# Limit to metadata updated after specified date; updates are data center specific.
# matchtimeseries : bool
# Only include data for which matching time series data is available.
# filename : str or file
# If given, the downloaded data will be saved there instead of being
# parsed to an ObsPy object. Thus it will contain the raw data from
# the webservices.
# format : str
# The format in which to request station information. "xml"
# (StationXML) or "text" (FDSN station text format). XML has more
# information but text is much faster.
#
# These parameters are accepted for FDSN compatibility but are not
# implemented for local database queries.
level = level.lower()
valid_levels = ['network', 'station', 'channel', 'response']
if level not in valid_levels:
raise ValueError(f"level must be one of {valid_levels}")
required_tables = {
'network': ('network',),
'station': ('network', 'affiliation', 'site'),
'channel': ('network', 'affiliation', 'site', 'sitechan'),
'response': ('network', 'affiliation', 'site', 'sitechan', 'sensor', 'instrument'),
}[level]
if any(table not in self.tables for table in required_tables):
names = ', '.join(required_tables)
raise ValueError(f"{names} tables required for {level} level metadata.")
Network = self.tables.get('network')
Affiliation = self.tables.get('affiliation')
Site = self.tables.get('site')
Sitechan = self.tables.get('sitechan')
Sensor = self.tables.get('sensor')
Instrument = self.tables.get('instrument')
times = _None_if_none(starttime, endtime)
region = _None_if_none(
minlongitude, maxlongitude, minlatitude, maxlatitude
)
if level == 'network':
q = self.session.query(Network)
if Affiliation:
q = q.add_entity(Affiliation)
q = filter_networks(q, net=network, sta=station, times=times)
else:
q = self.session.query(Network, Affiliation, Site)
q = filter_networks(q, net=network)
if level in ('channel', 'response'):
q = q.add_entity(Sitechan)
q = filter_stations(
q,
sta=station,
chan=channel,
times=times,
region=region,
)
if level == 'response':
q = q.add_entity(Sensor).add_entity(Instrument)
q = filter_responses(
q,
sta=station,
chan=channel,
times=times,
)
if asquery:
return q
return build_inventory(q, level=level)
[docs]
def get_availability(
self,
network=None,
station=None,
channel=None,
starttime=None,
endtime=None,
mergegaps=0.0,
mergesamplerate=None,
show=None,
includerestricted=True,
restricted_substring=None,
):
"""Get waveform availability for a requested time window.
Parameters
----------
network, station, channel : str, optional
Network, station, and channel patterns. Comma-separated values and
``*``/``?`` wildcards are supported.
starttime, endtime : obspy.UTCDateTime
Required request bounds.
mergegaps : float, optional
Merge spans separated by no more than this many seconds.
mergesamplerate : float, optional
Merge spans whose sample rates differ by no more than this amount.
show : str or None, optional
``"latestupdate"`` or ``None``.
Include the latest contributing update time.
includerestricted : bool, optional
Include restricted data by default.
restricted_substring : str, optional
Substring used to identify restricted Site or Network metadata when
``includerestricted=False``.
"""
# TODO: support quality, merge, orderby, limit, format, and nodata.
if starttime is None or endtime is None:
raise ValueError("starttime and endtime are required")
try:
Wfdisc = self.tables["wfdisc"]
Affiliation = self.tables["affiliation"]
except KeyError:
raise ValueError("Wfdisc and Affiliation tables required.")
tables = [Wfdisc, Affiliation]
if not includerestricted:
try:
Site = self.tables["site"]
Network = self.tables["network"]
except KeyError:
raise ValueError(
"Site and Network tables required when excluding restricted data."
)
tables.extend((Site, Network))
query = filter_waveforms(
self.session.query(*tables),
net=network,
sta=station,
chan=channel,
times=(starttime, endtime),
recordlength=None,
)
return availability(
query,
mergegaps=mergegaps,
mergesamplerate=mergesamplerate,
show=show,
includerestricted=includerestricted,
restricted_substring=restricted_substring,
)
[docs]
def get_extent(
self,
network=None,
station=None,
channel=None,
starttime=None,
endtime=None,
includerestricted=True,
restricted_substring=None,
):
"""Get waveform extents for a requested time window.
Parameters
----------
network, station, channel : str, optional
Network, station, and channel patterns. Comma-separated values and
``*``/``?`` wildcards are supported.
starttime, endtime : obspy.UTCDateTime
Required request bounds.
includerestricted : bool, optional
Include restricted data by default.
restricted_substring : str, optional
Substring used to identify restricted Site or Network metadata when
``includerestricted=False``.
"""
# TODO: support quality, merge, orderby, limit, format, and nodata.
if starttime is None or endtime is None:
raise ValueError("starttime and endtime are required")
try:
Wfdisc = self.tables["wfdisc"]
Affiliation = self.tables["affiliation"]
except KeyError:
raise ValueError("Wfdisc and Affiliation tables required.")
tables = [Wfdisc, Affiliation]
if not includerestricted:
try:
Site = self.tables["site"]
Network = self.tables["network"]
except KeyError:
raise ValueError(
"Site and Network tables required when excluding restricted data."
)
tables.extend((Site, Network))
query = filter_waveforms(
self.session.query(*tables),
net=network,
sta=station,
chan=channel,
times=(starttime, endtime),
recordlength=None,
)
return extent(
query,
includerestricted=includerestricted,
restricted_substring=restricted_substring,
)