Example #1
0
 def test_konnoOhmachiSmoothing(self):
     """
     Tests the actual smoothing matrix.
     """
     # Create some random spectra.
     np.random.seed(1111)
     spectra = np.random.ranf((5, 200)) * 50
     frequencies = np.logspace(-3.0, 2.0, 200)
     spectra = np.require(spectra, dtype=np.float32)
     frequencies = np.require(frequencies, dtype=np.float64)
     # Wrong dtype raises.
     self.assertRaises(ValueError, konnoOhmachiSmoothing, spectra,
                       np.arange(200))
     # Differing float dtypes raise a warning.
     with warnings.catch_warnings(record=True):
         warnings.simplefilter('error', UserWarning)
         self.assertRaises(UserWarning, konnoOhmachiSmoothing, spectra,
                           frequencies)
     warnings.filters.pop(0)
     # Correct the dtype.
     frequencies = np.require(frequencies, dtype=np.float32)
     # The first one uses the matrix method, the second one the non matrix
     # method.
     smoothed_1 = konnoOhmachiSmoothing(spectra, frequencies, count=3)
     smoothed_2 = konnoOhmachiSmoothing(spectra,
                                        frequencies,
                                        count=3,
                                        max_memory_usage=0)
     # XXX: Why are the numerical inaccuracies quite large?
     np.testing.assert_almost_equal(smoothed_1, smoothed_2, 3)
     # Test the non-matrix mode for single spectra.
     smoothed_3 = konnoOhmachiSmoothing(
         np.require(spectra[0], dtype='float64'),
         np.require(frequencies, dtype='float64'))
     smoothed_4 = konnoOhmachiSmoothing(np.require(spectra[0],
                                                   dtype='float64'),
                                        np.require(frequencies,
                                                   dtype='float64'),
                                        normalize=True)
     # The normalized and not normalized should not be the same. That the
     # normalizing works has been tested before.
     self.assertFalse(np.all(smoothed_3 == smoothed_4))
     # Input dtype should be output dtype.
     self.assertEqual(smoothed_3.dtype, np.float64)
Example #2
0
 def test_konnoOhmachiSmoothing(self):
     """
     Tests the actual smoothing matrix.
     """
     # Create some random spectra.
     np.random.seed(1111)
     spectra = np.random.ranf((5, 200)) * 50
     frequencies = np.logspace(-3.0, 2.0, 200)
     spectra = np.require(spectra, dtype=np.float32)
     frequencies = np.require(frequencies, dtype=np.float64)
     # Wrong dtype raises.
     self.assertRaises(ValueError, konnoOhmachiSmoothing, spectra,
                       np.arange(200))
     # Differing float dtypes raise a warning.
     with warnings.catch_warnings(record=True):
         warnings.simplefilter('error', UserWarning)
         self.assertRaises(UserWarning, konnoOhmachiSmoothing, spectra,
                           frequencies)
     warnings.filters.pop(0)
     # Correct the dtype.
     frequencies = np.require(frequencies, dtype=np.float32)
     # The first one uses the matrix method, the second one the non matrix
     # method.
     smoothed_1 = konnoOhmachiSmoothing(spectra, frequencies, count=3)
     smoothed_2 = konnoOhmachiSmoothing(spectra, frequencies, count=3,
                                        max_memory_usage=0)
     # XXX: Why are the numerical inaccuracies quite large?
     np.testing.assert_almost_equal(smoothed_1, smoothed_2, 3)
     # Test the non-matrix mode for single spectra.
     smoothed_3 = konnoOhmachiSmoothing(
         np.require(spectra[0], dtype='float64'),
         np.require(frequencies, dtype='float64'))
     smoothed_4 = konnoOhmachiSmoothing(
         np.require(spectra[0], dtype='float64'),
         np.require(frequencies, dtype='float64'),
         normalize=True)
     # The normalized and not normalized should not be the same. That the
     # normalizing works has been tested before.
     self.assertFalse(np.all(smoothed_3 == smoothed_4))
     # Input dtype should be output dtype.
     self.assertEqual(smoothed_3.dtype, np.float64)
