Esempio n. 1
0
    def test_evalresp_file_like_object(self):
        """
        Test evalresp with file like object
        """
        rawf = os.path.join(self.path, "CRLZ.HHZ.10.NZ.SAC")
        respf = os.path.join(self.path, "RESP.NZ.CRLZ.10.HHZ")

        tr1 = read(rawf)[0]
        tr2 = read(rawf)[0]

        date = UTCDateTime(2003, 11, 1, 0, 0, 0)
        seedresp = {
            "filename": respf,
            "date": date,
            "units": "VEL",
            "network": "NZ",
            "station": "CRLZ",
            "location": "10",
            "channel": "HHZ",
        }
        tr1.data = simulate_seismometer(tr1.data, tr1.stats.sampling_rate, seedresp=seedresp)

        with open(respf, "rb") as fh:
            stringio = io.BytesIO(fh.read())
        seedresp["filename"] = stringio
        tr2.data = simulate_seismometer(tr2.data, tr2.stats.sampling_rate, seedresp=seedresp)

        self.assertEqual(tr1, tr2)
Esempio n. 2
0
    def test_evalresp_file_like_object(self):
        """
        Test evalresp with file like object
        """
        rawf = os.path.join(self.path, 'CRLZ.HHZ.10.NZ.SAC')
        respf = os.path.join(self.path, 'RESP.NZ.CRLZ.10.HHZ')

        tr1 = read(rawf)[0]
        tr2 = read(rawf)[0]

        date = UTCDateTime(2003, 11, 1, 0, 0, 0)
        seedresp = {
            'filename': respf,
            'date': date,
            'units': 'VEL',
            'network': 'NZ',
            'station': 'CRLZ',
            'location': '10',
            'channel': 'HHZ'
        }
        tr1.data = simulate_seismometer(tr1.data,
                                        tr1.stats.sampling_rate,
                                        seedresp=seedresp)

        with open(respf, 'rb') as fh:
            stringio = io.BytesIO(fh.read())
        seedresp['filename'] = stringio
        tr2.data = simulate_seismometer(tr2.data,
                                        tr2.stats.sampling_rate,
                                        seedresp=seedresp)

        self.assertEqual(tr1, tr2)
Esempio n. 3
0
def remove_response_paz(st, paz_path, pre_filt):
    """
    remove response using paz file
    """
    for trace in st:
        # get key
        network = trace.stats.network
        station = trace.stats.station
        channel = trace.stats.channel
        key = f"{network}.{station}.{channel}"
        paz_path_used = join(paz_path, key)
        # try to read paz
        try:
            attach_paz(trace, paz_path_used)
        except:  # pylint: disable=bare-except
            return None
        # ndarray
        data = simulate_seismometer(trace.data,
                                    trace.stats.sampling_rate,
                                    paz_remove=trace.stats.paz,
                                    water_level=6e9,
                                    zero_mean=False,
                                    taper=False,
                                    pre_filt=pre_filt,
                                    sacsim=True)
        trace.data = data
    return st
def get_peak_spectrals(data, samp_rate,periods):
    """Calculate peak pseudo-spectral parameters.

    Compute 5% damped PSA at input periods seconds.

    Data must be an acceleration Trace.

    :param data:
      Obspy Trace object, containing acceleration data to convolve with pendulum at freq.
    :param delta: 
      sample rate (samples per sec).
    :returns: 
      Dictionary containing keys of input periods, and values of corresponding spectral accelerations.
    """

    D = 0.05	# 5% damping

    psadict = {}
    for T in periods:
        freq = 1.0 / T
        omega = (2 * 3.14159 * freq) ** 2

        paz_sa = corn_freq_2_paz(freq, damp=D)
        paz_sa['sensitivity'] = omega
        paz_sa['zeros'] = []
        dd = simulate_seismometer(data.data, samp_rate, paz_remove=None, paz_simulate=paz_sa,
                     taper=True, simulate_sensitivity=True, taper_fraction=0.05)

        if abs(max(dd)) >= abs(min(dd)):
            psa = abs(max(dd))
        else:
            psa = abs(min(dd))
        psadict[T] = psa

    return psadict
Esempio n. 5
0
    def test_seis_sim_vs_pitsa1(self):
        """
        Test simulate_seismometer seismometer simulation against seismometer
        simulation of Pitsa - LE3D seismometer.
        """
        # load test file
        filename = os.path.join(self.path, 'rjob_20051006.gz')
        with gzip.open(filename) as f:
            data = np.loadtxt(f)

        # paz of test file
        samp_rate = 200.0
        paz_le3d = {'poles': [-4.21 + 4.66j,
                              -4.21 - 4.66j,
                              -2.105 + 0.0j],
                    'zeros': [0.0 + 0.0j] * 3,
                    'sensitivity': 1.0,
                    'gain': 0.4}

        for id, paz in INSTRUMENTS.items():
            # simulate instrument
            datcorr = simulate_seismometer(
                data, samp_rate, paz_remove=paz_le3d, paz_simulate=paz,
                water_level=600.0, zero_mean=False, nfft_pow2=True)
            # load pitsa file
            filename = os.path.join(self.path, 'rjob_20051006_%s.gz' % id)
            with gzip.open(filename) as f:
                data_pitsa = np.loadtxt(f)
            # calculate normalized rms
            rms = np.sqrt(np.sum((datcorr - data_pitsa) ** 2) /
                          np.sum(data_pitsa ** 2))
            self.assertTrue(rms < 1.1e-05)
