Esempio n. 1
0
 def test_sacpz(self):
     """
     Fetches SAC poles and zeros information.
     """
     client = Client()
     # 1
     t1 = UTCDateTime("2005-01-01")
     t2 = UTCDateTime("2008-01-01")
     result = client.sacpz("IU", "ANMO", "00", "BHZ", t1, t2)
     # drop lines with creation date (current time during request)
     result = result.splitlines()
     sacpz_file = os.path.join(self.path, 'data', 'IU.ANMO.00.BHZ.sacpz')
     with open(sacpz_file, 'rb') as fp:
         expected = fp.read().splitlines()
     result.pop(5)
     expected.pop(5)
     self.assertEqual(result, expected)
     # 2 - empty location code
     dt = UTCDateTime("2002-11-01")
     result = client.sacpz('UW', 'LON', '', 'BHZ', dt)
     self.assertIn(b"* STATION    (KSTNM): LON", result)
     self.assertIn(b"* LOCATION   (KHOLE):   ", result)
     # 3 - empty location code via '--'
     result = client.sacpz('UW', 'LON', '--', 'BHZ', dt)
     self.assertIn(b"* STATION    (KSTNM): LON", result)
     self.assertIn(b"* LOCATION   (KHOLE):   ", result)
Esempio n. 2
0
 def test_distaz(self):
     """
     Tests distance and azimuth calculation between two points on a sphere.
     """
     client = Client()
     # normal request
     result = client.distaz(stalat=1.1, stalon=1.2, evtlat=3.2, evtlon=1.4)
     self.assertAlmostEqual(result['distance'], 2.10256)
     self.assertAlmostEqual(result['distancemeters'], 233272.79028)
     self.assertAlmostEqual(result['backazimuth'], 5.46944)
     self.assertAlmostEqual(result['azimuth'], 185.47695)
     self.assertEqual(result['ellipsoidname'], 'WGS84')
     self.assertTrue(isinstance(result['distance'], float))
     self.assertTrue(isinstance(result['distancemeters'], float))
     self.assertTrue(isinstance(result['backazimuth'], float))
     self.assertTrue(isinstance(result['azimuth'], float))
     self.assertTrue(isinstance(result['ellipsoidname'], str))
     # w/o kwargs
     result = client.distaz(1.1, 1.2, 3.2, 1.4)
     self.assertAlmostEqual(result['distance'], 2.10256)
     self.assertAlmostEqual(result['distancemeters'], 233272.79028)
     self.assertAlmostEqual(result['backazimuth'], 5.46944)
     self.assertAlmostEqual(result['azimuth'], 185.47695)
     self.assertEqual(result['ellipsoidname'], 'WGS84')
     # missing parameters
     self.assertRaises(Exception, client.distaz, stalat=1.1)
     self.assertRaises(Exception, client.distaz, 1.1)
     self.assertRaises(Exception, client.distaz, stalat=1.1, stalon=1.2)
     self.assertRaises(Exception, client.distaz, 1.1, 1.2)
Esempio n. 3
0
 def test_sacpz(self):
     """
     Fetches SAC poles and zeros information.
     """
     client = Client()
     # 1
     t1 = UTCDateTime("2005-01-01")
     t2 = UTCDateTime("2008-01-01")
     result = client.sacpz("IU", "ANMO", "00", "BHZ", t1, t2)
     # drop lines with creation date (current time during request)
     result = result.splitlines()
     sacpz_file = os.path.join(self.path, 'data', 'IU.ANMO.00.BHZ.sacpz')
     with open(sacpz_file, 'rb') as fp:
         expected = fp.read().splitlines()
     result.pop(5)
     expected.pop(5)
     self.assertEqual(result, expected)
     # 2 - empty location code
     dt = UTCDateTime("2002-11-01")
     result = client.sacpz('UW', 'LON', '', 'BHZ', dt)
     self.assertIn(b"* STATION    (KSTNM): LON", result)
     self.assertIn(b"* LOCATION   (KHOLE):   ", result)
     # 3 - empty location code via '--'
     result = client.sacpz('UW', 'LON', '--', 'BHZ', dt)
     self.assertIn(b"* STATION    (KSTNM): LON", result)
     self.assertIn(b"* LOCATION   (KHOLE):   ", result)
Esempio n. 4
0
    def test_sim_WA(self):
        """Test feeding both PAZ and seedresp."""
        t1 = UTCDateTime("2010-09-3T16:30:00.000")
        t2 = UTCDateTime("2010-09-3T17:00:00.000")
        fdsn_client = Client('IRIS')
        st = fdsn_client.get_waveforms(
            network='NZ', station='BFZ', location='10', channel='HHZ',
            starttime=t1, endtime=t2, attach_response=True)
        tr = st[0]
        PAZ = {'poles': [-4.440 + 4.440j, -4.440 - 4.440j, -1.083 + 0.0j],
               'zeros': [0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0],
               'sensitivity': 0.4,
               'gain': 60077000.0}
        tr_safe = tr.copy()
        # Test with PAZ
        _sim_WA(trace=tr, PAZ=PAZ, seedresp=None, water_level=10)
        tr = tr_safe.copy()
        # Test without PAZ or seedresp
        _sim_WA(trace=tr, PAZ=None, seedresp=None, water_level=10)
        tr = tr_safe.copy()
        with NamedTemporaryFile() as tf:
            respf = tf.name
            old_iris_client = OldIris_Client()
            # fetch RESP information from "old" IRIS web service, see
            # obspy.fdsn for accessing the new IRIS FDSN web services
            old_iris_client.resp('NZ', 'BFZ', '10', 'HHZ', t1, t2,
                                 filename=respf)
            date = t1

            seedresp = {
                'filename': respf, 'date': date, 'network': tr.stats.network,
                'station': tr.stats.station, 'channel': tr.stats.channel,
                'location': tr.stats.location, 'units': 'DIS'
                        }
            _sim_WA(trace=tr, PAZ=None, seedresp=seedresp, water_level=10)
Esempio n. 5
0
    def test_resp(self):
        """
        Tests resp Web service interface.

        Examples are inspired by https://service.iris.edu/irisws/resp/1/.
        """
        client = Client()
        # 1
        t1 = UTCDateTime("2005-001T00:00:00")
        t2 = UTCDateTime("2008-001T00:00:00")
        result = client.resp("IU", "ANMO", "00", "BHZ", t1, t2)
        self.assertIn(b'B050F03     Station:     ANMO', result)
        # Exception: No response data available
        # 2 - empty location code
        # result = client.resp("UW", "LON", "", "EHZ")
        # self.assertIn(b'B050F03     Station:     LON', result)
        # self.assertIn(b'B052F03     Location:    ??', result)
        # 3 - empty location code via '--'
        # result = client.resp("UW", "LON", "--", "EHZ")
        # self.assertIn(b'B050F03     Station:     LON', result)
        # self.assertIn(b'B052F03     Location:    ??', result)
        # 4
        dt = UTCDateTime("2010-02-27T06:30:00.000")
        result = client.resp("IU", "ANMO", "*", "*", dt)
        self.assertIn(b'B050F03     Station:     ANMO', result)

        dt = UTCDateTime("2005-001T00:00:00")
        result = client.resp("AK", "RIDG", "--", "LH?", dt)
        self.assertIn(b'B050F03     Station:     RIDG', result)