Example #3
0
def relcalstack(st1, st2, calib_file, window_len, overlap_frac=0.5, smooth=0,
                save_data=True):
    """
    Method for relative calibration of sensors using a sensor with known
    transfer function

    :param st1: Stream or Trace object, (known)
    :param st2: Stream or Trace object, (unknown)
    :type calib_file: String
    :param calib_file: file name of calibration file containing the PAZ of the
        known instrument in GSE2 standard.
    :type window_len: Float
    :param window_len: length of sliding window in seconds
    :type overlap_frac: float
    :param overlap_frac: fraction of overlap, defaults to fifty percent (0.5)
    :type smooth: Float
    :param smooth: variable that defines if the Konno-Ohmachi taper is used or
        not. default = 0 -> no taper generally used in geopsy: smooth = 40
    :type save_data: Boolean
    :param save_data: Whether or not to save the result to a file. If True, two
        output files will be created:
        * The new response in station_name.window_length.resp
        * The ref response in station_name.refResp
        Defaults to True
    :returns: frequency, amplitude and phase spectrum

    implemented after relcalstack.c by M.Ohrnberger and J.Wassermann.
    """
    # transform given trace objects to streams
    if isinstance(st1, Trace):
        st1 = Stream([st1])
    if isinstance(st2, Trace):
        st2 = Stream([st2])
    # check if sampling rate and trace length is the same
    if st1[0].stats.npts != st2[0].stats.npts:
        msg = "Traces don't have the same length!"
        raise ValueError(msg)
    elif st1[0].stats.sampling_rate != st2[0].stats.sampling_rate:
        msg = "Traces don't have the same sampling rate!"
        raise ValueError(msg)
    else:
        ndat1 = st1[0].stats.npts
        sampfreq = st1[0].stats.sampling_rate

    # read waveforms
    tr1 = st1[0].data.astype(np.float64)
    tr2 = st2[0].data.astype(np.float64)

    # get window length, nfft and frequency step
    ndat = int(window_len * sampfreq)
    nfft = nextpow2(ndat)

    # read calib file and calculate response function
    gg, _freq = _calcresp(calib_file, nfft, sampfreq)

    # calculate number of windows and overlap
    nwin = int(np.floor((ndat1 - nfft) / (nfft / 2)) + 1)
    noverlap = nfft * overlap_frac

    auto, _freq, _t = \
        spectral_helper(tr1, tr1, NFFT=nfft, Fs=sampfreq, noverlap=noverlap)
    cross, freq, _t = \
        spectral_helper(tr2, tr1, NFFT=nfft, Fs=sampfreq, noverlap=noverlap)

    res = (cross / auto).sum(axis=1) * gg

    # The first item might be zero. Problems with phase calculations.
    res = res[1:]
    freq = freq[1:]
    gg = gg[1:]

    res /= nwin
    # apply Konno-Ohmachi smoothing taper if chosen
    if smooth > 0:
        # Write in one matrix for performance reasons.
        spectra = np.empty((2, len(res.real)))
        spectra[0] = res.real
        spectra[1] = res.imag
        new_spectra = \
            konnoOhmachiSmoothing(spectra, freq, bandwidth=smooth, count=1,
                                  max_memory_usage=1024, normalize=True)
        res.real = new_spectra[0]
        res.imag = new_spectra[1]

    amp = np.abs(res)
    # include phase unwrapping
    phase = np.unwrap(np.angle(res))  # + 2.0 * np.pi
    ra = np.abs(gg)
    rpha = np.unwrap(np.angle(gg))

    if save_data:
        trans_new = (st2[0].stats.station + "." + st2[0].stats.channel +
                     "." + str(window_len) + ".resp")
        trans_ref = st1[0].stats.station + ".refResp"
        # Create empty array for easy saving
        temp = np.empty((len(freq), 3))
        temp[:, 0] = freq
        temp[:, 1] = amp
        temp[:, 2] = phase
        np.savetxt(trans_new, temp, fmt="%.10f")
        temp[:, 1] = ra
        temp[:, 2] = rpha
        np.savetxt(trans_ref, temp, fmt="%.10f")

    return freq, amp, phase
