Ejemplo n.º 1
0
def print_syngine_models():
    """
    Function to print available syngine models
    :return:
    """
    print("\n------------------------")
    print("Available syngine models")
    print("------------------------\n")

    from obspy.clients.syngine import Client as Client_syngine
    client_syngine = Client_syngine()
    avail_syngine_models = client_syngine.get_available_models()

    for count_mod, avail_mod in enumerate(avail_syngine_models.keys()):
        print('%s. %s' % (count_mod + 1, avail_mod))
    print('\n')
    for count_mod, avail_mod in enumerate(avail_syngine_models.keys()):
        print("------------------------")
        print('%s. %s' % (count_mod + 1, avail_mod))
        for inf in avail_syngine_models[avail_mod].keys():
            print("%s: %s" % (inf, avail_syngine_models[avail_mod][inf]))

    print("\n============================================================")
    print("This is the list of all available syngine models that can be")
    print("used for --syngine_bg_model option.")
    print("============================================================")
    sys.exit()
Ejemplo n.º 2
0
    def __init__(self, parent=None):
        super(SyntheticsGeneratorDialog, self).__init__(parent)
        self.setupUi(self)

        if parent is not None:
            self.setWindowIcon(parent.windowIcon())

        self.setWindowTitle('Synthetics Generator Dialog')

        self.progress_dialog = pw.QProgressDialog(self)
        self.progress_dialog.setRange(0, 0)
        self.progress_dialog.setLabelText('Requesting synthetic waveforms.')
        self.progress_dialog.setWindowIcon(self.windowIcon())
        self.progress_dialog.setWindowTitle(self.windowTitle())
        self.progress_dialog.close()
        self._client = Client()
        self.comboBoxModels.addItems(
            self._client.get_available_models().keys())
        self.radioButtonMT.toggled.connect(self._buttonMTFPClicked)
        self.radioButtonMT.setChecked(True)
        self._buttonMTFPClicked(True)
        self.pushButtonAddStation.clicked.connect(
            self._buttonAddStationClicked)
        self.pushButtonRemStation.setEnabled(False)
        self.pushButtonRemStation.clicked.connect(
            self._buttonRemoveStationClicked)
        self.tableWidget.setSelectionBehavior(pw.QAbstractItemView.SelectRows)
        self.tableWidget.itemSelectionChanged.connect(
            lambda: self.pushButtonRemStation.setEnabled(
                bool(self.tableWidget.selectedIndexes())))
        self.buttonBox.clicked.connect(self._buttonBoxClicked)
Ejemplo n.º 3
0
def get_synt(cmtfilename, outputdir, inventory):

    # Cmtsource
    cmtsource = lseis.CMTSource.from_CMTSOLUTION_file(cmtfilename)

    # Get synthetic seismograms
    client = Client()

    # Download Dict
    ddict = dict(
        model="ak135f_5s",
        components="RTZ",
        sourcelatitude=cmtsource.latitude,
        sourcelongitude=cmtsource.longitude,
        sourcedepthinmeters=cmtsource.depth_in_m,
        sourcemomenttensor=cmtsource.tensor * 1e-7,  # to Nm
        origintime=cmtsource.origin_time,
        starttime=cmtsource.origin_time - 30.0,
        endtime=cmtsource.origin_time + 3700.0,
        units='displacement',
        scale=1.0,
    )

    # List of stations
    bulk = [
        dict(networkcode=f"{_net}",
             stationcode=f"{_sta}",
             latitude=_lat,
             longitude=_lon) for _net, _sta, _lat, _lon in zip(
                 *lseis.inv2net_sta(inv), *lseis.inv2geoloc(inv))
    ]

    # Get bulk waveforms
    syntdir = os.path.join(outputdir, "synt")
    syntfilename = os.path.join(syntdir, "synt.mseed")

    # Download if synthetic is now downloaded yet
    if os.path.exists(syntfilename) is False:

        # Create directory if not existent
        if os.path.exists(syntdir) is False:
            # Make directory
            os.makedirs(syntdir)

        # Download new data
        st = client.get_waveforms_bulk(bulk=bulk,
                                       **ddict,
                                       filename=syntfilename)
    st = read(syntfilename)

    return st
Ejemplo n.º 4
0
# %matplotlib inline

import obspy
import numpy as np

from obspy.clients.syngine import Client

import itertools

import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap

plt.style.use("seaborn-paper")

# + {"deletable": true, "editable": true}
c = Client()

# + {"deletable": true, "editable": true}
# Get seismograms for various strike values.
_d_plane_crossing = []