Esempio n. 6
0
    def test_timeseries(self):
        """
        Tests timeseries Web service interface.

        Examples are inspired by https://service.iris.edu/irisws/timeseries/1/.
        """
        client = Client()
        # 1
        t1 = UTCDateTime("2005-001T00:00:00")
        t2 = UTCDateTime("2005-001T00:01:00")
        # no filter
        st1 = client.timeseries("IU", "ANMO", "00", "BHZ", t1, t2)
        # instrument corrected
        st2 = client.timeseries("IU",
                                "ANMO",
                                "00",
                                "BHZ",
                                t1,
                                t2,
                                filter=["correct"])
        # compare results
        self.assertEqual(st1[0].stats.starttime, st2[0].stats.starttime)
        self.assertEqual(st1[0].stats.endtime, st2[0].stats.endtime)
        self.assertEqual(st1[0].data[0], 24)
        self.assertAlmostEqual(st2[0].data[0], -2.8373747e-06)
Esempio n. 7
0
 def test_traveltime(self):
     """
     Tests calculation of travel-times for seismic phases.
     """
     client = Client()
     result = client.traveltime(
         evloc=(-36.122, -72.898), evdepth=22.9,
         staloc=[(-33.45, -70.67), (47.61, -122.33), (35.69, 139.69)])
     self.assertTrue(result.startswith(b'Model: iasp91'))
Esempio n. 8
0
 def test_traveltime(self):
     """
     Tests calculation of travel-times for seismic phases.
     """
     client = Client()
     result = client.traveltime(evloc=(-36.122, -72.898),
                                evdepth=22.9,
                                staloc=[(-33.45, -70.67), (47.61, -122.33),
                                        (35.69, 139.69)])
     self.assertTrue(result.startswith(b'Model: iasp91'))
Esempio n. 9
0
 def test_flinnengdahl(self):
     """
     Tests calculation of Flinn-Engdahl region code or name.
     """
     client = Client()
     # code
     result = client.flinnengdahl(lat=-20.5, lon=-100.6, rtype="code")
     self.assertEqual(result, 683)
     # w/o kwargs
     result = client.flinnengdahl(-20.5, -100.6, "code")
     self.assertEqual(result, 683)
     # region
     result = client.flinnengdahl(lat=42, lon=-122.24, rtype="region")
     self.assertEqual(result, 'OREGON')
     # w/o kwargs
     result = client.flinnengdahl(42, -122.24, "region")
     self.assertEqual(result, 'OREGON')
     # both
     result = client.flinnengdahl(lat=-20.5, lon=-100.6, rtype="both")
     self.assertEqual(result, (683, 'SOUTHEAST CENTRAL PACIFIC OCEAN'))
     # w/o kwargs
     result = client.flinnengdahl(-20.5, -100.6, "both")
     self.assertEqual(result, (683, 'SOUTHEAST CENTRAL PACIFIC OCEAN'))
     # default rtype
     result = client.flinnengdahl(lat=42, lon=-122.24)
     self.assertEqual(result, (32, 'OREGON'))
     # w/o kwargs
     # outside boundaries
     self.assertRaises(Exception, client.flinnengdahl, lat=-90.1, lon=0)
     self.assertRaises(Exception, client.flinnengdahl, lat=90.1, lon=0)
     self.assertRaises(Exception, client.flinnengdahl, lat=0, lon=-180.1)
     self.assertRaises(Exception, client.flinnengdahl, lat=0, lon=180.1)
Esempio n. 10
0
def rotate_traces(event_code, database):
    data_path = f"{database}/{event_code}/synthetics/point_source/"
    filelist = glob.glob(f"{data_path}/*MXZ*.sac")

    cmt_finite_fault = f"{database}/{event_code}/{event_code}"
    cmt_lines = open(cmt_finite_fault).readlines()
    for line in cmt_lines:
        if line.split()[0] == "latitude":
            ev_lat = float(line.split()[1])
        elif line.split()[0] == "longitude":
            ev_lon = float(line.split()[1])
        else:
            continue

    client = Client()
    for Zfile in filelist:
        print(Zfile)
        Nfile = Zfile.replace("MXZ", "MXN")
        Efile = Zfile.replace("MXZ", "MXE")
        Rfile = Zfile.replace("MXZ", "MXR")
        Tfile = Zfile.replace("MXZ", "MXT")

        if os.path.isfile(Nfile) and os.path.isfile(Efile):
            st = read(Zfile)
            st += read(Nfile)
            st += read(Efile)

            Ztr = st[0]
            st_lat = Ztr.stats["sac"]["stla"]
            st_lon = Ztr.stats["sac"]["stlo"]
            station = Ztr.stats.station
            channel = Ztr.stats.channel

            result = client.distaz(stalat=st_lat,
                                   stalon=st_lon,
                                   evtlat=ev_lat,
                                   evtlon=ev_lon)
            baz = result["backazimuth"]
            az = result["azimuth"]
            dist_km = result["distancemeters"] / 1000.0
            dist_deg = result["distance"]
            print(station, channel, st_lat, st_lon, dist_km, dist_deg, baz, az)

            os.system(
                f"sac > macro {_lib}/rotate.macro {Nfile} {Efile} {baz} {Rfile} {Tfile}"
            )

            Rtr = read(Rfile)[0]
            Rtr.stats["channel"] = "MXR"
            Rtr.write(Rfile, format="SAC")

            Ttr = read(Tfile)[0]
            Ttr.stats["channel"] = "MXT"
            Ttr.write(Tfile, format="SAC")