Example #4
0
def relcalstack(st1,
                st2,
                calib_file,
                window_len,
                overlap_frac=0.5,
                smooth=0,
                save_data=True):
    """
    Method for relative calibration of sensors using a sensor with known
    transfer function

    :param st1: Stream or Trace object, (known)
    :param st2: Stream or Trace object, (unknown)
    :type calib_file: str
    :param calib_file: file name of calibration file containing the PAZ of the
        known instrument in GSE2 standard.
    :type window_len: float
    :param window_len: length of sliding window in seconds
    :type overlap_frac: float
    :param overlap_frac: fraction of overlap, defaults to fifty percent (0.5)
    :type smooth: float
    :param smooth: variable that defines if the Konno-Ohmachi taper is used or
        not. default = 0 -> no taper generally used in geopsy: smooth = 40
    :type save_data: bool
    :param save_data: Whether or not to save the result to a file. If True, two
        output files will be created:
        * The new response in station_name.window_length.resp
        * The ref response in station_name.refResp
        Defaults to True
    :returns: frequency, amplitude and phase spectrum

    implemented after relcalstack.c by M.Ohrnberger and J.Wassermann.
    """
    # transform given trace objects to streams
    if isinstance(st1, Trace):
        st1 = Stream([st1])
    if isinstance(st2, Trace):
        st2 = Stream([st2])
    # check if sampling rate and trace length is the same
    if st1[0].stats.npts != st2[0].stats.npts:
        msg = "Traces don't have the same length!"
        raise ValueError(msg)
    elif st1[0].stats.sampling_rate != st2[0].stats.sampling_rate:
        msg = "Traces don't have the same sampling rate!"
        raise ValueError(msg)
    else:
        ndat1 = st1[0].stats.npts
        sampfreq = st1[0].stats.sampling_rate

    # read waveforms
    tr1 = st1[0].data.astype(np.float64)
    tr2 = st2[0].data.astype(np.float64)

    # get window length, nfft and frequency step
    ndat = int(window_len * sampfreq)
    nfft = nextpow2(ndat)

    # read calib file and calculate response function
    gg, _freq = _calcresp(calib_file, nfft, sampfreq)

    # calculate number of windows and overlap
    nwin = int(np.floor((ndat1 - nfft) / (nfft / 2)) + 1)
    noverlap = nfft * overlap_frac

    auto, _freq, _t = \
        spectral_helper(tr1, tr1, NFFT=nfft, Fs=sampfreq, noverlap=noverlap)
    cross, freq, _t = \
        spectral_helper(tr2, tr1, NFFT=nfft, Fs=sampfreq, noverlap=noverlap)

    res = (cross / auto).sum(axis=1) * gg

    # The first item might be zero. Problems with phase calculations.
    res = res[1:]
    freq = freq[1:]
    gg = gg[1:]

    res /= nwin
    # apply Konno-Ohmachi smoothing taper if chosen
    if smooth > 0:
        # Write in one matrix for performance reasons.
        spectra = np.empty((2, len(res.real)))
        spectra[0] = res.real
        spectra[1] = res.imag
        new_spectra = \
            konnoOhmachiSmoothing(spectra, freq, bandwidth=smooth, count=1,
                                  max_memory_usage=1024, normalize=True)
        res.real = new_spectra[0]
        res.imag = new_spectra[1]

    amp = np.abs(res)
    # include phase unwrapping
    phase = np.unwrap(np.angle(res))  # + 2.0 * np.pi
    ra = np.abs(gg)
    rpha = np.unwrap(np.angle(gg))

    if save_data:
        trans_new = (st2[0].stats.station + "." + st2[0].stats.channel + "." +
                     str(window_len) + ".resp")
        trans_ref = st1[0].stats.station + ".refResp"
        # Create empty array for easy saving
        temp = np.empty((len(freq), 3))
        temp[:, 0] = freq
        temp[:, 1] = amp
        temp[:, 2] = phase
        np.savetxt(trans_new, temp, fmt="%.10f")
        temp[:, 1] = ra
        temp[:, 2] = rpha
        np.savetxt(trans_ref, temp, fmt="%.10f")

    return freq, amp, phase