Esempio n. 6
0
 def test_simulate(self):
     """
     Tests if calling simulate of trace gives the same result as using
     simulate_seismometer manually.
     """
     tr = read()[0]
     paz_sts2 = {'poles': [-0.037004 + 0.037016j, -0.037004 - 0.037016j,
                           - 251.33 + 0j, -131.04 - 467.29j,
                           - 131.04 + 467.29j],
                 'zeros': [0j, 0j],
                 'gain': 60077000.0,
                 'sensitivity': 2516778400.0}
     paz_le3d1s = {'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.0j],
                   'gain': 0.4,
                   'sensitivity': 1.0}
     data = simulate_seismometer(
         tr.data, tr.stats.sampling_rate, paz_remove=paz_sts2,
         paz_simulate=paz_le3d1s, remove_sensitivity=True,
         simulate_sensitivity=True)
     tr.simulate(paz_remove=paz_sts2, paz_simulate=paz_le3d1s)
     # There is some strange issue on Win32bit (see #2188). Thus we just
     # use assert_allclose() here instead of testing for full equality.
     np.testing.assert_allclose(tr.data, data)
def calculate_damped_spectral_acc(data, delta, freq, damp, ty):

    samp_rate = 1.0 / delta
    t = freq * 1.0
    d = damp
    omega = (2 * math.pi * t)**2

    paz_sa = corn_freq_2_paz(t, damp=d)
    paz_sa['sensitivity'] = omega
    paz_sa['zeros'] = []

    if ty == 'displacement':
        data = np.gradient(data, delta)
        data = np.gradient(data, delta)
    elif ty == 'velocity':
        data = np.gradient(data, delta)

    data = simulate_seismometer(data,
                                samp_rate,
                                paz_remove=None,
                                paz_simulate=paz_sa,
                                taper=True,
                                simulate_sensitivity=True,
                                taper_fraction=0.05)

    return data
Esempio n. 8
0
 def test_simulate(self):
     """
     Tests if calling simulate of trace gives the same result as using
     simulate_seismometer manually.
     """
     tr = read()[0]
     paz_sts2 = {
         'poles': [
             -0.037004 + 0.037016j, -0.037004 - 0.037016j, -251.33 + 0j,
             -131.04 - 467.29j, -131.04 + 467.29j
         ],
         'zeros': [0j, 0j],
         'gain':
         60077000.0,
         'sensitivity':
         2516778400.0
     }
     paz_le3d1s = {
         '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.0j],
         'gain': 0.4,
         'sensitivity': 1.0
     }
     data = simulate_seismometer(tr.data,
                                 tr.stats.sampling_rate,
                                 paz_remove=paz_sts2,
                                 paz_simulate=paz_le3d1s,
                                 remove_sensitivity=True,
                                 simulate_sensitivity=True)
     tr.simulate(paz_remove=paz_sts2, paz_simulate=paz_le3d1s)
     np.testing.assert_array_equal(tr.data, data)
Esempio n. 9
0
    def test_seis_sim_vs_pitsa_2(self):
        """
        Test simulate_seismometer seismometer simulation against seismometer
        simulation of Pitsa - STS-2 seismometer.
        """
        # load test file
        file = os.path.join(self.path, 'rotz_20081028.gz')
        with gzip.open(file) as f:
            data = np.loadtxt(f)

        # paz of test file
        samp_rate = 200.0
        paz_sts2 = {'poles': [-0.03736 - 0.03617j,
                              -0.03736 + 0.03617j],
                    'zeros': [0.0 + 0.0j] * 2,
                    'sensitivity': 1.0,
                    'gain': 1.5}

        for id, paz in INSTRUMENTS.items():
            # simulate instrument
            datcorr = simulate_seismometer(
                data, samp_rate, paz_remove=paz_sts2, paz_simulate=paz,
                water_level=600.0, zero_mean=False, nfft_pow2=True)
            # load pitsa file
            filename = os.path.join(self.path, 'rotz_20081028_%s.gz' % id)
            with gzip.open(filename) as f:
                data_pitsa = np.loadtxt(f)
            # calculate normalized rms
            rms = np.sqrt(np.sum((datcorr - data_pitsa) ** 2) /
                          np.sum(data_pitsa ** 2))
            self.assertTrue(rms < 1e-04)