Esempio n. 11
0
 def test_flinnengdahl(self):
     """
     Tests calculation of Flinn-Engdahl region code or name.
     """
     client = Client()
     # code
     result = client.flinnengdahl(lat=-20.5, lon=-100.6, rtype="code")
     self.assertEqual(result, 683)
     # w/o kwargs
     result = client.flinnengdahl(-20.5, -100.6, "code")
     self.assertEqual(result, 683)
     # region
     result = client.flinnengdahl(lat=42, lon=-122.24, rtype="region")
     self.assertEqual(result, 'OREGON')
     # w/o kwargs
     result = client.flinnengdahl(42, -122.24, "region")
     self.assertEqual(result, 'OREGON')
     # both
     result = client.flinnengdahl(lat=-20.5, lon=-100.6, rtype="both")
     self.assertEqual(result, (683, 'SOUTHEAST CENTRAL PACIFIC OCEAN'))
     # w/o kwargs
     result = client.flinnengdahl(-20.5, -100.6, "both")
     self.assertEqual(result, (683, 'SOUTHEAST CENTRAL PACIFIC OCEAN'))
     # default rtype
     result = client.flinnengdahl(lat=42, lon=-122.24)
     self.assertEqual(result, (32, 'OREGON'))
     # w/o kwargs
     # outside boundaries
     self.assertRaises(Exception, client.flinnengdahl, lat=-90.1, lon=0)
     self.assertRaises(Exception, client.flinnengdahl, lat=90.1, lon=0)
     self.assertRaises(Exception, client.flinnengdahl, lat=0, lon=-180.1)
     self.assertRaises(Exception, client.flinnengdahl, lat=0, lon=180.1)
Esempio n. 12
0
    def test_sim_WA(self):
        """Test feeding both PAZ and seedresp."""
        from eqcorrscan.utils.mag_calc import _sim_WA
        from obspy.core.util import NamedTemporaryFile
        from obspy import UTCDateTime
        from obspy.clients.fdsn import Client
        from obspy.clients.iris import Client as OldIris_Client

        t1 = UTCDateTime("2010-09-3T16:30:00.000")
        t2 = UTCDateTime("2010-09-3T17:00:00.000")
        fdsn_client = Client('IRIS')
        st = fdsn_client.get_waveforms(network='NZ', station='BFZ',
                                       location='10',
                                       channel='HHZ',
                                       starttime=t1, endtime=t2,
                                       attach_response=True)
        tr = st[0]
        PAZ = {'poles': [-4.440 + 4.440j, -4.440 - 4.440j, -1.083 + 0.0j],
               'zeros': [0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0],
               'sensitivity': 0.4,
               'gain': 60077000.0}
        tr_safe = tr.copy()
        # Test with PAZ
        _sim_WA(trace=tr, PAZ=PAZ, seedresp=None, water_level=10)
        tr = tr_safe.copy()
        # Test without PAZ or seedresp
        _sim_WA(trace=tr, PAZ=None, seedresp=None, water_level=10)
        tr = tr_safe.copy()
        with NamedTemporaryFile() as tf:
            respf = tf.name
            old_iris_client = OldIris_Client()
            # fetch RESP information from "old" IRIS web service, see obspy.fdsn
            # for accessing the new IRIS FDSN web services
            old_iris_client.resp('NZ', 'BFZ', '10', 'HHZ', t1, t2,
                                 filename=respf)
            date = t1

            seedresp = {'filename': respf,  # RESP filename
                        'date': date,
                        'network': tr.stats.network,
                        'station': tr.stats.station,
                        'channel': tr.stats.channel,
                        'location': tr.stats.location,
                        # Units to return response in ('DIS', 'VEL' or ACC)
                        'units': 'DIS'
                        }
            _sim_WA(trace=tr, PAZ=None, seedresp=seedresp, water_level=10)
Esempio n. 13
0
def download_response(network, station, location, channel, start, end,
                      respfile):
    '''
    Download instrument response file from IRIS and save to .resp
    Input:
        network:            String with network name
        station:            String with station name
        location:           String with location - can have * for wildcards
        channel:            String with channel - can have * for wildcards
        start:              String with start date and time: yyy-mm-ddThh:mm.sss
        end:                String with end date and time: yyy-mm-ddThh:mm.sss
    Output: 
        respfile:           Prints instrument response to respfile
    '''

    from obspy.clients.iris import Client
    from obspy import UTCDateTime

    # Set up client
    client = Client()

    # Define start and end date for resp file
    startdt = UTCDateTime(start)
    enddt = UTCDateTime(end)

    # Download resp data
    dlstring = 'downloading resp data for network ' + network + ', station ' \
        + station + ', location and channel ' + location + ' ' + channel \
        + ', \n for time ' + start + ' to ' + end
    print dlstring

    respdata = client.resp(network,
                           station,
                           location,
                           channel,
                           starttime=startdt,
                           endtime=enddt)

    # Save to file:
    respf = open(respfile, 'w')
    respf.write(respdata)
    respf.close()

    # Print statement:
    print 'Saved resp to file ' + respfile
Esempio n. 14
0
 def test_distaz(self):
     """
     Tests distance and azimuth calculation between two points on a sphere.
     """
     client = Client()
     # normal request
     result = client.distaz(stalat=1.1, stalon=1.2, evtlat=3.2, evtlon=1.4)
     self.assertAlmostEqual(result['distance'], 2.09554)
     self.assertAlmostEqual(result['backazimuth'], 5.46946)
     self.assertAlmostEqual(result['azimuth'], 185.47692)
     # w/o kwargs
     result = client.distaz(1.1, 1.2, 3.2, 1.4)
     self.assertAlmostEqual(result['distance'], 2.09554)
     self.assertAlmostEqual(result['backazimuth'], 5.46946)
     self.assertAlmostEqual(result['azimuth'], 185.47692)
     # missing parameters
     self.assertRaises(Exception, client.distaz, stalat=1.1)
     self.assertRaises(Exception, client.distaz, 1.1)
     self.assertRaises(Exception, client.distaz, stalat=1.1, stalon=1.2)
     self.assertRaises(Exception, client.distaz, 1.1, 1.2)
Esempio n. 15
0
 def test_distaz(self):
     """
     Tests distance and azimuth calculation between two points on a sphere.
     """
     client = Client()
     # normal request
     result = client.distaz(stalat=1.1, stalon=1.2, evtlat=3.2, evtlon=1.4)
     self.assertAlmostEqual(result['distance'], 2.09554)
     self.assertAlmostEqual(result['backazimuth'], 5.46946)
     self.assertAlmostEqual(result['azimuth'], 185.47692)
     # w/o kwargs
     result = client.distaz(1.1, 1.2, 3.2, 1.4)
     self.assertAlmostEqual(result['distance'], 2.09554)
     self.assertAlmostEqual(result['backazimuth'], 5.46946)
     self.assertAlmostEqual(result['azimuth'], 185.47692)
     # missing parameters
     self.assertRaises(Exception, client.distaz, stalat=1.1)
     self.assertRaises(Exception, client.distaz, 1.1)
     self.assertRaises(Exception, client.distaz, stalat=1.1, stalon=1.2)
     self.assertRaises(Exception, client.distaz, 1.1, 1.2)
