Coverage for /opt/obspy/update-docs/src/obspy/obspy/neries/client : 91%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
# -*- coding: utf-8 -*- NERIES Web service client for ObsPy.
.. seealso:: http://www.seismicportal.eu/jetspeed/portal/web-services.psml
:copyright: The ObsPy Development Team (devs@obspy.org) :license: GNU Lesser General Public License, Version 3 (http://www.gnu.org/copyleft/lesser.html) """
'min_latitude': "latMin", 'max_latitude': "latMax", 'min_longitude': "lonMin", 'max_longitude': "lonMax", 'min_depth': "depthMin", 'max_depth': "depthMax", 'min_magnitude': "magMin", 'max_magnitude': "magMax", 'magnitude_type': "magType", 'author': "auth", 'max_results': "limit", 'sort_by': "sort", 'sort_direction': "dir", 'format': "format", 'datetime': "datetime", 'depth': "depth", 'flynn_region': "flynn_region", 'latitude': "lat", 'longitude': "lon", 'magnitude': "mag", 'origin_id': "orid", 'event_id': "unid"}
# in results the "magType" key is all lowercase, so add it to..
platform.platform(), platform.python_version())
# monkey patching SUDS # ses also https://fedorahosted.org/suds/ticket/292
ns = (prefix, ns[1])
""" Maps function arguments to keyword arguments. """ def wrapper(*args, **kwargs): # set some default values 'format': "list"}
""" Suds plug-in extending the method call with arbitrary attributes. """
""" NERIES Web service request client. """ user_agent=DEFAULT_USER_AGENT): """ Initializes the NERIES Web service client.
:type user: str, optional :param user: The user name used for identification with the Web service. This entry in form of a email address is required for using the following methods: * :meth:`~obspy.neries.client.Client.saveWaveform` * :meth:`~obspy.neries.client.Client.getWaveform` * :meth:`~obspy.neries.client.Client.getInventory` Defaults to ``''``. :type password: str, optional :param password: A password used for authentication with the Web service. Defaults to ``''``. :type timeout: int, optional :param timeout: Seconds before a connection timeout is raised (default is 10 seconds). Available only for Python >= 2.6.x. :type debug: boolean, optional :param debug: Enables verbose output. :type user_agent: str, optional :param user_agent: Sets an client identification string which may be used on server side for statistical analysis (default contains the current module version and basic information about the used operation system, e.g. ``'ObsPy 0.4.7.dev-r2432 (Windows-7-6.1.7601-SP1, Python 2.7.1)'``. """ # Create an OpenerDirector for Basic HTTP Authentication self.password) # install globally
""" Send a HTTP request via urllib2.
:type url: str :param url: Complete URL of resource :type headers: dict :param headers: Additional header information for request """ # replace special characters if self.debug: print('\nRequesting %s' % (remoteaddr))
""" Converts a JSON formated string into a event/origin list. """ for k, v in result.iteritems()]) # convention in ObsPy: all depths negative down
min_longitude=None, max_longitude=None, min_latitude=None, max_latitude=None, min_depth=None, max_depth=None, min_magnitude=None, max_magnitude=None, magnitude_type=None, author=None, sort_by="datetime", sort_direction="ASC", max_results=100, format=None, **kwargs): """ Gets a list of events.
:type min_datetime: str, optional :param min_datetime: Earliest date and time for search. ISO 8601-formatted, in UTC: yyyy-MM-dd['T'HH:mm:ss]. e.g.: ``"2002-05-17"`` or ``"2002-05-17T05:24:00"`` :type max_datetime: str, optional :param max_datetime: Latest date and time for search. :type min_latitude: int or float, optional :param min_latitude: Minimum latitude for search. Format: +/- 90 decimal degrees. :type max_latitude: int or float, optional :param max_latitude: Maximum latitude for search. :type min_longitude: int or float, optional :param min_longitude: Minimum ("left-side") longitude for search. Format: +/- 180 decimal degrees. :type max_longitude: int or float, optional :param max_longitude: Maximum ("right-side") longitude for search. :type min_depth: int or float, optional :param min_depth: Minimum event depth. Format: in km, negative down. :type max_depth: int or float, optional :param max_depth: Maximum event depth. :type min_magnitude: int or float, optional :param min_magnitude: Minimum event magnitude. :type max_magnitude: int or float, optional :param max_magnitude: Maximum event magnitude. :type magnitude_type: str, optional :param magnitude_type: Magnitude scale type. Examples: ``"mw"`` or ``"mb"``. :type author: str, optional :param author: Origin author. Examples: ``"CSEM"``, ``"LDG"``, ... :type max_results: int (maximum: 2500) :param max_results: Maximum number of returned results. :type sort_by: str :param sort_by: Field to sort by. Options: ``"datetime"``, ``"magnitude"``, ``"flynn_region"``, ``"depth"``. Only available if attribute ``format`` is set to ``"list"``. :type sort_direction: str :param sort_direction: Sort direction. Format: ``"ASC"`` or ``"DESC"``. :type format: ``'list'``, ``'xml'`` or ``'catalog'``, optional :param format: Format of returned results. Defaults to ``'list'``.
.. note:: The JSON-formatted queries only look at preferred origin parameters, whereas QuakeML queries search all associated origins.
:rtype: :class:`~obspy.core.event.Catalog`, list or str :return: Method will return either an ObsPy :class:`~obspy.core.event.Catalog` object, a list of event dictionaries or a QuakeML string depending on the ``format`` keyword.
.. seealso:: http://www.seismicportal.eu/services/event/search/info/
.. rubric:: Example
>>> from obspy.neries import Client >>> client = Client() >>> events = client.getEvents(min_datetime="2004-12-01", ... max_datetime="2005-01-01", ... min_magnitude=9, format="list") >>> len(events) 1 >>> events #doctest: +SKIP [{'author': u'CSEM', 'event_id': u'20041226_0000148', 'origin_id': 127773, 'longitude': 95.724, 'datetime': UTCDateTime(2004, 12, 26, 0, 58, 50), 'depth': -10.0, 'magnitude': 9.3, 'magnitude_type': u'mw', 'latitude': 3.498, 'flynn_region': u'OFF W COAST OF NORTHERN SUMATRA'}] """ # deprecation warning if format is not set msg = "The default setting format='list' for obspy.neries." + \ "Client.getEvents() will be changed in the future to " + \ "format='catalog'. Please call this function with the " + \ "format keyword in order to hide this deprecation warning." warnings.warn(msg, category=DeprecationWarning) format = "list" # map request format string "list" -> "json" # switch depth to positive down # fetch data # format output else:
""" Gets a list of recent events.
:type num: int, optional :param num: Number of events to return. Defaults to ``10``.
.. note:: Absolute maximum is 2500 events.
:type format: ``'list'``, ``'xml'`` or ``'catalog'``, optional :param format: Format of returned results. Defaults to ``'xml'``. :rtype: :class:`~obspy.core.event.Catalog`, list or str :return: Method will return either an ObsPy :class:`~obspy.core.event.Catalog` object, a list of event dictionaries or a QuakeML string depending on the ``format`` keyword.
.. seealso:: http://www.seismicportal.eu/services/event/latest/info/
.. rubric:: Example
>>> from obspy.neries import Client >>> client = Client() >>> events = client.getLatestEvents(num=5, format='list') >>> len(events) 5 >>> events[0] #doctest: +SKIP [{'author': u'CSEM', 'event_id': u'20041226_0000148', 'origin_id': 127773, 'longitude': 95.724, 'datetime': u'2004-12-26T00:58:50Z', 'depth': -10.0, 'magnitude': 9.3, 'magnitude_type': u'mw', 'latitude': 3.498, 'flynn_region': u'OFF W COAST OF NORTHERN SUMATRA'}] """ # deprecation warning if format is not set msg = "The default setting format='xml' for obspy.neries." + \ "Client.getLatestEvents() will be changed in the future " + \ "to format='catalog'. Please call this function with the " + \ "format keyword in order to hide this deprecation warning." warnings.warn(msg, category=DeprecationWarning) format = "xml" # parse parameters else: # fetch data # format output else:
""" Gets event detail information.
:type uri: str :param uri: Event identifier as either a EMSC event unique identifier, e.g. ``"19990817_0000001"`` or a QuakeML-formatted event URI, e.g. ``"quakeml:eu.emsc/event#19990817_0000001"``. :type format: ``'list'``, ``'xml'`` or ``'catalog'``, optional :param format: Format of returned results. Defaults to ``'xml'``. :rtype: :class:`~obspy.core.event.Catalog`, list or str :return: Method will return either an ObsPy :class:`~obspy.core.event.Catalog` object, a list of event dictionaries or a QuakeML string depending on the ``format`` keyword.
.. seealso:: http://www.seismicportal.eu/services/event/detail/info/
.. rubric:: Example
>>> from obspy.neries import Client >>> client = Client() >>> result = client.getEventDetail("19990817_0000001", 'list') >>> len(result) # Number of calculated origins 12 >>> result[0] # Details about first calculated origin #doctest: +SKIP {'author': u'EMSC', 'event_id': u'19990817_0000001', 'origin_id': 1465935, 'longitude': 29.972, 'datetime': UTCDateTime(1999, 8, 17, 0, 1, 35), 'depth': -10.0, 'magnitude': 6.7, 'magnitude_type': u'mw', 'latitude': 40.749} """ # deprecation warning if format is not set msg = "The default setting format='xml' for obspy.neries." + \ "Client.getEventDetail() will be changed in the future to " + \ "format='catalog'. Please call this function with the " + \ "format keyword in order to hide this deprecation warning." warnings.warn(msg, category=DeprecationWarning) format = "xml" # parse parameters else: # QuakeML-formatted event URI else: # EMSC event unique identifier # fetch data # format output else:
model='iasp91'): """ Returns travel times for specified station-event geometry using standard velocity models such as ``iasp91``, ``ak135`` or ``qdt``.
:type latitude: float :param latitude: Event latitude. :type longitude: float :param longitude: Event longitude. :type depth: float :param depth: Event depth in km. :type locations: list of tuples :param locations: Each tuple contains a pair of (latitude, longitude) of a station. :type model: ``'iasp91'``, ``'ak135'``, or ``'qdt'``, optional :param model: Velocity model, defaults to 'iasp91'. :return: List of dicts containing phase name and arrival times in ms.
.. seealso:: http://www.orfeus-eu.org/wsdl/taup/taup.wsdl
.. rubric:: Example
>>> client = Client() >>> locations = [(48.0, 12.0), (48.1, 12.0)] >>> result = client.getTravelTimes(latitude=20.0, longitude=20.0, ... depth=10.0, locations=locations, ... model='iasp91') >>> len(result) 2 >>> result[0] # doctest: +SKIP {'P': 356981.13561726053, 'S': 646841.5619481194} """ # enable logging if debug option is set if self.debug: import logging logging.basicConfig(level=logging.INFO) logging.getLogger('suds.client').setLevel(logging.DEBUG) # initialize client # set cache of 5 days # create request 'event-lat': float(latitude), 'event-lon': float(longitude), 'model': str(model), 'point-lat': float(location[0]), 'point-lon': float(location[1])}
starttime=UTCDateTime(), endtime=UTCDateTime(), instruments=True, min_latitude=-90, max_latitude=90, min_longitude=-180, max_longitude=180, modified_after=None, format='SUDS'): """ Returns information about the available networks and stations in that particular space/time region.
:type network: str :param network: Network code, e.g. ``'BW'``. :type station: str :param station: Station code, e.g. ``'MANZ'``. Station code may contain wild cards. :type location: str :param location: Location code, e.g. ``'01'``. Location code may contain wild cards. :type channel: str :param channel: Channel code, e.g. ``'EHE'``. Channel code may contain wild cards. :type starttime: :class:`~obspy.core.utcdatetime.UTCDateTime` :param starttime: Start date and time. :type endtime: :class:`~obspy.core.utcdatetime.UTCDateTime` :param endtime: End date and time. :type instruments: boolean, optional :param instruments: Include instrument data. Default is ``True``. :type min_latitude: float, optional :param min_latitude: Minimum latitude, defaults to ``-90.0`` :type max_latitude: float, optional :param max_latitude: Maximum latitude, defaults to ``90.0`` :type min_longitude: float, optional :param min_longitude: Minimum longitude, defaults to ``-180.0`` :type max_longitude: float, optional :param max_longitude: Maximum longitude, defaults to ``180.0``. :type modified_after: :class:`~obspy.core.utcdatetime.UTCDateTime`, optional :param modified_after: Returns only data modified after given date. Default is ``None``, returning all available data. :type format: ``'XML'`` or ``'SUDS'``, optional :param format: Output format. Either returns a XML document or a parsed SUDS object. Defaults to ``SUDS``. :return: XML document or a parsed SUDS object containing inventory information.
.. rubric:: Example
>>> from obspy.neries import Client >>> from obspy import UTCDateTime >>> client = Client(user='test@obspy.org') >>> dt = UTCDateTime("2011-01-01T00:00:00") >>> result = client.getInventory('GE', 'SNAA', '', 'BHZ', dt, dt+10, ... instruments=True) >>> paz = result.ArclinkInventory.inventory.responsePAZ >>> print(paz.poles) # doctest: +ELLIPSIS (-0.037004,0.037016) (-0.037004,-0.037016) (-251.33,0.0) ... """ # enable logging if debug option is set if self.debug: import logging logging.basicConfig(level=logging.INFO) logging.getLogger('suds.client').setLevel(logging.DEBUG) # initialize client retxml=(format == 'XML')) # set prefixes for easier debugging # set cache of 5 days # create user token # create station filter UTCDateTime(starttime).strftime("%Y-%m-%dT%H:%M:%S") UTCDateTime(endtime).strftime("%Y-%m-%dT%H:%M:%S") # create spatial filters (min(min_latitude, max_latitude), min(min_longitude, max_longitude)) (max(min_latitude, max_latitude), max(min_longitude, max_longitude)) # instruments attribute _AttributePlugin({'Instruments': 'true'})) else: _AttributePlugin({'Instruments': 'false'})) # modified_after attribute dt = UTCDateTime(modified_after).strftime("%Y-%m-%dT%H:%M:%S") client.options.plugins.append( _AttributePlugin({'ModifiedAfter': dt})) # add version attribute needed for instruments _AttributePlugin({'Version': '1.0'})) # request data spatialbounds) # response is a full SOAP response # export XML prepending a XML declaration else: # response is a SUDS object
endtime, format="MSEED"): """ Retrieves waveform data from the NERIES Web service and returns a ObsPy Stream object.
:type network: str :param network: Network code, e.g. ``'BW'``. :type station: str :param station: Station code, e.g. ``'MANZ'``. :type location: str :param location: Location code, e.g. ``'01'``. Location code may contain wild cards. :type channel: str :param channel: Channel code, e.g. ``'EHE'``. . Channel code may contain wild cards. :type starttime: :class:`~obspy.core.utcdatetime.UTCDateTime` :param starttime: Start date and time. :type endtime: :class:`~obspy.core.utcdatetime.UTCDateTime` :param endtime: End date and time. :type format: ``'FSEED'`` or ``'MSEED'``, optional :param format: Output format. Either as full SEED (``'FSEED'``) or Mini-SEED (``'MSEED'``) volume. Defaults to ``'MSEED'``. :return: ObsPy :class:`~obspy.core.stream.Stream` object.
.. rubric:: Example
>>> from obspy.neries import Client >>> client = Client(user='test@obspy.org') >>> dt = UTCDateTime("2009-04-01T00:00:00") >>> st = client.getWaveform("NL", "WIT", "", "BH*", dt, dt+30) >>> print st # doctest: +ELLIPSIS 3 Trace(s) in Stream: NL.WIT..BHZ | 2009-04-01T00:00:00.010200Z - ... | 40.0 Hz, 1201 samples NL.WIT..BHN | 2009-04-01T00:00:00.010200Z - ... | 40.0 Hz, 1201 samples NL.WIT..BHE | 2009-04-01T00:00:00.010200Z - ... | 40.0 Hz, 1201 samples """ starttime, endtime, format=format) # read stream using obspy.mseed except: stream = Stream() # remove temporary file: except: pass # trim stream
starttime, endtime, format="MSEED"): """ Writes a retrieved waveform directly into a file.
This method ensures the storage of the unmodified waveform data delivered by the NERIES Web service, e.g. preserving the record based quality flags of MiniSEED files which would be neglected reading it with obspy.mseed.
:type filename: str :param filename: Name of the output file. :type network: str :param network: Network code, e.g. ``'BW'``. :type station: str :param station: Station code, e.g. ``'MANZ'``. :type location: str :param location: Location code, e.g. ``'01'``. Location code may contain wild cards. :type channel: str :param channel: Channel code, e.g. ``'EHE'``. . Channel code may contain wild cards. :type starttime: :class:`~obspy.core.utcdatetime.UTCDateTime` :param starttime: Start date and time. :type endtime: :class:`~obspy.core.utcdatetime.UTCDateTime` :param endtime: End date and time. :type format: ``'FSEED'`` or ``'MSEED'``, optional :param format: Output format. Either as full SEED (``'FSEED'``) or Mini-SEED (``'MSEED'``) volume. Defaults to ``'MSEED'``. :return: None
.. seealso:: http://www.orfeus-eu.org/wsdl/seismolink/seismolink.wsdl
.. rubric:: Example
>>> from obspy.neries import Client >>> c = Client(user='test@obspy.org') >>> dt = UTCDateTime("2009-04-01T00:00:00") >>> st = c.saveWaveform("outfile.fseed", "NL", "WIT", "", "BH*", ... dt, dt+30, format="FSEED") #doctest: +SKIP """ # enable logging if debug option is set if self.debug: import logging logging.basicConfig(level=logging.INFO) logging.getLogger('suds.client').setLevel(logging.DEBUG) # initialize client # set cache of 5 days # create user token # create station filter # adding default record length (4096) * delta to start and end time to # ensure right date times # XXX: 4096 may be overkill (UTCDateTime(starttime) - delta).strftime("%Y-%m-%dT%H:%M:%S") (UTCDateTime(endtime) + delta).strftime("%Y-%m-%dT%H:%M:%S") # request data # start data request # filter for request ids return # check status using request ids # if we hit MAX_REQUESTS break the loop msg = 'MAX_REQUESTS exceeded - breaking current request loop' warnings.warn(msg, UserWarning) break # retry until all are set to 'true' # keep only request ids which are fulfilled and have 'status = OK' if 'Status: OK' in r.StatusDescription and r.Fulfillment == 100] return # retrieve download URLs using request ids # create file handler if a file name is given else: msg = "Parameter filename must be either string or file handler." raise TypeError(msg) # clean up
if __name__ == '__main__': import doctest doctest.testmod(exclude_empty=True) |