Esempio n. 10
0
 def test_simulate(self):
     """
     Tests if calling simulate of trace gives the same result as using
     simulate_seismometer manually.
     """
     tr = read()[0]
     paz_sts2 = {
         'poles': [
             -0.037004 + 0.037016j, -0.037004 - 0.037016j, -251.33 + 0j,
             -131.04 - 467.29j, -131.04 + 467.29j
         ],
         'zeros': [0j, 0j],
         'gain':
         60077000.0,
         'sensitivity':
         2516778400.0
     }
     paz_le3d1s = {
         '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.0j],
         'gain': 0.4,
         'sensitivity': 1.0
     }
     data = simulate_seismometer(tr.data,
                                 tr.stats.sampling_rate,
                                 paz_remove=paz_sts2,
                                 paz_simulate=paz_le3d1s,
                                 remove_sensitivity=True,
                                 simulate_sensitivity=True)
     tr.simulate(paz_remove=paz_sts2, paz_simulate=paz_le3d1s)
     # There is some strange issue on Win32bit (see #2188). Thus we just
     # use assert_allclose() here instead of testing for full equality.
     np.testing.assert_allclose(tr.data, data)
Esempio n. 11
0
    def test_sac_instrument_correction(self):
        # SAC recommends to taper the transfer function if a pure
        # deconvolution is done instead of simulating a different
        # instrument. This test checks the difference between the
        # result from removing the instrument response using SAC or
        # ObsPy. Visual inspection shows that the traces are pretty
        # much identical but differences remain (rms ~ 0.042). Haven't
        # found the cause for those, yet. One possible reason is the
        # floating point arithmetic of SAC vs. the double precision
        # arithmetic of Python. However differences still seem to be
        # too big for that.
        pzf = os.path.join(self.path, 'SAC_PZs_KARC_BHZ')
        sacf = os.path.join(self.path, 'KARC.LHZ.SAC.asc.gz')
        testsacf = os.path.join(self.path, 'KARC_corrected.sac.asc.gz')
        plow = 160.
        phigh = 4.
        fl1 = 1.0 / (plow + 0.0625 * plow)
        fl2 = 1.0 / plow
        fl3 = 1.0 / phigh
        fl4 = 1.0 / (phigh - 0.25 * phigh)
        # Uncomment the following to run the sac-commands
        # that created the testing file
        # if 1:
        #    import subprocess as sp
        #    p = sp.Popen('sac',shell=True,stdin=sp.PIPE)
        #    cd1 = p.stdin
        #    print("r %s"%sacf, file=cd1)
        #    print("rmean", file=cd1)
        #    print("rtrend", file=cd1)
        #    print("taper type cosine width 0.03", file=cd1)
        #    print("transfer from polezero subtype %s to none \
        #    freqlimits %f %f %f %f" % (pzf, fl1, fl2, fl3, fl4), file=cd1)
        #    print("w over ./data/KARC_corrected.sac", file=cd1)
        #    print("quit", file=cd1)
        #    cd1.close()
        #    p.wait()

        stats = {'network': 'KA', 'delta': 0.99999988079072466,
                 'station': 'KARC', 'location': 'S1',
                 'starttime': UTCDateTime(2001, 2, 13, 0, 0, 0, 993700),
                 'calib': 1.00868e+09, 'channel': 'BHZ'}
        with gzip.open(sacf) as f:
            tr = Trace(np.loadtxt(f), stats)

        attach_paz(tr, pzf, tovel=False)
        tr.data = simulate_seismometer(
            tr.data, tr.stats.sampling_rate, paz_remove=tr.stats.paz,
            remove_sensitivity=False, pre_filt=(fl1, fl2, fl3, fl4))

        with gzip.open(testsacf) as f:
            data = np.loadtxt(f)

        # import matplotlib.pyplot as plt
        # plt.plot(tr.data)
        # plt.plot(data)
        # plt.show()
        rms = np.sqrt(np.sum((tr.data - data) ** 2) /
                      np.sum(tr.data ** 2))
        self.assertTrue(rms < 0.0421)