Esempio n. 16
0
    def test_timeseries(self):
        """
        Tests timeseries Web service interface.

        Examples are inspired by https://service.iris.edu/irisws/timeseries/1/.
        """
        client = Client()
        # 1
        t1 = UTCDateTime("2005-001T00:00:00")
        t2 = UTCDateTime("2005-001T00:01:00")
        # no filter
        st1 = client.timeseries("IU", "ANMO", "00", "BHZ", t1, t2)
        # instrument corrected
        st2 = client.timeseries("IU", "ANMO", "00", "BHZ", t1, t2,
                                filter=["correct"])
        # compare results
        self.assertEqual(st1[0].stats.starttime, st2[0].stats.starttime)
        self.assertEqual(st1[0].stats.endtime, st2[0].stats.endtime)
        self.assertEqual(st1[0].data[0], 24)
        self.assertAlmostEqual(st2[0].data[0], -2.8373747e-06)
Esempio n. 17
0
 def select_client(self, client):
     """
     Function that creates the client for connectivity according to user's input, and link with the users variables.
     Args:
         client: str
         The type of client we want to connect with.
     """
     if client == 'Earthworm':
         from obspy.clients.earthworm import Client as EClient
         self.cnt = EClient(self.ip_address, int(self.port))
     elif client == 'Seedlink':
         from obspy.clients.seedlink import Client as SClient
         self.cnt = SClient(self.ip_address, int(self.port))
     elif client == 'FDSN':
         from obspy.clients.fdsn import Client as FClient
         self.cnt = FClient(self.ip_address, self.port)
     elif client == 'arclink':
         from obspy.clients.arclink import Client as AClient
         self.cnt = AClient(self.ip_address, int(self.port))
     else:
         from obspy.clients.iris import Client as IClient
         self.cnt = IClient("IRIS")
Esempio n. 18
0
    def test_resp(self):
        """
        Tests resp Web service interface.

        Examples are inspired by https://service.iris.edu/irisws/resp/1/.
        """
        client = Client()
        # 1
        t1 = UTCDateTime("2005-001T00:00:00")
        t2 = UTCDateTime("2008-001T00:00:00")
        result = client.resp("IU", "ANMO", "00", "BHZ", t1, t2)
        self.assertIn(b'B050F03     Station:     ANMO', result)
        # 2 - empty location code
        result = client.resp("UW", "LON", "", "EHZ")
        self.assertIn(b'B050F03     Station:     LON', result)
        self.assertIn(b'B052F03     Location:    ??', result)
        # 3 - empty location code via '--'
        result = client.resp("UW", "LON", "--", "EHZ")
        self.assertIn(b'B050F03     Station:     LON', result)
        self.assertIn(b'B052F03     Location:    ??', result)
        # 4
        dt = UTCDateTime("2010-02-27T06:30:00.000")
        result = client.resp("IU", "ANMO", "*", "*", dt)
        self.assertIn(b'B050F03     Station:     ANMO', result)
Esempio n. 19
0
    def test_resp(self):
        """
        Tests resp Web service interface.

        Examples are inspired by http://www.iris.edu/ws/resp/.
        """
        client = Client()
        # 1
        t1 = UTCDateTime("2005-001T00:00:00")
        t2 = UTCDateTime("2008-001T00:00:00")
        result = client.resp("IU", "ANMO", "00", "BHZ", t1, t2)
        self.assertIn(b'B050F03     Station:     ANMO', result)
        # 2 - empty location code
        result = client.resp("UW", "LON", "", "EHZ")
        self.assertIn(b'B050F03     Station:     LON', result)
        self.assertIn(b'B052F03     Location:    ??', result)
        # 3 - empty location code via '--'
        result = client.resp("UW", "LON", "--", "EHZ")
        self.assertIn(b'B050F03     Station:     LON', result)
        self.assertIn(b'B052F03     Location:    ??', result)
        # 4
        dt = UTCDateTime("2010-02-27T06:30:00.000")
        result = client.resp("IU", "ANMO", "*", "*", dt)
        self.assertIn(b'B050F03     Station:     ANMO', result)
Esempio n. 20
0
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 12 15:10:29 2018