for strike in np.linspace(85, 95, 11):
    print(strike)
    _d_plane_crossing.append(
        (strike,
         c.get_waveforms(model="ak135f_5s",
                         receiverlatitude=0.0,
                         receiverlongitude=0.0,
                         sourcelatitude=0.0,
                         sourcelongitude=30.0,
                         components="Z",
Ejemplo n.º 5
0
#
# This notebook creates a plot for seismograms for all models part of Syngine.
# Requires matplotlib >= 1.5 and an ObsPy version (>= 1.0) with the Syngine client.
#
# ##### Authors:
# * Lion Krischer ([@krischer](https://github.com/krischer))

# + {"deletable": true, "editable": true}
# %matplotlib inline
import obspy
import matplotlib.pyplot as plt
import numpy as np
plt.style.use("seaborn-whitegrid")

from obspy.clients.syngine import Client
c = Client()

# + {"deletable": true, "editable": true}
# Get all available models for the Syngine service.
models = c.get_available_models()
models

# + {"deletable": true, "editable": true}
# Chile earthquake 2015-09-16 22:55:22 Mw 8.3
event_id = "GCMT:C201509162254A"

# + {"deletable": true, "editable": true, "cell_type": "markdown"}
# ```
# Date-Time (UTC): 	2015-09-16 22:55:22
# Location: 	OFF COAST OF CENTRAL CHILE
# Latitude, Longitude: 	-31.130 °, -72.090 °
Ejemplo n.º 6
0
class SyntheticsGeneratorDialog(pw.QDialog,
                                UiSyntheticsGeneratorDialog,
                                metaclass=SettingsLoader):
    def __init__(self, parent=None):
        super(SyntheticsGeneratorDialog, self).__init__(parent)
        self.setupUi(self)

        if parent is not None:
            self.setWindowIcon(parent.windowIcon())

        self.setWindowTitle('Synthetics Generator Dialog')

        self.progress_dialog = pw.QProgressDialog(self)
        self.progress_dialog.setRange(0, 0)
        self.progress_dialog.setLabelText('Requesting synthetic waveforms.')
        self.progress_dialog.setWindowIcon(self.windowIcon())
        self.progress_dialog.setWindowTitle(self.windowTitle())
        self.progress_dialog.close()
        self._client = Client()
        self.comboBoxModels.addItems(
            self._client.get_available_models().keys())
        self.radioButtonMT.toggled.connect(self._buttonMTFPClicked)
        self.radioButtonMT.setChecked(True)
        self._buttonMTFPClicked(True)
        self.pushButtonAddStation.clicked.connect(
            self._buttonAddStationClicked)
        self.pushButtonRemStation.setEnabled(False)
        self.pushButtonRemStation.clicked.connect(
            self._buttonRemoveStationClicked)
        self.tableWidget.setSelectionBehavior(pw.QAbstractItemView.SelectRows)
        self.tableWidget.itemSelectionChanged.connect(
            lambda: self.pushButtonRemStation.setEnabled(
                bool(self.tableWidget.selectedIndexes())))
        self.buttonBox.clicked.connect(self._buttonBoxClicked)

        # TODO Add inventory for selecting stations database location.

    def closeEvent(self, ce):
        self.load_values()

    def __load__(self):
        self.load_values()

    def _buttonBoxClicked(self, button):
        if (pw.QDialogButtonBox.ApplyRole == self.buttonBox.buttonRole(button)
            ):
            if not self.tableWidget.rowCount():
                pw.QMessageBox.warning(
                    self, self.windowTitle(),
                    "At least one station must be inserted")
                return
            bulk = []
            for i in range(self.tableWidget.rowCount()):
                lat_str = self.tableWidget.item(i, 0).data(0)
                lon_str = self.tableWidget.item(i, 1).data(0)

                if lat_str and lon_str:
                    try:
                        lat = float(lat_str)
                        lon = float(lon_str)
                    except ValueError:
                        pw.QMessageBox.warning(
                            self, self.windowTitle(),
                            f"Lat/lon not valid numbers at row {i + 1}")
                        return
                    if not (-90 <= lat <= 90 and -180 <= lon <= 180):
                        pw.QMessageBox.warning(
                            self, self.windowTitle(),
                            f"Lat/lon out of range at row {i + 1}")
                        return

                net = self.tableWidget.item(i, 2).data(0)
                stat = self.tableWidget.item(i, 3).data(0)
                if lat_str and lon_str and net and stat:
                    bulk.append({
                        "latitude": lat,
                        "longitude": lon,
                        "networkcode": net,
                        "stationcode": stat
                    })
                elif lat_str and lon_str and not net and not stat:
                    bulk.append([lat, lon])
                elif net and stat and not lat_str and not lon_str:
                    bulk.append([net, stat])
                else:
                    message = (f"Invalid station at row {i + 1}. Must insert"
                               f"lat/lon or net/stat or the four parameters.")
                    pw.QMessageBox.warning(self, self.windowTitle(), message)
                    return

            params = {
                "model": self.comboBoxModels.currentText(),
                "bulk": bulk,
                "sourcelatitude": self.doubleSBSrcLat.value(),
                "sourcelongitude": self.doubleSBSrcLon.value(),
                "sourcedepthinmeters": self.doubleSBDep.value(),
                "units": self.unitsCB.currentText(),
                "origintime":
                self.dateTimeEditOrigin.dateTime().toPyDateTime(),
                "starttime": self.dateTimeEditStart.dateTime().toPyDateTime(),
                "endtime": self.dateTimeEditEnd.dateTime().toPyDateTime(),
                "format": "miniseed"
            }

            if self.radioButtonMT.isChecked():
                mrr_str = self.lineEditMrr.text()
                mtt_str = self.lineEditMtt.text()
                mpp_str = self.lineEditMpp.text()
                mrt_str = self.lineEditMrt.text()
                mrp_str = self.lineEditMrp.text()
                mtp_str = self.lineEditMtp.text()
                if (not mrr_str or not mtt_str or not mpp_str or not mrt_str
                        or not mrp_str or not mtp_str):
                    pw.QMessageBox.warning(
                        self, self.windowTitle(),
                        "Some moment tensor value is missing")
                    return
                try:
                    mrr = float(mrr_str)
                    mtt = float(mtt_str)
                    mpp = float(mpp_str)
                    mrt = float(mrt_str)
                    mrp = float(mrp_str)
                    mtp = float(mtp_str)
                except ValueError:
                    pw.QMessageBox.warning(self, self.windowTitle(),
                                           "Moment tensor values are invalid")
                    return
                mtparams = [mrr, mtt, mpp, mrt, mrp, mtp]
                params["sourcemomenttensor"] = mtparams
            else:
                fpparams = [
                    self.doubleSBStrike.value(),
                    self.doubleSBDip.value(),
                    self.doubleSBRake.value()
                ]
                if self.lineEditM0.text():
                    try:
                        m0 = float(self.lineEditM0.text())
                        fpparams.append(m0)
                    except:
                        pw.QMessageBox.warning(self, self.windowTitle(),
                                               "M0 value is invalid")
                        return

                params["sourcedoublecouple"] = fpparams

            with ThreadPoolExecutor(1) as executor:
                f = executor.submit(lambda: self._requestSynthetics(params))
                r = self.progress_dialog.exec()
                if r == pw.QDialog.Accepted:
                    st = f.result()
                    if not st:
                        pw.QMessageBox.warning(
                            self, self.windowTitle(),
                            "Synthetics generator request failed.")
                        return

                    if "darwin" == platform:
                        dir_path = pw.QFileDialog.getExistingDirectory(
                            self, 'Select Directory')
                    else:
                        dir_path = pw.QFileDialog.getExistingDirectory(
                            self, 'Select Directory', '',
                            pw.QFileDialog.DontUseNativeDialog)
                    if not dir_path:
                        return

                    for tr in st:
                        path_output = os.path.join(dir_path, tr.id)
                        tr.write(path_output, format="MSEED")
                    current = datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
                    name = 'generation_params' + current + '.pkl'
                    with open(os.path.join(dir_path, name), 'wb') as f:
                        pickle.dump(params, f)

                    self.save_values()

                    pw.QMessageBox.information(
                        self, self.windowTitle(),
                        "Synthetics generation done !!!")

    def _requestSynthetics(self, params):
        try:
            st = self._client.get_waveforms_bulk(**params)
        except Exception as e:
            print(e)

        pyc.QMetaObject.invokeMethod(self.progress_dialog, 'accept',
                                     qt.QueuedConnection)
        return st

    def _buttonAddStationClicked(self):
        self.tableWidget.setRowCount(self.tableWidget.rowCount() + 1)
        item = pw.QTableWidgetItem()
        self.tableWidget.setItem(self.tableWidget.rowCount() - 1, 0, item)
        item = pw.QTableWidgetItem()
        self.tableWidget.setItem(self.tableWidget.rowCount() - 1, 1, item)
        item = pw.QTableWidgetItem()
        self.tableWidget.setItem(self.tableWidget.rowCount() - 1, 2, item)
        item = pw.QTableWidgetItem()
        self.tableWidget.setItem(self.tableWidget.rowCount() - 1, 3, item)

    def _buttonRemoveStationClicked(self):
        rows = self.tableWidget.selectionModel().selectedRows()
        if rows:
            rows = [r.row() for r in rows]
            rows.sort(reverse=True)
            for r in rows:
                self.tableWidget.removeRow(r)

    def _buttonMTFPClicked(self, mt_checked):
        # When button 0 (MT) is clicked, activate MT parameters
        # and disable FP parameters and viceversa.
        self.groupBoxMT.setEnabled(mt_checked)
        self.groupBoxFP.setEnabled(not mt_checked)
Ejemplo n.º 7
0
class ClientTestCase(unittest.TestCase):
    """
    Test cases for obspy.clients.iris.client.Client.
    """
    c = Client(user_agent=DEFAULT_TESTING_USER_AGENT)

    def test_get_model_info_mock(self):
        """
        Mock test for the get_model_info() method.
        """
        with mock.patch("requests.get") as p:
            r = RequestsMockResponse()
            r._json["slip"] = [0.0, 1.0, 2.0]
            r._json["sliprate"] = [0.0, 1.0, 2.0]
            p.return_value = r
            self.c.get_model_info("test_model")

        self.assertEqual(p.call_count, 1)
        self.assertEqual(p.call_args[1]["url"],
                         'http://service.iris.edu/irisws/syngine/1/info')
        self.assertEqual(p.call_args[1]["params"], {'model': 'test_model'})
        self.assertEqual(p.call_args[1]["headers"],
                         {'User-Agent': DEFAULT_TESTING_USER_AGENT})

    def test_get_model_info(self):
        """
        Actual test for the get_model_info() method.
        """
        info = self.c.get_model_info("test")

        self.assertIsInstance(info, obspy.core.AttribDict)
        # Check two random keys.
        self.assertEqual(info.dump_type, "displ_only")
        self.assertEqual(info.time_scheme, "newmark2")
        # Check that both arrays have been converted to numpy arrays.
        self.assertIsInstance(info.slip, np.ndarray)
        self.assertIsInstance(info.sliprate, np.ndarray)

    def test_get_available_models_mock(self):
        with mock.patch("requests.get") as p:
            p.return_value = RequestsMockResponse()
            self.c.get_available_models()

        self.assertEqual(p.call_count, 1)
        self.assertEqual(p.call_args[1]["url"],
                         'http://service.iris.edu/irisws/syngine/1/models')
        self.assertEqual(p.call_args[1]["params"], None)
        self.assertEqual(p.call_args[1]["headers"],
                         {'User-Agent': DEFAULT_TESTING_USER_AGENT})

    def test_get_available_models(self):
        models = self.c.get_available_models()
        self.assertIsInstance(models, dict)
        self.assertGreater(len(models), 3)
        self.assertIn("ak135f_5s", models)
        # Check random key.
        self.assertEqual(models["ak135f_5s"]["components"],
                         "vertical and horizontal")

    def test_get_service_version_mock(self):
        with mock.patch("requests.get") as p:
            p.return_value = RequestsMockResponse()
            p.return_value.text = "1.2.3"
            version = self.c.get_service_version()

        self.assertEqual(version, "1.2.3")

        self.assertEqual(p.call_count, 1)
        self.assertEqual(p.call_args[1]["url"],
                         'http://service.iris.edu/irisws/syngine/1/version')
        self.assertEqual(p.call_args[1]["params"], None)
        self.assertEqual(p.call_args[1]["headers"],
                         {'User-Agent': DEFAULT_TESTING_USER_AGENT})

    def test_get_waveforms_mock(self):
        """
        Test the queries from the IRIS syngine website and see if they
        produce the correct URLS.
        """
        r = RequestsMockResponse()
        with io.BytesIO() as buf:
            obspy.read()[0].write(buf, format="mseed")
            buf.seek(0, 0)
            r.content = buf.read()

        # http://service.iris.edu/irisws/syngine/1/query?network=IU&
        # station=ANMO&components=ZRT&eventid=GCMT:M110302J
        with mock.patch("requests.get") as p:
            p.return_value = r
            st = self.c.get_waveforms(model="ak135f_5s",
                                      network="IU",
                                      station="ANMO",
                                      components="ZRT",
                                      eventid="GCMT:M110302J")

        self.assertIsInstance(st, obspy.Stream)

        self.assertEqual(p.call_count, 1)
        self.assertEqual(p.call_args[1]["url"],
                         "http://service.iris.edu/irisws/syngine/1/query")
        self.assertEqual(
            p.call_args[1]["params"], {
                "components": "ZRT",
                "eventid": "GCMT:M110302J",
                "format": "miniseed",
                "model": "ak135f_5s",
                "network": "IU",
                "station": "ANMO"
            })
        self.assertEqual(p.call_args[1]["headers"],
                         {"User-Agent": DEFAULT_TESTING_USER_AGENT})

        # http://service.iris.edu/irisws/syngine/1/query?network=_GSN&
        # components=Z&eventid=GCMT:M110302J&endtime=1800
        with mock.patch("requests.get") as p:
            p.return_value = r
            st = self.c.get_waveforms(model="ak135f_5s",
                                      network="_GSN",
                                      components="Z",
                                      endtime=1800.0,
                                      eventid="GCMT:M110302J")

        self.assertIsInstance(st, obspy.Stream)

        self.assertEqual(p.call_count, 1)
        self.assertEqual(p.call_args[1]["url"],
                         "http://service.iris.edu/irisws/syngine/1/query")
        self.assertEqual(
            p.call_args[1]["params"], {
                "components": native_str("Z"),
                "endtime": native_str(1800.0),
                "eventid": native_str("GCMT:M110302J"),
                "format": native_str("miniseed"),
                "model": native_str("ak135f_5s"),
                "network": native_str("_GSN")
            })
        self.assertEqual(p.call_args[1]["headers"],
                         {"User-Agent": DEFAULT_TESTING_USER_AGENT})

        # http://service.iris.edu/irisws/syngine/1/query?network=_GSN&
        # components=Z&eventid=GCMT:M110302J&starttime=P-10&endtime=ScS%2B60
        with mock.patch("requests.get") as p:
            p.return_value = r
            st = self.c.get_waveforms(model="ak135f_5s",
                                      network="_GSN",
                                      components="Z",
                                      starttime="P-10",
                                      endtime="ScS+60",
                                      eventid="GCMT:M110302J")

        self.assertIsInstance(st, obspy.Stream)

        self.assertEqual(p.call_count, 1)
        self.assertEqual(p.call_args[1]["url"],
                         "http://service.iris.edu/irisws/syngine/1/query")
        self.assertEqual(
            p.call_args[1]["params"], {
                "components": native_str("Z"),
                "starttime": native_str("P-10"),
                "endtime": native_str("ScS+60"),
                "eventid": native_str("GCMT:M110302J"),
                "format": native_str("miniseed"),
                "model": native_str("ak135f_5s"),
                "network": native_str("_GSN")
            })
        self.assertEqual(p.call_args[1]["headers"],
                         {"User-Agent": DEFAULT_TESTING_USER_AGENT})

    def test_error_handling_arguments(self):
        # Floating points value
        with self.assertRaises(ValueError):
            self.c.get_waveforms(model="test", receiverlatitude="a")
        # Int.
        with self.assertRaises(ValueError):
            self.c.get_waveforms(model="test", kernelwidth="a")
        # Time.
        with self.assertRaises(TypeError):
            self.c.get_waveforms(model="test", origintime="a")

    def test_source_mechanisms_mock(self):
        r = RequestsMockResponse()
        with io.BytesIO() as buf:
            obspy.read()[0].write(buf, format="mseed")
            buf.seek(0, 0)
            r.content = buf.read()

        with mock.patch("requests.get") as p:
            p.return_value = r
            self.c.get_waveforms(model="ak135f_5s",
                                 sourcemomenttensor=[1, 2, 3, 4, 5, 6])
        self.assertEqual(p.call_count, 1)
        self.assertEqual(p.call_args[1]["url"],
                         "http://service.iris.edu/irisws/syngine/1/query")
        self.assertEqual(
            p.call_args[1]["params"], {
                "model": native_str("ak135f_5s"),
                "format": native_str("miniseed"),
                "sourcemomenttensor": "1,2,3,4,5,6"
            })

        with mock.patch("requests.get") as p:
            p.return_value = r
            self.c.get_waveforms(model="ak135f_5s",
                                 sourcedoublecouple=[1, 2, 3, 4])
        self.assertEqual(p.call_count, 1)
        self.assertEqual(p.call_args[1]["url"],
                         "http://service.iris.edu/irisws/syngine/1/query")
        self.assertEqual(
            p.call_args[1]["params"], {
                "model": native_str("ak135f_5s"),
                "format": native_str("miniseed"),
                "sourcedoublecouple": "1,2,3,4"
            })

        with mock.patch("requests.get") as p:
            p.return_value = r
            self.c.get_waveforms(model="ak135f_5s",
                                 sourceforce=[3.32, 4.23, 5.11])
        self.assertEqual(p.call_count, 1)
        self.assertEqual(p.call_args[1]["url"],
                         "http://service.iris.edu/irisws/syngine/1/query")
        self.assertEqual(
            p.call_args[1]["params"], {
                "model": native_str("ak135f_5s"),
                "format": native_str("miniseed"),
                "sourceforce": "3.32,4.23,5.11"
            })

    def test_error_handling(self):
        """
        Tests the error handling. The clients just pass on most things to
        syngine and rely on the service for the error detection.
        """
        # Wrong components.
        with self.assertRaises(ClientHTTPException) as cm:
            self.c.get_waveforms(model="ak135f_5s",
                                 eventid="GCMT:C201002270634A",
                                 station="ANMO",
                                 network="IU",
                                 components="ABC")

        msg = cm.exception.args[0]
        self.assertIn("HTTP code 400 when", msg)
        self.assertIn("Unrecognized component", msg)

    def test_bulk_waveform_download_mock(self):
        """
        Mock the bulk download requests to test the payload generation.
        """
        r = RequestsMockResponse()
        with io.BytesIO() as buf:
            obspy.read()[0].write(buf, format="mseed")
            buf.seek(0, 0)
            r.content = buf.read()

        payload = []

        def side_effect(*args, **kwargs):
            payload[:] = [kwargs["data"].decode()]
            return r

        # Test simple lists first.
        with mock.patch("requests.post") as p:
            p.side_effect = side_effect
            self.c.get_waveforms_bulk(model="ak135f_5s",
                                      bulk=[[1.0, 2.0], (2.0, 3.0),
                                            ("AA", "BB")])

        self.assertEqual(
            payload[0], "\n".join([
                "model=ak135f_5s", "format=miniseed", "1.0 2.0", "2.0 3.0",
                "AA BB\n"
            ]))

        # A couple more parameters
        with mock.patch("requests.post") as p:
            p.side_effect = side_effect
            self.c.get_waveforms_bulk(model="ak135f_5s",
                                      bulk=[[1.0, 2.0], (2.0, 3.0),
                                            ("AA", "BB")],
                                      format="miniseed",
                                      sourcemomenttensor=[1, 2, 3, 4, 5, 6])

        self.assertEqual(
            payload[0], "\n".join([
                "model=ak135f_5s", "format=miniseed",
                "sourcemomenttensor=1,2,3,4,5,6", "1.0 2.0", "2.0 3.0",
                "AA BB\n"
            ]))

        # A couple of dictionaries.
        with mock.patch("requests.post") as p:
            p.side_effect = side_effect
            self.c.get_waveforms_bulk(model="ak135f_5s",
                                      bulk=[{
                                          "network": "IU",
                                          "station": "ANMO"
                                      }, {
                                          "latitude": 12,
                                          "longitude": 13.1
                                      }, {
                                          "latitude": 12,
                                          "longitude": 13.1,
                                          "networkcode": "IU"
                                      }, {
                                          "latitude": 12,
                                          "longitude": 13.1,
                                          "stationcode": "ANMO"
                                      }, {
                                          "latitude": 12,
                                          "longitude": 13.1,
                                          "locationcode": "00"
                                      }, {
                                          "latitude": 12,
                                          "longitude": 13.1,
                                          "networkcode": "IU",
                                          "stationcode": "ANMO",
                                          "locationcode": "00"
                                      }],
                                      format="miniseed",
                                      eventid="GCMT:C201002270634A")

        self.assertEqual(
            payload[0], "\n".join([
                "model=ak135f_5s", "eventid=GCMT:C201002270634A",
                "format=miniseed", "IU ANMO", "12 13.1", "12 13.1 NETCODE=IU",
                "12 13.1 STACODE=ANMO", "12 13.1 LOCCODE=00",
                "12 13.1 NETCODE=IU STACODE=ANMO LOCCODE=00\n"
            ]))

    def test_get_waveforms(self):
        """
        Test get_waveforms() and get_waveforms_bulk() by actually downloading
        some things.

        Use the 'test' model which does not produce useful seismograms but
        is quick to test.
        """
        st = self.c.get_waveforms(model="test",
                                  network="IU",
                                  station="ANMO",
                                  eventid="GCMT:C201002270634A",
                                  components="Z")
        self.assertEqual(len(st), 1)
        # Download exactly the same with a bulk request and check the result
        # is the same!
        st_bulk = self.c.get_waveforms_bulk(model="test",
                                            bulk=[("IU", "ANMO")],
                                            eventid="GCMT:C201002270634A",
                                            components="Z")
        self.assertEqual(len(st_bulk), 1)
        self.assertEqual(st, st_bulk)

        # Test phase relative times. This tests that everything is correctly
        # encoded and what not.
        st = self.c.get_waveforms(model="test",
                                  network="IU",
                                  station="ANMO",
                                  eventid="GCMT:C201002270634A",
                                  starttime="P-10",
                                  endtime="P+20",
                                  components="Z")
        self.assertEqual(len(st), 1)
        st_bulk = self.c.get_waveforms_bulk(model="test",
                                            bulk=[("IU", "ANMO")],
                                            starttime="P-10",
                                            endtime="P+20",
                                            eventid="GCMT:C201002270634A",
                                            components="Z")
        self.assertEqual(len(st_bulk), 1)
        self.assertEqual(st, st_bulk)

        # One to test a source mechanism
        st = self.c.get_waveforms(model="test",
                                  network="IU",
                                  station="ANMO",
                                  sourcemomenttensor=[1, 2, 3, 4, 5, 6],
                                  sourcelatitude=10,
                                  sourcelongitude=20,
                                  sourcedepthinmeters=100,
                                  components="Z")
        self.assertEqual(len(st), 1)
        st_bulk = self.c.get_waveforms_bulk(
            model="test",
            bulk=[("IU", "ANMO")],
            sourcemomenttensor=[1, 2, 3, 4, 5, 6],
            sourcelatitude=10,
            sourcelongitude=20,
            sourcedepthinmeters=100,
            components="Z")
        self.assertEqual(len(st_bulk), 1)
        self.assertEqual(st, st_bulk)

        # One more to test actual time values.
        st = self.c.get_waveforms(
            model="test",
            network="IU",
            station="ANMO",
            origintime=obspy.UTCDateTime(2015, 1, 2, 3, 0, 5),
            starttime=obspy.UTCDateTime(2015, 1, 2, 3, 4, 5),
            endtime=obspy.UTCDateTime(2015, 1, 2, 3, 10, 5),
            sourcemomenttensor=[1, 2, 3, 4, 5, 6],
            sourcelatitude=10,
            sourcelongitude=20,
            sourcedepthinmeters=100,
            components="Z")
        self.assertEqual(len(st), 1)
        st_bulk = self.c.get_waveforms_bulk(
            model="test",
            bulk=[("IU", "ANMO")],
            origintime=obspy.UTCDateTime(2015, 1, 2, 3, 0, 5),
            starttime=obspy.UTCDateTime(2015, 1, 2, 3, 4, 5),
            endtime=obspy.UTCDateTime(2015, 1, 2, 3, 10, 5),
            sourcemomenttensor=[1, 2, 3, 4, 5, 6],
            sourcelatitude=10,
            sourcelongitude=20,
            sourcedepthinmeters=100,
            components="Z")
        self.assertEqual(len(st_bulk), 1)
        self.assertEqual(st, st_bulk)

    def test_saving_directly_to_file(self):
        # Save to a filename.
        with NamedTemporaryFile() as tf:
            filename = tf.name
            st = self.c.get_waveforms(model="test",
                                      network="IU",
                                      station="ANMO",
                                      eventid="GCMT:C201002270634A",
                                      starttime="P-10",
                                      endtime="P+10",
                                      components="Z",
                                      filename=tf)
            # No return value.
            self.assertTrue(st is None)

            st = obspy.read(filename)
            self.assertEqual(len(st), 1)

        # Save to an open file-like object.
        with io.BytesIO() as buf:
            st = self.c.get_waveforms(model="test",
                                      network="IU",
                                      station="ANMO",
                                      eventid="GCMT:C201002270634A",
                                      starttime="P-10",
                                      endtime="P+10",
                                      components="Z",
                                      filename=buf)
            # No return value.
            self.assertTrue(st is None)

            buf.seek(0, 0)
            st = obspy.read(buf)
            self.assertEqual(len(st), 1)

    def test_reading_saczip_files(self):
        st = self.c.get_waveforms(model="test",
                                  network="IU",
                                  station="ANMO",
                                  eventid="GCMT:C201002270634A",
                                  starttime="P-10",
                                  endtime="P+10",
                                  components="Z",
                                  format="saczip")
        self.assertEqual(len(st), 1)
        # Same with bulk request.
        st_bulk = self.c.get_waveforms_bulk(model="test",
                                            bulk=[("IU", "ANMO")],
                                            eventid="GCMT:C201002270634A",
                                            starttime="P-10",
                                            endtime="P+10",
                                            components="Z",
                                            format="saczip")
        self.assertEqual(len(st_bulk), 1)

        self.assertEqual(st, st_bulk)

    def test_bulk_waveform_send_custom_payload(self):
        """
        The get_waveforms_bulk() method can send a custom payload.
        """
        r = RequestsMockResponse()
        with io.BytesIO() as buf:
            obspy.read()[0].write(buf, format="mseed")
            buf.seek(0, 0)
            r.content = buf.read()

        payload = []

        def side_effect(*args, **kwargs):
            payload[:] = [kwargs["data"]]
            return r

        # Test simple lists first.
        with mock.patch("requests.post") as p:
            p.side_effect = side_effect
            self.c.get_waveforms_bulk(model="ak135f_5s",
                                      bulk=[],
                                      data=b"1234\n5678")

        self.assertEqual(payload[0], b"1234\n5678")
Ejemplo n.º 8
0
# ---
#
# # Figure 1: Phase Relative Time
#
# This notebook is part of the supplementary materials for the Syngine paper and reproduces figure 1.
#
# This notebook creates the phase relative times figure. Requires matplotlib >= 1.5 and an ObsPy version (>= 1.0) with the syngine client.
#
# ##### Authors:
# * Lion Krischer ([@krischer](https://github.com/krischer))

# + {"deletable": true, "editable": true}
# %matplotlib inline
import obspy
from obspy.clients.syngine import Client
c = Client()

# + {"deletable": true, "editable": true}
# Define latitude/longitude for a bunch of receivers.
bulk = [[0.0, 20.0], [0.0, 30.0], [0.0, 40.0], [0.0, 50.0], [0.0, 60.0],
        [0.0, 70.0], [0.0, 80.0], [0.0, 90.0]]

# Request them all at once.
st = c.get_waveforms_bulk(model="ak135f_2s",
                          bulk=bulk,
                          sourcelatitude=0.0,
                          sourcelongitude=0.0,
                          sourcedepthinmeters=600000,
                          starttime="P-50",
                          endtime="S+100",
                          components="Z")
Ejemplo n.º 9
0
#!/usr/bin/python

from obspy.clients.syngine import Client
from obspy import read
from obspy.taup import TauPyModel
from obspy.core import UTCDateTime
from subprocess import call
from sys import stdout, stderr
import numpy as np

client = Client()

##------------------------------------------------------------------------
# we use uniformly distributed random earthquake focal mechanisms to generate
# synthetic seismogram
# The IRIS syngine Green function database have been used
# http://service.iris.edu/irisws/syngine/1/
##-------------------------------------------------------------------------
for i in range(1, 5):
    # the source depth range from 10km to 70km
    evdpinmeter = int(np.random.uniform(10, 70) * 1000)
    strike = int(np.random.uniform(0.1, 1) * 360)
    rake = int(np.random.uniform(0.1, 1) * 180)
    dip = int(np.random.uniform(0.1, 1) * 90)
    # epicenter distance from 30 degree to 90 degree
    dist = np.random.uniform(30, 90)
    # the moment magnitude from 5.5 to 7.5
    mw = np.random.uniform(5.5, 7.5)
    m0 = np.power(10., 1.5 * mw + 9.1)
    model = TauPyModel(model="ak135")
    arrt = model.get_travel_times(source_depth_in_km=evdpinmeter / 1000.,
application = "smi:local/cmtsolution/201501230347A/event"

all_data = []
all_data.extend(training)
all_data.append(validate)
all_data.append(application)

cat.events = [_i for _i in cat.events if _i.resource_id.id in all_data]

print(cat)
cat.plot();

# + {"deletable": true, "editable": true}
# For all of them: download the syngine data 50 seconds before the p-phase
# and 50 seconds after for the 5s ak135f DB.
c_syngine = SyngineClient()

# + {"deletable": true, "editable": true}
# Download all syngine data.
synthetic_data = {}

# Build up bulk request.
bulk = [
    {"networkcode": "CI", "stationcode": _i.code,
     "latitude": _i.latitude, "longitude": _i.longitude} for _i in inv[0]]

# Actually download everything.
for _i, event in enumerate(cat):
    origin = [_i for _i in event.origins if _i.origin_type == "hypocenter"][0]
    mt = event.focal_mechanisms[0].moment_tensor.tensor
    print("Downloading data for event %i of %i ..." % (_i + 1, len(cat)))