Esempio n. 12
0
    def test_evalrespVsObsPy(self):
        """
        Compare results from removing instrument response using
        evalresp in SAC and ObsPy. Visual inspection shows that the traces are
        pretty much identical but differences remain (rms ~ 0.042). Haven't
        found the cause for those, yet.
        """
        evalrespf = os.path.join(self.path, "CRLZ.HHZ.10.NZ.SAC_resp")
        rawf = os.path.join(self.path, "CRLZ.HHZ.10.NZ.SAC")
        respf = os.path.join(self.path, "RESP.NZ.CRLZ.10.HHZ")
        fl1 = 0.00588
        fl2 = 0.00625
        fl3 = 30.0
        fl4 = 35.0

        #        #Set the following if-clause to True to run
        #        #the sac-commands that created the testing file
        #        if False:
        #            import subprocess as sp
        #            p = sp.Popen('sac', stdin=sp.PIPE)
        #            cd1 = p.stdin
        #            print("r %s" % rawf, file=cd1)
        #            print("rmean", file=cd1)
        #            print("taper type cosine width 0.05", file=cd1)
        #            print("transfer from evalresp fname %s to vel freqlimits\
        #            %f %f %f %f" % (respf, fl1, fl2, fl3, fl4), file=cd1)
        #            print("w over %s" % evalrespf, file=cd1)
        #            print("quit", file=cd1)
        #            cd1.close()
        #            p.wait()

        tr = read(rawf)[0]
        trtest = read(evalrespf)[0]
        date = UTCDateTime(2003, 11, 1, 0, 0, 0)
        seedresp = {
            "filename": respf,
            "date": date,
            "units": "VEL",
            "network": "NZ",
            "station": "CRLZ",
            "location": "10",
            "channel": "HHZ",
        }
        tr.data = simulate_seismometer(
            tr.data,
            tr.stats.sampling_rate,
            paz_remove=None,
            pre_filt=(fl1, fl2, fl3, fl4),
            seedresp=seedresp,
            taper_fraction=0.1,
            pitsasim=False,
            sacsim=True,
        )
        tr.data *= 1e9
        rms = np.sqrt(np.sum((tr.data - trtest.data) ** 2) / np.sum(trtest.data ** 2))
        self.assertTrue(rms < 0.0094)
Esempio n. 13
0
    def test_evalresp_vs_obspy(self):
        """
        Compare results from removing instrument response using
        evalresp in SAC and ObsPy. Visual inspection shows that the traces are
        pretty much identical but differences remain (rms ~ 0.042). Haven't
        found the cause for those, yet.
        """
        evalrespf = os.path.join(self.path, 'CRLZ.HHZ.10.NZ.SAC_resp')
        rawf = os.path.join(self.path, 'CRLZ.HHZ.10.NZ.SAC')
        respf = os.path.join(self.path, 'RESP.NZ.CRLZ.10.HHZ')
        fl1 = 0.00588
        fl2 = 0.00625
        fl3 = 30.
        fl4 = 35.

        #        #Set the following if-clause to True to run
        #        #the sac-commands that created the testing file
        #        if False:
        #            import subprocess as sp
        #            p = sp.Popen('sac', stdin=sp.PIPE)
        #            cd1 = p.stdin
        #            print("r %s" % rawf, file=cd1)
        #            print("rmean", file=cd1)
        #            print("taper type cosine width 0.05", file=cd1)
        #            print("transfer from evalresp fname %s to vel freqlimits\
        #            %f %f %f %f" % (respf, fl1, fl2, fl3, fl4), file=cd1)
        #            print("w over %s" % evalrespf, file=cd1)
        #            print("quit", file=cd1)
        #            cd1.close()
        #            p.wait()

        tr = read(rawf)[0]
        trtest = read(evalrespf)[0]
        date = UTCDateTime(2003, 11, 1, 0, 0, 0)
        seedresp = {
            'filename': respf,
            'date': date,
            'units': 'VEL',
            'network': 'NZ',
            'station': 'CRLZ',
            'location': '10',
            'channel': 'HHZ'
        }
        tr.data = simulate_seismometer(tr.data,
                                       tr.stats.sampling_rate,
                                       paz_remove=None,
                                       pre_filt=(fl1, fl2, fl3, fl4),
                                       seedresp=seedresp,
                                       taper_fraction=0.1,
                                       pitsasim=False,
                                       sacsim=True)
        tr.data *= 1e9
        rms = np.sqrt(
            np.sum((tr.data - trtest.data)**2) / np.sum(trtest.data**2))
        self.assertTrue(rms < 0.0094)
def remove_response(st, pre_filt=None, inv=None):
    for index, item in enumerate(st):
        pz_vir_file = io.StringIO()
        inv_tr = inv.select(channel=item.stats.channel)
        inv_tr.write(pz_vir_file, format="SACPZ")
        pz_vir_file.seek(0)
        obspy.io.sac.sacpz.attach_paz(item, pz_vir_file)
        data = simulate_seismometer(
            item.data, item.stats.sampling_rate, paz_remove=item.stats.paz, water_level=6e9, zero_mean=False, taper=False, pre_filt=pre_filt, sacsim=True)
        st[index].data = data
    return st
Esempio n. 15
0
def removeInstrument(st,args):

    if(args.sim == 'PZs'):

       # prefilters
       f = args.flim.split()
       f0 = eval(f[0])
       f1 = eval(f[1])
       f2 = eval(f[2])
       f3 = eval(f[3])
       toPurge=  []   # station to purge if no Paz found

       for i in range(len(st)):
   
           # attach poles and zeros instrument
           if(args.dva=='1'):
              try:
                attach_paz(st[i], st[i].stats.PZs_file,todisp=False)
              except:
                print "No appropriate PZs file found for station " + st[i].stats.station,st[i].stats.channel,st[i].stats.network
                toPurge.append(st[i].stats.station)
           else:
              try:
                attach_paz(st[i], st[i].stats.PZs_file,tovel=True)
              except:
                print "No appropriate PZs file found for station " + st[i].stats.station,st[i].stats.channel,st[i].stats.network
                toPurge.append(st[i].stats.station)

                
       # remove stations if len(toPurge>0)
       if len(toPurge) > 0:
           st = purgeListStation(st,toPurge,'r')
           print "Check if station/channel/network/location of the PZs files and the same string within loaded binary files "
           print "do correspond. It may occour for instance that the headers strings of the waveform files (e.g. sac, fseed) "
           print "do not agrees with the same strings of the PZs name files. For instance the name of the network. "
           print "If these strings do not correspond, modify the name of the PZs files or the header values of the waveforms"
           print "You may also choose to remove this station using the option --purge (see help for details)"

       # now do remove
       for i in range(len(st)):

           # remove instrument to displacement