@author: jfarrugia
"""

#%% Get some raw data from IRIS to pass through our new stationXML file
from obspy import read_inventory
inv = read_inventory('NV_ONC.xml', format="STATIONXML")
plotting_flag = 1

if plotting_flag == 1:
    from obspy.clients.iris import Client
    client = Client(timeout=100)
    from obspy import UTCDateTime
    import pandas as pd
    import matplotlib.pyplot as plt

    start_t = UTCDateTime("2018-01-10T03:00:00")
    end_t = start_t + 60 * 30
    st_e = client.timeseries(network='NV',
                             station='NC89',
                             location=None,
                             channel='HHE',
                             starttime=start_t,
                             endtime=end_t,
                             filter=['decimate=5.0'])
    st_e_noresponse = st_e.remove_response(inventory=inv, output='ACC')
    st_e_noresponse.write('E_honduras_correct_response.dat', format='TSPAIR')
Esempio n. 21
0
        else:
            sta1 = part[1]
            sta2 = part[2] + '_1'
    else:
        sta1 = part[1] + '_1'
        sta2 = part[3] + '_1'

    # if (sta1[0] in ['A','C','J'] or (sta1[0]=='D' and sta1 != 'DOC')) \
    # and (sta2[0] in ['A','C','J'] or (sta2[0]=='D' and sta2 != 'DOC')):

    if (sta1[0] == 'B' or sta1 == 'KMI' or sta1 == 'DOC') and (sta2[0] == 'B' or sta2 == 'KMI' or sta2 == 'DOC'):
        sac_num = sac_num + 1
        p1 = st_names.index(sta1)
        p2 = st_names.index(sta2)
        st_lo1, st_la1, st_lo2, st_la2 = st_los[p1], st_las[p1], st_los[p2], st_las[p2]
        client = Client()
        result = client.distaz(stalat=st_la1, stalon=st_lo1, evtlat=st_la2, evtlon=st_lo2)
        dist = int(result['distancemeters']) / 10 ** 3
        dists.append(dist)
        sta1s.append(sta1)
        sta2s.append(sta2)

for i in range(sac_num - 1):
    for j in range(i + 1, sac_num):
        if dists[i] > dists[j]:
            td, t1, t2 = dists[i], sta1s[i], sta2s[i]
            dists[i], sta1s[i], sta2s[i] = dists[j], sta1s[j], sta2s[j]
            dists[j], sta1s[j], sta2s[j] = td, t1, t2

dist_file = open('dist_s.dat', 'w')
for i in range(sac_num):
Esempio n. 22
0
def rate(network,
         phase,
         preproloc,
         station=None,
         review=False,
         retained=False,
         decon_meth='it',
         test_tt_calculation=False):
    """
    Module to rate and review the quality of Sp or Ps waveforms from the given
    station. Shows the automatic rating from qc. Tapers can be controlled with
    the mouse. Rating is done with the keyboard. Makes only sense if the
    files in preproloc have not been quality controlled (the script is a
    reminant from an earlier alpha version).

    Parameters
    ----------
    network : STRING
        Network code (two letters).
    phase : STRING
        Either "P" for Ps or "S" Sp. The default is "S".
    preproloc : string
        Directory that contains the preprocessed files (not quality controlled)
    station : str or list, optional
        Station code (three letters).
    review : INTEGER, optional
        If true, already rated waveforms are shown.
        Can also be an integer between 1 and 4. Then, only waveforms rated
        with the respected rating are shown. The default is False.
    retained : Bool, optional
        Show only waveforms retained by qcp or qcs. The default is False.
    decon_meth : STRING, optional
        Deconvolution method, "waterlevel", 'dampedf' for constant
        damping level, 'it' for iterative time domain deconvoltuion, 'multit'
        for multitaper or 'fqd' for frequency dependently damped spectral
        division. The default is 'it'

    Raises
    ------
    Exception
        For Typing mistakes.

    Returns
    -------
    None.

    """
    if phase == 'P':
        onset = 30
    elif phase[-1] == 'S':
        onset = 120

    inloc = os.path.join(preproloc, phase, 'by_station', network)

    infiles = []  # List of all files in folder
    pattern = []  # List of input constraints
    streams = []  # List of files filtered for input criteria

    for root, dirs, files in os.walk(inloc):
        for name in files:
            infiles.append(os.path.join(root, name))

    # Set filter patterns

    if station:
        if type(station) == str:
            pattern.append('*%s*%s*.mseed' % (network, station))
        elif type(station) == list:
            for stat in station:
                pattern.append('*%s*%s*.mseed' % (network, stat))
    else:
        pattern.append('*%s*.mseed' % (network))

    # Do filtering
    for pat in pattern:
        streams.extend(fnmatch.filter(infiles, pat))

    # clear memory
    del pattern, infiles

    # For TauPy lookup
    model = TauPyModel()

    if test_tt_calculation:
        client = Client()

    for f in streams:
        # if file[:4] == "info":  # Skip the info files
        #     continue
        # try:
        #     st = read(inloc + file)
        # except IsADirectoryError as e:
        #     print(e)
        #     continue

        st = read(f)
        # List for taper coordinates
        if "taper" in rating:
            del rating["taper"]
        rating["taper"] = []
        st.normalize()

        # Additional filter "test"
        if phase == "S":
            st.filter("lowpass", freq=1.0, zerophase=True, corners=2)
        elif phase == "P":
            st.filter("lowpass", freq=1.0, zerophase=True, corners=2)

        y = []
        ch = []
        starttime = str(st[0].stats.starttime)
        dt = st[0].stats.delta
        sampling_f = st[0].stats.sampling_rate
        old = __r_file(network, st[0].stats.station, starttime)  # old

        # read info file
        # location info file
        infof = os.path.join(inloc, st[0].stats.station, 'info')
        with shelve.open(infof) as info:
            ii = info["starttime"].index(st[0].stats.starttime)
            rdelta = info["rdelta"][ii]  # epicentral distance
            mag = info["magnitude"][ii]
            statlat = info["statlat"]
            statlon = info["statlon"]
            rayp = info["rayp_s_deg"][ii] / 111319.9
            evt_depth = info["evt_depth"][ii] / 1000
            ot = info["ot_ret"][ii]
            evtlat = info['evtlat'][ii]
            evtlon = info['evtlon'][ii]

        if old and not review:  # skip already rated files
            continue
        if type(review) == int:
            if review > 4:
                raise Exception("review has to be between 0 and 4")
            if review != int(old):
                continue

        # check automatic rating
        if phase == "S":
            st_f, crit, hf, noisemat = qcs(st, dt, sampling_f, onset=onset)
        elif phase == "P":
            st_f, crit, hf, noisemat = qcp(st, dt, sampling_f, onset=onset)

        # skip files that have not been retained
        if retained and not crit:
            continue

        # create RF
        if not test_tt_calculation:
            _, _, PSV = rotate_PSV(statlat, statlon, rayp, st_f)
        else:
            PSV = st_f  # to see correlation at theoretical arrival

        try:
            RF = createRF(PSV, phase, method=decon_meth, shift=onset)
        except ValueError as e:  # There were some problematic events
            print(e)
            continue

        # TauPy lookup
        ph_name = []
        ph_time = []

        if not test_tt_calculation:
            arrivals = model.get_travel_times(evt_depth,
                                              distance_in_degree=rdelta)

            primary_time = model.get_travel_times(evt_depth,
                                                  distance_in_degree=rdelta,
                                                  phase_list=phase)[0].time

            for arr in arrivals:
                if arr.time < primary_time - onset or arr.time > \
                        primary_time + 120 or arr.name == phase:
                    continue
                ph_name.append(arr.name)
                ph_time.append(arr.time - primary_time)

        else:
            # Caluclate travel times with different methods
            ph_time.append(
                model.get_travel_times_geo(evt_depth,
                                           evtlat,
                                           evtlon,
                                           statlat,
                                           statlon,
                                           phase_list=phase)[0].time)

            d = []
            d.append(
                client.distaz(statlat, statlon, evtlat, evtlon)['distance'])

            d.append(
                kilometer2degrees(
                    gps2dist_azimuth(statlat, statlon, evtlat, evtlon)[0] /
                    1000))

            for dis in d:
                ph_time.append(
                    model.get_travel_times(evt_depth, dis,
                                           phase_list=phase)[0].time)
            ph_name = ['taup', 'iris', 'geodetics']
            ph_time = np.array(ph_time) - (st[0].stats.starttime + onset -
                                           UTCDateTime(ot))

        # waveform data
        st.sort()
        for tr in st:
            y.append(tr.data)
            ch.append(tr.stats.channel[2])

        # create time vector
        t = np.linspace(0 - onset, tr.stats.npts * tr.stats.delta - onset,
                        len(y[0]))

        # plot
        fig, ax = __draw_plot(starttime, t, y, ph_time, ph_name, ch, noisemat,
                              RF, old, rdelta, mag, crit, ot, evt_depth, phase,
                              test_tt_calculation)
        while not plt.waitforbuttonpress(30):
            # Taper when input is there
            if len(rating["taper"]) == 2:
                if rating["taper"][0] < rating["taper"][1]:
                    trim = [rating["taper"][0], rating["taper"][1]]
                else:
                    trim = [rating["taper"][1], rating["taper"][0]]
                trim[0] = trim[0] - t[0]
                trim[1] = t[-1] - trim[1]

                RF = createRF(PSV,
                              phase,
                              method=decon_meth,
                              shift=onset,
                              trim=trim)

                __draw_plot(starttime, t, y, ph_time, ph_name, ch, noisemat,
                            RF, old, rdelta, mag, crit, ot, evt_depth, phase,
                            test_tt_calculation)
                rating["taper"].clear()
        # fig.canvas.mpl_connect('key_press_event', ontype)
        if rating["k"] == "q":
            break
        elif "k" in rating:
            __w_file(network, st[0].stats.station, starttime)
Esempio n. 23
0
 def test_evalresp(self):
     """
     Tests evaluating instrument response information.
     """
     client = Client()
     dt = UTCDateTime("2005-01-01")
     # plot as PNG file
     with NamedTemporaryFile() as tf:
         tempfile = tf.name
         client.evalresp(network="IU",
                         station="ANMO",
                         location="00",
                         channel="BHZ",
                         time=dt,
                         output='plot',
                         filename=tempfile)
         with open(tempfile, 'rb') as fp:
             self.assertEqual(fp.read(4)[1:4], b'PNG')
     # plot-amp as PNG file
     with NamedTemporaryFile() as tf:
         tempfile = tf.name
         client.evalresp(network="IU",
                         station="ANMO",
                         location="00",
                         channel="BHZ",
                         time=dt,
                         output='plot-amp',
                         filename=tempfile)
         with open(tempfile, 'rb') as fp:
             self.assertEqual(fp.read(4)[1:4], b'PNG')
     # plot-phase as PNG file
     with NamedTemporaryFile() as tf:
         tempfile = tf.name
         client.evalresp(network="IU",
                         station="ANMO",
                         location="00",
                         channel="BHZ",
                         time=dt,
                         output='plot-phase',
                         filename=tempfile)
         with open(tempfile, 'rb') as fp:
             self.assertEqual(fp.read(4)[1:4], b'PNG')
     # fap as ASCII file
     with NamedTemporaryFile() as tf:
         tempfile = tf.name
         client.evalresp(network="IU",
                         station="ANMO",
                         location="00",
                         channel="BHZ",
                         time=dt,
                         output='fap',
                         filename=tempfile)
         with open(tempfile, 'rt') as fp:
             self.assertEqual(fp.readline(),
                              '1.000000E-05  1.055999E+04  1.792007E+02\n')
     # cs as ASCII file
     with NamedTemporaryFile() as tf:
         tempfile = tf.name
         client.evalresp(network="IU",
                         station="ANMO",
                         location="00",
                         channel="BHZ",
                         time=dt,
                         output='cs',
                         filename=tempfile)
         with open(tempfile, 'rt') as fp:
             self.assertEqual(fp.readline(),
                              '1.000000E-05 -1.055896E+04 1.473054E+02\n')
     # fap & def as ASCII file
     with NamedTemporaryFile() as tf:
         tempfile = tf.name
         client.evalresp(network="IU",
                         station="ANMO",
                         location="00",
                         channel="BHZ",
                         time=dt,
                         output='fap',
                         units='def',
                         filename=tempfile)
         with open(tempfile, 'rt') as fp:
             self.assertEqual(fp.readline(),
                              '1.000000E-05  1.055999E+04  1.792007E+02\n')
     # fap & dis as ASCII file
     with NamedTemporaryFile() as tf:
         tempfile = tf.name
         client.evalresp(network="IU",
                         station="ANMO",
                         location="00",
                         channel="BHZ",
                         time=dt,
                         output='fap',
                         units='dis',
                         filename=tempfile)
         with open(tempfile, 'rt') as fp:
             self.assertEqual(fp.readline(),
                              '1.000000E-05  6.635035E-01  2.692007E+02\n')
     # fap & vel as ASCII file
     with NamedTemporaryFile() as tf:
         tempfile = tf.name
         client.evalresp(network="IU",
                         station="ANMO",
                         location="00",
                         channel="BHZ",
                         time=dt,
                         output='fap',
                         units='vel',
                         filename=tempfile)
         with open(tempfile, 'rt') as fp:
             self.assertEqual(fp.readline(),
                              '1.000000E-05  1.055999E+04  1.792007E+02\n')
     # fap & acc as ASCII file
     with NamedTemporaryFile() as tf:
         tempfile = tf.name
         client.evalresp(network="IU",
                         station="ANMO",
                         location="00",
                         channel="BHZ",
                         time=dt,
                         output='fap',
                         units='acc',
                         filename=tempfile)
         with open(tempfile, 'rt') as fp:
             self.assertEqual(fp.readline(),
                              '1.000000E-05  1.680674E+08  8.920073E+01\n')
     # fap as NumPy ndarray
     data = client.evalresp(network="IU",
                            station="ANMO",
                            location="00",
                            channel="BHZ",
                            time=dt,
                            output='fap')
     np.testing.assert_array_equal(
         data[0], [1.00000000e-05, 1.05599900e+04, 1.79200700e+02])
     # cs as NumPy ndarray
     data = client.evalresp(network="IU",
                            station="ANMO",
                            location="00",
                            channel="BHZ",
                            time=dt,
                            output='cs')
     np.testing.assert_array_equal(
         data[0], [1.00000000e-05, -1.05589600e+04, 1.47305400e+02])
Esempio n. 24
0
from bqmail.query import Query
from obspy import UTCDateTime
from obspy.taup import TauPyModel
from obspy.clients.iris import Client
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from .distaz import distaz
model = TauPyModel()
cld = Client()


def connectsmtp(server, port, sender, password):
    smtpObj = smtplib.SMTP_SSL(server, port)
    smtpObj.login(sender, password)
    return smtpObj


def loginmail(sender, server='localhost', password='', port=465, test_num=5):
    test_it = 1
    while test_it <= test_num:
        if test_it > 1:
            print('Try to link to {} in {} times'.format(server, test_it))
        try:
            smtpObj = connectsmtp(server, port, sender, password)
        except:
            test_it += 1
            continue
        else:
            break
    if test_it > test_num:
Esempio n. 25
0
from obspy.core.util import NamedTemporaryFile
from obspy.clients.fdsn import Client as FDSN_Client
from obspy.clients.iris import Client as OldIris_Client

# MW 7.1 Darfield earthquake, New Zealand
t1 = obspy.UTCDateTime("2010-09-3T16:30:00.000")
t2 = obspy.UTCDateTime("2010-09-3T17:00:00.000")

# Fetch waveform from IRIS FDSN web service into a ObsPy stream object
fdsn_client = FDSN_Client("IRIS")
st = fdsn_client.get_waveforms('NZ', 'BFZ', '10', 'HHZ', t1, t2)

# Download and save instrument response file into a temporary file
with NamedTemporaryFile() as tf:
    respf = tf.name
    old_iris_client = OldIris_Client()
    # fetch RESP information from "old" IRIS web service, see obspy.fdsn
    # for accessing the new IRIS FDSN web services
    old_iris_client.resp('NZ', 'BFZ', '10', 'HHZ', t1, t2, filename=respf)

    # make a copy to keep our original data
    st_orig = st.copy()

    # define a filter band to prevent amplifying noise during the deconvolution
    pre_filt = (0.005, 0.006, 30.0, 35.0)

    # this can be the date of your raw data or any date for which the
    # SEED RESP-file is valid
    date = t1

    seedresp = {
Esempio n. 26
0
class WindowConnection(QtGui.QMainWindow, DialogConnection.Ui_MainWindow):
    """
    This class handles the connection with the data repositories and send back the data to the main interface.
    """
    def __init__(self, parent):
        super(WindowConnection, self).__init__(parent)
        self.setupUi(self)
        self.requestbutton.clicked.connect(self.requestdata)
        self.cnt = None

    def select_client(self, client):
        """
        Function that creates the client for connectivity according to user's input, and link with the users variables.
        Args:
            client: str
            The type of client we want to connect with.
        """
        if client == 'Earthworm':
            from obspy.clients.earthworm import Client as EClient
            self.cnt = EClient(self.ip_address, int(self.port))
        elif client == 'Seedlink':
            from obspy.clients.seedlink import Client as SClient
            self.cnt = SClient(self.ip_address, int(self.port))
        elif client == 'FDSN':
            from obspy.clients.fdsn import Client as FClient
            self.cnt = FClient(self.ip_address, self.port)
        elif client == 'arclink':
            from obspy.clients.arclink import Client as AClient
            self.cnt = AClient(self.ip_address, int(self.port))
        else:
            from obspy.clients.iris import Client as IClient
            self.cnt = IClient("IRIS")

    def requestdata(self):
        """ Native function to request data from the clients."""
        self.ip_address = self.ip_c.text()
        self.port = int(self.port_c.text())

        if self.ip_address == '' or self.port == '':
            gui_functions.msg_box("IP address or port seems empty", "Please, enter data correctly!")

        self.parent().network = str(self.network_c.text())
        self.parent().station = str(self.station_c.text())
        self.parent().channel = str(self.channel_c.text())
        self.parent().location = str(self.location_c.text())
        # self.parent().component = str(self.component_c.text())
        # self.parent().trace_number = str(self.numtraceBox.value())

        self.parent().start_data = UTCDateTime((self.startTime.dateTime().toPyDateTime()))
        self.parent().end_data = UTCDateTime((self.endTime.dateTime().toPyDateTime()))

        # request the data
        self.select_client(str(self.comboServers.currentText()))
        st = self.cnt.get_waveforms(self.parent().network, self.parent().station,
                                    self.parent().location,
                                    self.parent().channel,
                                    self.parent().start_data,
                                    self.parent().end_data)

        # a test trace below for test. Remove on final versions.
        # st = "9702-10-1441-50S.MVO_18_1" #this is only from test!!
        self.parent().trace_loaded = st
        self.parent().stream = st
        self.close()
        gc.collect()
        self.parent().plot_from_server()
Esempio n. 27
0
#!/usr/bin/env python

#from obspy.core import read
from obspy.clients.iris import Client
from obspy import core

stat = 'AAM'  # Station Code
net = 'US'  # Station Network
ch = ['BHZ', 'BH1', 'BH2']  # Channel
loc = '00'  # Location
# These 4 parameter identify the trace to download

start = core.UTCDateTime("2017-09-19T18:14:38")
end = core.UTCDateTime(start + 1800)

client = Client(
)  # Not sure what this does but its gets rid of the "self" error message
str = core.stream.Stream()
for x in range(0, 3):
    str += client.timeseries(network=net,
                             station=stat,
                             channel=ch[x],
                             location=loc,
                             starttime=start,
                             endtime=end)
## Plot Traces
start_plot = start + 222  #Manipulate starttime to get a nicer plot
end_plot = start_plot + 960
str.plot(size=[800, 600],
         starttime=start_plot,
         endtime=end_plot,
         type='relative')
from utilities_Array import deg_km_az_baz

# To dictate headers
from obspy.core.util import AttribDict

## Web service packages
from obspy.clients.iris import Client

# TauP
from obspy.taup import TauPyModel

# my model of choice is prem :D
model = TauPyModel(model="prem")

# Make client - just for giggles
client = Client()

import shutil
import numpy

import matplotlib.pyplot as plt

import argparse

parser = argparse.ArgumentParser(
    description='Preprocessing script for data retrieved from obspy DMT')

parser.add_argument("-fmin",
                    "--minimuum_frequency",
                    help="Enter the lowest frequency to be bandpass filtered.",
                    type=float,
Esempio n. 29
0
    def test_sim_WA(self):
        """Test feeding both PAZ and seedresp."""
        t1 = UTCDateTime("2010-09-3T16:30:00.000")
        t2 = UTCDateTime("2010-09-3T17:00:00.000")
        fdsn_client = Client('IRIS')
        st = fdsn_client.get_waveforms(network='NZ',
                                       station='BFZ',
                                       location='10',
                                       channel='HHZ',
                                       starttime=t1,
                                       endtime=t2,
                                       attach_response=True)
        tr = st[0]
        PAZ = {
            'poles': [-4.440 + 4.440j, -4.440 - 4.440j, -1.083 + 0.0j],
            'zeros': [0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0],
            'sensitivity': 0.4,
            'gain': 60077000.0
        }
        tr_safe = tr.copy()
        # Test with PAZ
        _sim_WA(trace=tr, PAZ=PAZ, seedresp=None, water_level=10)
        tr = tr_safe.copy()
        # Test without PAZ or seedresp
        _sim_WA(trace=tr, PAZ=None, seedresp=None, water_level=10)
        tr = tr_safe.copy()
        with open("Temp_resp", "w") as tf:
            respf = tf.name
            old_iris_client = OldIris_Client()
            # fetch RESP information from "old" IRIS web service, see
            # obspy.fdsn for accessing the new IRIS FDSN web services
            old_iris_client.resp('NZ',
                                 'BFZ',
                                 '10',
                                 'HHZ',
                                 t1,
                                 t2,
                                 filename=respf)
            # Hack around unit issues
        with open("Temp_resp", "r") as tf:
            resp_contents = [line for line in tf]
        corrected_contents = []
        for line in resp_contents:
            if "COUNT" in line:
                line = line.replace("COUNT", "COUNTS")
            corrected_contents.append(line)
        with open("Temp_resp", "w") as tf:
            for line in corrected_contents:
                tf.write(line)
        date = t1

        seedresp = {
            'filename': respf,
            'date': date,
            'network': tr.stats.network,
            'station': tr.stats.station,
            'channel': tr.stats.channel,
            'location': tr.stats.location,
            'units': 'DIS'
        }
        _sim_WA(trace=tr, PAZ=None, seedresp=seedresp, water_level=10)
        os.remove(respf)
Esempio n. 30
0
        net_name.lower()))
    os.system('cp ../mt_inv.in MT_INVERSION')

    os.system('mkdir RAW')
    os.chdir('RAW')

    #download sac file & instrument responce
    if process_stage <= 2:
        for sta_name in sta_list:
            for chn_name in chn_list:
                #loop over sta/channels
                sac_name = 'SAC.' + ymd_list[0] + ymd_list[1] + ymd_list[
                    2] + '.' + net_name + '.' + sta_name + '.' + chn_name
                pz_name = net_name + '.' + sta_name + '.pz'
                t0 = UTCDateTime(item["time"])
                client = Client()
                client.timeseries(net_name,
                                  sta_name,
                                  "",
                                  chn_name,
                                  t0 - 60,
                                  t0 + 5 * 60,
                                  filename=sac_name,
                                  output='sacbb')
                client.sacpz(net_name,
                             sta_name,
                             "",
                             chn_name,
                             t0,
                             filename=pz_name)
from obspy.clients.fdsn import Client as FDSN_Client
from obspy.clients.iris import Client as OldIris_Client


# MW 7.1 Darfield earthquake, New Zealand
t1 = obspy.UTCDateTime("2010-09-3T16:30:00.000")
t2 = obspy.UTCDateTime("2010-09-3T17:00:00.000")

# Fetch waveform from IRIS FDSN web service into a ObsPy stream object
fdsn_client = FDSN_Client("IRIS")
st = fdsn_client.get_waveforms('NZ', 'BFZ', '10', 'HHZ', t1, t2)

# Download and save instrument response file into a temporary file
with NamedTemporaryFile() as tf:
    respf = tf.name
    old_iris_client = OldIris_Client()
    # fetch RESP information from "old" IRIS web service, see obspy.fdsn
    # for accessing the new IRIS FDSN web services
    old_iris_client.resp('NZ', 'BFZ', '10', 'HHZ', t1, t2, filename=respf)

    # make a copy to keep our original data
    st_orig = st.copy()

    # define a filter band to prevent amplifying noise during the deconvolution
    pre_filt = (0.005, 0.006, 30.0, 35.0)

    # this can be the date of your raw data or any date for which the
    # SEED RESP-file is valid
    date = t1

    seedresp = {'filename': respf,  # RESP filename
Esempio n. 32
0
 def test_evalresp(self):
     """
     Tests evaluating instrument response information.
     """
     client = Client()
     dt = UTCDateTime("2005-01-01")
     # plot as PNG file
     with NamedTemporaryFile() as tf:
         tempfile = tf.name
         client.evalresp(network="IU", station="ANMO", location="00",
                         channel="BHZ", time=dt, output='plot',
                         filename=tempfile)
         with open(tempfile, 'rb') as fp:
             self.assertEqual(fp.read(4)[1:4], b'PNG')
     # plot-amp as PNG file
     with NamedTemporaryFile() as tf:
         tempfile = tf.name
         client.evalresp(network="IU", station="ANMO", location="00",
                         channel="BHZ", time=dt, output='plot-amp',
                         filename=tempfile)
         with open(tempfile, 'rb') as fp:
             self.assertEqual(fp.read(4)[1:4], b'PNG')
     # plot-phase as PNG file
     with NamedTemporaryFile() as tf:
         tempfile = tf.name
         client.evalresp(network="IU", station="ANMO", location="00",
                         channel="BHZ", time=dt, output='plot-phase',
                         filename=tempfile)
         with open(tempfile, 'rb') as fp:
             self.assertEqual(fp.read(4)[1:4], b'PNG')
     # fap as ASCII file
     with NamedTemporaryFile() as tf:
         tempfile = tf.name
         client.evalresp(network="IU", station="ANMO", location="00",
                         channel="BHZ", time=dt, output='fap',
                         filename=tempfile)
         with open(tempfile, 'rt') as fp:
             self.assertEqual(fp.readline(),
                              '1.000000E-05  1.055999E+04  1.792007E+02\n')
     # cs as ASCII file
     with NamedTemporaryFile() as tf:
         tempfile = tf.name
         client.evalresp(network="IU", station="ANMO", location="00",
                         channel="BHZ", time=dt, output='cs',
                         filename=tempfile)
         with open(tempfile, 'rt') as fp:
             self.assertEqual(fp.readline(),
                              '1.000000E-05 -1.055896E+04 1.473054E+02\n')
     # fap & def as ASCII file
     with NamedTemporaryFile() as tf:
         tempfile = tf.name
         client.evalresp(network="IU", station="ANMO", location="00",
                         channel="BHZ", time=dt, output='fap', units='def',
                         filename=tempfile)
         with open(tempfile, 'rt') as fp:
             self.assertEqual(fp.readline(),
                              '1.000000E-05  1.055999E+04  1.792007E+02\n')
     # fap & dis as ASCII file
     with NamedTemporaryFile() as tf:
         tempfile = tf.name
         client.evalresp(network="IU", station="ANMO", location="00",
                         channel="BHZ", time=dt, output='fap', units='dis',
                         filename=tempfile)
         with open(tempfile, 'rt') as fp:
             self.assertEqual(fp.readline(),
                              '1.000000E-05  6.635035E-01  2.692007E+02\n')
     # fap & vel as ASCII file
     with NamedTemporaryFile() as tf:
         tempfile = tf.name
         client.evalresp(network="IU", station="ANMO", location="00",
                         channel="BHZ", time=dt, output='fap', units='vel',
                         filename=tempfile)
         with open(tempfile, 'rt') as fp:
             self.assertEqual(fp.readline(),
                              '1.000000E-05  1.055999E+04  1.792007E+02\n')
     # fap & acc as ASCII file
     with NamedTemporaryFile() as tf:
         tempfile = tf.name
         client.evalresp(network="IU", station="ANMO", location="00",
                         channel="BHZ", time=dt, output='fap', units='acc',
                         filename=tempfile)
         with open(tempfile, 'rt') as fp:
             self.assertEqual(fp.readline(),
                              '1.000000E-05  1.680674E+08  8.920073E+01\n')
     # fap as NumPy ndarray
     data = client.evalresp(network="IU", station="ANMO", location="00",
                            channel="BHZ", time=dt, output='fap')
     np.testing.assert_array_equal(
         data[0], [1.00000000e-05, 1.05599900e+04, 1.79200700e+02])
     # cs as NumPy ndarray
     data = client.evalresp(network="IU", station="ANMO", location="00",
                            channel="BHZ", time=dt, output='cs')
     np.testing.assert_array_equal(
         data[0], [1.00000000e-05, -1.05589600e+04, 1.47305400e+02])