#          st[i].data=detrend(st[i].data)
           st[i].data = simulate_seismometer(st[i].data,st[i].stats.sampling_rate,paz_remove=st[i].stats.paz, \
                        taper=True, taper_fraction=0.050, pre_filt=(f0,f1,f2,f3)) #,water_level=60.0) 

           # from meters to centimeters
           st[i].data = st[i].data * 100
       
    
    return st
Esempio n. 16
0
    def test_evalresp_file_like_object(self):
        """
        Test evalresp with file like object
        """
        rawf = os.path.join(self.path, 'CRLZ.HHZ.10.NZ.SAC')
        respf = os.path.join(self.path, 'RESP.NZ.CRLZ.10.HHZ')

        tr1 = read(rawf)[0]
        tr2 = read(rawf)[0]

        date = UTCDateTime(2003, 11, 1, 0, 0, 0)
        seedresp = {'filename': respf, 'date': date, 'units': 'VEL',
                    'network': 'NZ', 'station': 'CRLZ', 'location': '10',
                    'channel': 'HHZ'}
        tr1.data = simulate_seismometer(
            tr1.data, tr1.stats.sampling_rate, seedresp=seedresp)

        with open(respf, 'rb') as fh:
            stringio = io.BytesIO(fh.read())
        seedresp['filename'] = stringio
        tr2.data = simulate_seismometer(tr2.data, tr2.stats.sampling_rate,
                                        seedresp=seedresp)

        self.assertEqual(tr1, tr2)
Esempio n. 17
0
def get_peak_spectrals(data, samp_rate, periods):
    """Calculate peak pseudo-spectral parameters.

    Compute 5% damped PSA at input periods seconds.

    Data must be an acceleration Trace.

    :param data:
      Obspy Trace object, containing acceleration data to convolve with pendulum at freq.
    :param delta: 
      sample rate (samples per sec).
    :returns: 
      Dictionary containing keys of input periods, and values of corresponding spectral accelerations.
    """

    D = 0.05  # 5% damping

    psadict = {}
    for T in periods:
        freq = 1.0 / T
        omega = (2 * 3.14159 * freq)**2

        paz_sa = corn_freq_2_paz(freq, damp=D)
        paz_sa['sensitivity'] = omega
        paz_sa['zeros'] = []
        dd = simulate_seismometer(data.data,
                                  samp_rate,
                                  paz_remove=None,
                                  paz_simulate=paz_sa,
                                  taper=True,
                                  simulate_sensitivity=True,
                                  taper_fraction=0.05)

        if abs(max(dd)) >= abs(min(dd)):
            psa = abs(max(dd))
        else:
            psa = abs(min(dd))
        psadict[T] = psa

    return psadict
Esempio n. 18
0
 def test_simulate(self):
     """
     Tests if calling simulate of trace gives the same result as using
     simulate_seismometer manually.
     """
     tr = read()[0]
     paz_sts2 = {'poles': [-0.037004 + 0.037016j, -0.037004 - 0.037016j,
                           - 251.33 + 0j, -131.04 - 467.29j,
                           - 131.04 + 467.29j],
                 'zeros': [0j, 0j],
                 'gain': 60077000.0,
                 'sensitivity': 2516778400.0}
     paz_le3d1s = {'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.0j],
                   'gain': 0.4,
                   'sensitivity': 1.0}
     data = simulate_seismometer(
         tr.data, tr.stats.sampling_rate, paz_remove=paz_sts2,
         paz_simulate=paz_le3d1s, remove_sensitivity=True,
         simulate_sensitivity=True)
     tr.simulate(paz_remove=paz_sts2, paz_simulate=paz_le3d1s)
     np.testing.assert_array_equal(tr.data, data)
Esempio n. 19
0
    def test_seis_sim_vs_pitsa_2(self):
        """
        Test simulate_seismometer seismometer simulation against seismometer
        simulation of Pitsa - STS-2 seismometer.
        """
        # load test file
        file = os.path.join(self.path, 'rotz_20081028.gz')
        with gzip.open(file) as f:
            data = np.loadtxt(f)

        # paz of test file
        samp_rate = 200.0
        paz_sts2 = {
            'poles': [-0.03736 - 0.03617j, -0.03736 + 0.03617j],
            'zeros': [0.0 + 0.0j] * 2,
            'sensitivity': 1.0,
            'gain': 1.5
        }

        for id, paz in INSTRUMENTS.items():
            # simulate instrument
            datcorr = simulate_seismometer(data,
                                           samp_rate,
                                           paz_remove=paz_sts2,
                                           paz_simulate=paz,
                                           water_level=600.0,
                                           zero_mean=False,
                                           nfft_pow2=True)
            # load pitsa file
            filename = os.path.join(self.path, 'rotz_20081028_%s.gz' % id)
            with gzip.open(filename) as f:
                data_pitsa = np.loadtxt(f)
            # calculate normalized rms
            rms = np.sqrt(
                np.sum((datcorr - data_pitsa)**2) / np.sum(data_pitsa**2))
            self.assertTrue(rms < 1e-04)
Esempio n. 20
0
    def test_seis_sim_vs_pitsa1(self):
        """
        Test simulate_seismometer seismometer simulation against seismometer
        simulation of Pitsa - LE3D seismometer.
        """
        # load test file
        filename = os.path.join(self.path, 'rjob_20051006.gz')
        with gzip.open(filename) as f:
            data = np.loadtxt(f)

        # paz of test file
        samp_rate = 200.0
        paz_le3d = {
            'poles': [-4.21 + 4.66j, -4.21 - 4.66j, -2.105 + 0.0j],
            'zeros': [0.0 + 0.0j] * 3,
            'sensitivity': 1.0,
            'gain': 0.4
        }

        for id, paz in INSTRUMENTS.items():
            # simulate instrument
            datcorr = simulate_seismometer(data,
                                           samp_rate,
                                           paz_remove=paz_le3d,
                                           paz_simulate=paz,
                                           water_level=600.0,
                                           zero_mean=False,
                                           nfft_pow2=True)
            # load pitsa file
            filename = os.path.join(self.path, 'rjob_20051006_%s.gz' % id)
            with gzip.open(filename) as f:
                data_pitsa = np.loadtxt(f)
            # calculate normalized rms
            rms = np.sqrt(
                np.sum((datcorr - data_pitsa)**2) / np.sum(data_pitsa**2))
            self.assertTrue(rms < 1.1e-05)
Esempio n. 21
0
from cut_traces3 import cut_traces
from resp import respN
from obspy.signal.invsim import seisSim,simulate_seismometer

units = 'DIS'
station = 'GUA'
pre_filt = (0.2, 0.3, 20.0, 25.0)

dic,head=cut_traces('01-2250-03L.S201403',0)
tr=dic[station][0]
tr2 = tr.copy()
tr1 = tr.copy()

seedrespN=respN(station,units)
tr1.simulate(paz_remove=None, pre_filt=pre_filt, seedresp=seedrespN)

seedrespN['date']=tr2.stats.starttime
seedrespN['network']=tr2.stats.network
seedrespN['station']=tr2.stats.station
seedrespN['location']=tr2.stats.location
seedrespN['network']=tr2.stats.network
seedrespN['channel']=tr2.stats.channel
tr2.data=simulate_seismometer(tr2.data, 100, remove_sensitivity=False, simulate_sensitivity=False, 
                 water_level=0, seedresp=seedrespN, pre_filt=None )

tr.plot()
#tr1.plot()
tr2.plot()
Esempio n. 22
0
def simulate(data, params, remove_sensitivity=True):
    """Remove instrumental response"""
    data -= np.mean(data)
    data = simulate_seismometer(data, params['df'], paz_remove=params['paz'], \
           pre_filt=params['pre_filt'], remove_sensitivity=remove_sensitivity)
    return data
Esempio n. 23
0
    def test_sac_instrument_correction(self):
        # SAC recommends to taper the transfer function if a pure
        # deconvolution is done instead of simulating a different
        # instrument. This test checks the difference between the
        # result from removing the instrument response using SAC or
        # ObsPy. Visual inspection shows that the traces are pretty
        # much identical but differences remain (rms ~ 0.042). Haven't
        # found the cause for those, yet. One possible reason is the
        # floating point arithmetic of SAC vs. the double precision
        # arithmetic of Python. However differences still seem to be
        # too big for that.
        pzf = os.path.join(self.path, 'SAC_PZs_KARC_BHZ')
        sacf = os.path.join(self.path, 'KARC.LHZ.SAC.asc.gz')
        testsacf = os.path.join(self.path, 'KARC_corrected.sac.asc.gz')
        plow = 160.
        phigh = 4.
        fl1 = 1.0 / (plow + 0.0625 * plow)
        fl2 = 1.0 / plow
        fl3 = 1.0 / phigh
        fl4 = 1.0 / (phigh - 0.25 * phigh)
        # Uncomment the following to run the sac-commands
        # that created the testing file
        # if 1:
        #    import subprocess as sp
        #    p = sp.Popen('sac',shell=True,stdin=sp.PIPE)
        #    cd1 = p.stdin
        #    print("r %s"%sacf, file=cd1)
        #    print("rmean", file=cd1)
        #    print("rtrend", file=cd1)
        #    print("taper type cosine width 0.03", file=cd1)
        #    print("transfer from polezero subtype %s to none \
        #    freqlimits %f %f %f %f" % (pzf, fl1, fl2, fl3, fl4), file=cd1)
        #    print("w over ./data/KARC_corrected.sac", file=cd1)
        #    print("quit", file=cd1)
        #    cd1.close()
        #    p.wait()

        stats = {
            'network': 'KA',
            'delta': 0.99999988079072466,
            'station': 'KARC',
            'location': 'S1',
            'starttime': UTCDateTime(2001, 2, 13, 0, 0, 0, 993700),
            'calib': 1.00868e+09,
            'channel': 'BHZ'
        }
        with gzip.open(sacf) as f:
            tr = Trace(np.loadtxt(f), stats)

        attach_paz(tr, pzf, tovel=False)
        tr.data = simulate_seismometer(tr.data,
                                       tr.stats.sampling_rate,
                                       paz_remove=tr.stats.paz,
                                       remove_sensitivity=False,
                                       pre_filt=(fl1, fl2, fl3, fl4))

        with gzip.open(testsacf) as f:
            data = np.loadtxt(f)

        # import matplotlib.pyplot as plt
        # plt.plot(tr.data)
        # plt.plot(data)
        # plt.show()
        rms = np.sqrt(np.sum((tr.data - data)**2) / np.sum(tr.data**2))
        self.assertTrue(rms < 0.0421)
Esempio n. 24
0
def peak_ground_motion(data, delta, freq, damp=0.1):
    """
    Peak ground motion parameters

    Compute the maximal displacement, velocity, acceleration and the peak
    ground acceleration at a certain frequency (standard frequencies for
    ShakeMaps are 0.3/1.0/3.0 Hz).

    Data must be displacement

    :type data: :class:`~numpy.ndarray`
    :param data: Data in displacement to convolve with pendulum at freq.
    :type delta: float
    :param delta: Sampling interval
    :type freq: float
    :param freq: Frequency in Hz.
    :type damp: float
    :param damp: damping factor. Default is set to 0.1
    :rtype: (float, float, float, float)
    :return: Peak Ground Acceleration, maximal displacement, velocity,
        acceleration
    """
    data = data.copy()

    # Displacement
    if abs(max(data)) >= abs(min(data)):
        m_dis = abs(max(data))
    else:
        m_dis = abs(min(data))

    # Velocity
    data = np.gradient(data, delta)
    if abs(max(data)) >= abs(min(data)):
        m_vel = abs(max(data))
    else:
        m_vel = abs(min(data))

    # Acceleration
    data = np.gradient(data, delta)
    if abs(max(data)) >= abs(min(data)):
        m_acc = abs(max(data))
    else:
        m_acc = abs(min(data))

    samp_rate = 1.0 / delta
    T = freq * 1.0
    D = damp
    omega = (2 * 3.14159 * T) ** 2

    paz_sa = corn_freq_2_paz(T, damp=D)
    paz_sa['sensitivity'] = omega
    paz_sa['zeros'] = []
    data = simulate_seismometer(data, samp_rate, paz_remove=None,
                                paz_simulate=paz_sa, taper=True,
                                simulate_sensitivity=True, taper_fraction=0.05)

    if abs(max(data)) >= abs(min(data)):
        pga = abs(max(data))
    else:
        pga = abs(min(data))

    return (pga, m_dis, m_vel, m_acc)
import obspy
from obspy.clients.arclink import Client
from obspy.signal.invsim import corn_freq_2_paz, simulate_seismometer


# Retrieve data via ArcLink
# please provide a valid email address for the keyword user
client = Client(user="******")
t = obspy.UTCDateTime("2009-08-24 00:20:03")
st = client.get_waveforms('BW', 'RJOB', '', 'EHZ', t, t + 30)
paz = client.get_paz('BW', 'RJOB', '', 'EHZ', t)

# 1Hz instrument
one_hertz = corn_freq_2_paz(1.0)
# Correct for frequency response of the instrument
res = simulate_seismometer(st[0].data.astype('float32'),
                           st[0].stats.sampling_rate, paz, inst_sim=one_hertz)
# Correct for overall sensitivity
res = res / paz['sensitivity']

# Plot the seismograms
sec = np.arange(len(res)) / st[0].stats.sampling_rate
plt.subplot(211)
plt.plot(sec, st[0].data, 'k')
plt.title("%s %s" % (st[0].stats.station, t))
plt.ylabel('STS-2')
plt.subplot(212)
plt.plot(sec, res, 'k')
plt.xlabel('Time [s]')
plt.ylabel('1Hz CornerFrequency')
plt.show()
Esempio n. 26
0
import obspy
from obspy.clients.arclink import Client
from obspy.signal.invsim import corn_freq_2_paz, simulate_seismometer

# Retrieve data via ArcLink
# please provide a valid email address for the keyword user
client = Client(user="******")
t = obspy.UTCDateTime("2009-08-24 00:20:03")
st = client.get_waveforms('BW', 'RJOB', '', 'EHZ', t, t + 30)
paz = client.get_paz('BW', 'RJOB', '', 'EHZ', t)

# 1Hz instrument
one_hertz = corn_freq_2_paz(1.0)
# Correct for frequency response of the instrument
res = simulate_seismometer(st[0].data.astype('float32'),
                           st[0].stats.sampling_rate,
                           paz,
                           inst_sim=one_hertz)
# Correct for overall sensitivity
res = res / paz['sensitivity']

# Plot the seismograms
sec = np.arange(len(res)) / st[0].stats.sampling_rate
plt.subplot(211)
plt.plot(sec, st[0].data, 'k')
plt.title("%s %s" % (st[0].stats.station, t))
plt.ylabel('STS-2')
plt.subplot(212)
plt.plot(sec, res, 'k')
plt.xlabel('Time [s]')
plt.ylabel('1Hz CornerFrequency')
plt.show()
Esempio n. 27
0
def peak_ground_motion(data, delta, freq, damp=0.1):
    """
    Peak ground motion parameters

    Compute the maximal displacement, velocity, acceleration and the peak
    ground acceleration at a certain frequency (standard frequencies for
    ShakeMaps are 0.3/1.0/3.0 Hz).

    Data must be displacement

    :type data: :class:`~numpy.ndarray`
    :param data: Data in displacement to convolve with pendulum at freq.
    :type delta: float
    :param delta: Sampling interval
    :type freq: float
    :param freq: Frequency in Hz.
    :type damp: float
    :param damp: damping factor. Default is set to 0.1
    :rtype: (float, float, float, float)
    :return: Peak Ground Acceleration, maximal displacement, velocity,
        acceleration
    """
    data = data.copy()

    # Displacement
    if abs(max(data)) >= abs(min(data)):
        m_dis = abs(max(data))
    else:
        m_dis = abs(min(data))

    # Velocity
    data = np.gradient(data, delta)
    if abs(max(data)) >= abs(min(data)):
        m_vel = abs(max(data))
    else:
        m_vel = abs(min(data))

    # Acceleration
    data = np.gradient(data, delta)
    if abs(max(data)) >= abs(min(data)):
        m_acc = abs(max(data))
    else:
        m_acc = abs(min(data))

    samp_rate = 1.0 / delta
    t = freq * 1.0
    d = damp
    omega = (2 * 3.14159 * t)**2

    paz_sa = corn_freq_2_paz(t, damp=d)
    paz_sa['sensitivity'] = omega
    paz_sa['zeros'] = []
    data = simulate_seismometer(data,
                                samp_rate,
                                paz_remove=None,
                                paz_simulate=paz_sa,
                                taper=True,
                                simulate_sensitivity=True,
                                taper_fraction=0.05)

    if abs(max(data)) >= abs(min(data)):
        pga = abs(max(data))
    else:
        pga = abs(min(data))

    return (pga, m_dis, m_vel, m_acc)
Esempio n. 28
0
                seedrespN['station']=trN.stats.station
                seedrespN['location']=trN.stats.location
                seedrespN['network']=trN.stats.network
                seedrespN['channel']=trN.stats.channel

                seedrespE['date']=trE.stats.starttime
                seedrespE['network']=trE.stats.network
                seedrespE['station']=trE.stats.station
                seedrespE['location']=trE.stats.location
                seedrespE['network']=trE.stats.network
                seedrespE['channel']=trE.stats.channel
                #"""            
            
                amp_t.append(trN.max())
                
                trN.data=simulate_seismometer(trN.data, 100, paz_remove=None, paz_simulate=None, remove_sensitivity=True, simulate_sensitivity=True, water_level=wt, taper=True, taper_fraction=tpf, pre_filt=pre_filt, seedresp=seedrespN, nfft_pow2=False)
                #trN.simulate(paz_remove=None, pre_filt=pre_filt, seedresp=seedrespN)
            
            
                trE.data=simulate_seismometer(trE.data, 100, paz_remove=None, paz_simulate=None, remove_sensitivity=True, simulate_sensitivity=True, water_level=wt, taper=True, taper_fraction=tpf, pre_filt=pre_filt, seedresp=seedrespN, nfft_pow2=False)
                #trE.simulate(paz_remove=None, pre_filt=pre_filt, seedresp=seedrespE)
            
    #          trN.plot(outfile='espectros/Swave_%s_%s.png' % (units,trN.stats.station))
                #trN.plot()
#==================================================================================================================            
#=========    #Calculando la transformada de fourier   ==============================================================
#==================================================================================================================            
                #spectrum=mper(trN.data,200,np.size(trN.data))
                n=np.size(trN.data)
                #dt=0.01
                t=np.linspace(0,n-1,n)*dt