Exemple #1
0
def bandwidth(data, fs, smoothie, fk):
    """
    Bandwidth of a signal.

    Computes the bandwidth of the given data which can be windowed or not.
    The bandwidth corresponds to the level where the power of the spectrum is
    half its maximum value. It is determined as the level of 1/sqrt(2) times
    the maximum Fourier amplitude.

    If data are windowed the bandwidth of each window is returned.

    :type data: :class:`~numpy.ndarray`
    :param data: Data to make envelope of.
    :param fs: Sampling frequency in Hz.
    :param smoothie: Factor for smoothing the result.
    :param fk: Coefficients for calculating time derivatives
        (calculated via central difference).
    :return: **bandwidth[, dbwithd]** - Bandwidth, Time derivative of
        predominant period (windowed only).
    """
    new_dtype = np.float32 if data.dtype.itemsize == 4 else np.float64
    data = np.require(data, dtype=new_dtype)

    nfft = util.next_pow_2(data.shape[1])
    freqaxis = np.linspace(0, fs, nfft + 1)
    bwith = np.zeros(data.shape[0])
    f = fftpack.fft(data, nfft)
    f_sm = util.smooth(abs(f[:, 0:nfft // 2]), 10)
    if np.size(data.shape) > 1:
        i = 0
        for row in f_sm:
            minfc = abs(row - max(abs(row * (1 / np.sqrt(2)))))
            [mdist_ind, _mindist] = min(enumerate(minfc), key=itemgetter(1))
            bwith[i] = freqaxis[mdist_ind]
            i = i + 1
        # bwith_add = \
        # np.append(np.append([bandwidth[0]] * (np.size(fk) // 2), bandwidth),
        #        [bandwidth[np.size(bandwidth) - 1]] * (np.size(fk) // 2))
        # faster alternative
        bwith_add = np.hstack(
            ([bwith[0]] * (np.size(fk) // 2), bwith,
             [bwith[np.size(bwith) - 1]] * (np.size(fk) // 2)))
        dbwith = signal.lfilter(fk, 1, bwith_add)
        # dbwith = dbwith[np.size(fk) // 2:(np.size(dbwith) -
        #         np.size(fk) // 2)]
        # correct start and end values of time derivative
        dbwith = dbwith[np.size(fk) - 1:]
        bwith = util.smooth(bwith, smoothie)
        dbwith = util.smooth(dbwith, smoothie)
        return bwith, dbwith
    else:
        minfc = abs(data - max(abs(data * (1 / np.sqrt(2)))))
        [mdist_ind, _mindist] = min(enumerate(minfc), key=itemgetter(1))
        bwith = freqaxis[mdist_ind]
        return bwith
Exemple #2
0
def bandwidth(data, fs, smoothie, fk):
    """
    Bandwidth of a signal.

    Computes the bandwidth of the given data which can be windowed or not.
    The bandwidth corresponds to the level where the power of the spectrum is
    half its maximum value. It is determined as the level of 1/sqrt(2) times
    the maximum Fourier amplitude.

    If data are windowed the bandwidth of each window is returned.

    :type data: :class:`~numpy.ndarray`
    :param data: Data to make envelope of.
    :param fs: Sampling frequency in Hz.
    :param smoothie: Factor for smoothing the result.
    :param fk: Coefficients for calculating time derivatives
        (calculated via central difference).
    :return: **bandwidth[, dbwithd]** - Bandwidth, Time derivative of
        predominant period (windowed only).
    """
    new_dtype = np.float32 if data.dtype.itemsize == 4 else np.float64
    data = np.require(data, dtype=new_dtype)

    nfft = util.next_pow_2(data.shape[1])
    freqaxis = np.linspace(0, fs, nfft + 1)
    bwith = np.zeros(data.shape[0])
    f = fftpack.fft(data, nfft)
    f_sm = util.smooth(abs(f[:, 0:nfft // 2]), 10)
    if np.size(data.shape) > 1:
        i = 0
        for row in f_sm:
            minfc = abs(row - max(abs(row * (1 / np.sqrt(2)))))
            [mdist_ind, _mindist] = min(enumerate(minfc), key=itemgetter(1))
            bwith[i] = freqaxis[mdist_ind]
            i = i + 1
        # bwith_add = \
        # np.append(np.append([bandwidth[0]] * (np.size(fk) // 2), bandwidth),
        #        [bandwidth[np.size(bandwidth) - 1]] * (np.size(fk) // 2))
        # faster alternative
        bwith_add = np.hstack(
            ([bwith[0]] * (np.size(fk) // 2), bwith,
             [bwith[np.size(bwith) - 1]] * (np.size(fk) // 2)))
        dbwith = signal.lfilter(fk, 1, bwith_add)
        # dbwith = dbwith[np.size(fk) // 2:(np.size(dbwith) -
        #         np.size(fk) // 2)]
        # correct start and end values of time derivative
        dbwith = dbwith[np.size(fk) - 1:]
        bwith = util.smooth(bwith, smoothie)
        dbwith = util.smooth(dbwith, smoothie)
        return bwith, dbwith
    else:
        minfc = abs(data - max(abs(data * (1 / np.sqrt(2)))))
        [mdist_ind, _mindist] = min(enumerate(minfc), key=itemgetter(1))
        bwith = freqaxis[mdist_ind]
        return bwith
Exemple #3
0
def dominant_period(data, fs, smoothie, fk):
    """
    Predominant period of a signal.

    Computes the predominant period of the given data which can be windowed or
    not. The period is determined as the period of the maximum value of the
    Fourier amplitude spectrum.

    If data are windowed the predominant period of each window is returned.

    :type data: :class:`~numpy.ndarray`
    :param data: Data to determine predominant period of.
    :param fs: Sampling frequency in Hz.
    :param smoothie: Factor for smoothing the result.
    :param fk: Coefficients for calculating time derivatives
        (calculated via central difference).
    :return: **dperiod[, ddperiod]** - Predominant period, Time derivative of
        predominant period (windowed only).
    """
    new_dtype = np.float32 if data.dtype.itemsize == 4 else np.float64
    data = np.require(data, dtype=new_dtype)

    nfft = 1024
    # nfft = util.next_pow_2(data.shape[1])
    freqaxis = np.linspace(0, fs, nfft + 1)
    dperiod = np.zeros(data.shape[0])
    f = fftpack.fft(data, nfft)
    # f_sm = util.smooth(abs(f[:,0:nfft // 2]),1)
    f_sm = f[:, 0:nfft // 2]
    if np.size(data.shape) > 1:
        i = 0
        for row in f_sm:
            [mdist_ind, _mindist] = max(enumerate(abs(row)), key=itemgetter(1))
            dperiod[i] = freqaxis[mdist_ind]
            i = i + 1
        # dperiod_add = np.append(np.append([dperiod[0]] * \
        #        (np.size(fk) // 2), dperiod),
        #        [dperiod[np.size(dperiod) - 1]] * (np.size(fk) // 2))
        # faster alternative
        dperiod_add = np.hstack(
            ([dperiod[0]] * (np.size(fk) // 2), dperiod,
             [dperiod[np.size(dperiod) - 1]] * (np.size(fk) // 2)))
        ddperiod = signal.lfilter(fk, 1, dperiod_add)
        # ddperiod = ddperiod[np.size(fk) / \
        #    2:(np.size(ddperiod) - np.size(fk) // 2)]
        # correct start and end values of time derivative
        ddperiod = ddperiod[np.size(fk) - 1:]
        dperiod = util.smooth(dperiod, smoothie)
        ddperiod = util.smooth(ddperiod, smoothie)
        return dperiod, ddperiod
    else:
        [mdist_ind, _mindist] = max(enumerate(abs(data)), key=itemgetter(1))
        dperiod = freqaxis[mdist_ind]
        return dperiod
Exemple #4
0
def dominant_period(data, fs, smoothie, fk):
    """
    Predominant period of a signal.

    Computes the predominant period of the given data which can be windowed or
    not. The period is determined as the period of the maximum value of the
    Fourier amplitude spectrum.

    If data are windowed the predominant period of each window is returned.

    :type data: :class:`~numpy.ndarray`
    :param data: Data to determine predominant period of.
    :param fs: Sampling frequency in Hz.
    :param smoothie: Factor for smoothing the result.
    :param fk: Coefficients for calculating time derivatives
        (calculated via central difference).
    :return: **dperiod[, ddperiod]** - Predominant period, Time derivative of
        predominant period (windowed only).
    """
    new_dtype = np.float32 if data.dtype.itemsize == 4 else np.float64
    data = np.require(data, dtype=new_dtype)

    nfft = 1024
    # nfft = util.next_pow_2(data.shape[1])
    freqaxis = np.linspace(0, fs, nfft + 1)
    dperiod = np.zeros(data.shape[0])
    f = fftpack.fft(data, nfft)
    # f_sm = util.smooth(abs(f[:,0:nfft // 2]),1)
    f_sm = f[:, 0:nfft // 2]
    if np.size(data.shape) > 1:
        i = 0
        for row in f_sm:
            [mdist_ind, _mindist] = max(enumerate(abs(row)), key=itemgetter(1))
            dperiod[i] = freqaxis[mdist_ind]
            i = i + 1
        # dperiod_add = np.append(np.append([dperiod[0]] * \
        #        (np.size(fk) // 2), dperiod),
        #        [dperiod[np.size(dperiod) - 1]] * (np.size(fk) // 2))
        # faster alternative
        dperiod_add = np.hstack(
            ([dperiod[0]] * (np.size(fk) // 2), dperiod,
             [dperiod[np.size(dperiod) - 1]] * (np.size(fk) // 2)))
        ddperiod = signal.lfilter(fk, 1, dperiod_add)
        # ddperiod = ddperiod[np.size(fk) / \
        #    2:(np.size(ddperiod) - np.size(fk) // 2)]
        # correct start and end values of time derivative
        ddperiod = ddperiod[np.size(fk) - 1:]
        dperiod = util.smooth(dperiod, smoothie)
        ddperiod = util.smooth(ddperiod, smoothie)
        return dperiod, ddperiod
    else:
        [mdist_ind, _mindist] = max(enumerate(abs(data)), key=itemgetter(1))
        dperiod = freqaxis[mdist_ind]
        return dperiod
Exemple #5
0
def cfrequency(data, fs, smoothie, fk):

    nfft = nextpow2(data.shape[0])
    freq = np.arange(0, float(fs) - 1. / (nextpow2(data.shape[0]) / float(fs)),
                                 1. / (nextpow2(data.shape[0]) / float(fs)))
    freqaxis = freq[0:len(freq) / 2 + 1]
    cfreq = np.zeros(data.shape[0])
    if (np.size(data.shape) > 1):
        i = 0
        for row in data:
            Px_wm = welch(row, hamming(len(row)), nextpow2(len(row)))
            Px = Px_wm[0:len(Px_wm) / 2]
            cfreq[i] = np.sqrt(sum(pow(freqaxis, 2) * Px) / (sum(Px)))
            i = i + 1
        cfreq = smooth(cfreq, smoothie)
        cfreq_add = append(append([cfreq[0]] * (size(fk) // 2), cfreq),
                              [cfreq[size(cfreq) - 1]] * (size(fk) // 2))
        dcfreq = signal.lfilter(fk, 1, cfreq_add)
        dcfreq = dcfreq[size(fk) // 2:(size(dcfreq) - size(fk) // 2)]
        return cfreq, dcfreq
    else:
        Px_wm = welch(data, np.hamming(len(data)), nextpow2(len(data)))
        Px = Px_wm[0:len(Px_wm) / 2]
        cfreq = np.sqrt(np.sum(pow(freqaxis, 2) * Px) / (sum(Px)))

    return cfreq
Exemple #6
0
def whiteCalib(monitor_trace, response_trace, **kwargs):

	m_trace=monitor_trace.copy()
	r_trace=response_trace.copy()

	#Calcul du spectre du signal moniteur et du spectre de la réponse de la bobine
	mSpectre=np.fft.fft(m_trace.data)
	rSpectre=np.fft.fft(r_trace.data)
	
	#Fréquences associées
	f1=np.fft.fftfreq(len(mSpectre), d=1./m_trace.stats.sampling_rate)
	f2=np.fft.fftfreq(len(rSpectre), d=1./r_trace.stats.sampling_rate)
	
	if len(f1)-len(f2) != 0 or np.sum(f1-f2)!=0:
		print("Warning: frequencies arrays does'nt have same length or frequencies arrays not strictly identical, mixing")
		fmax=np.minimum(np.amax(np.absolute(f1)), np.amax(np.absolute(f2)))
		i1=np.where(np.absolute(f1)<fmax)
		f1=f1[i1]
		mSpectre=mSpectre[i1]
		i2=np.where(np.absolute(f2)<fmax)
		f2=f2[i2]
		rSpectre=rSpectre[i2]

		if len(f1)>len(f2):
			i=np.argmax(f1)
			f1=np.delete(f1, i)
			mSpectre=np.delete(mSpectre, i)
			i=np.argmin(f1)
			f1=np.delete(f1, i)
			mSpectre=np.delete(mSpectre, i)
		elif len(f2)>len(f1):
			i=np.argmax(f2)
			f2=np.delete(f2, i)
			rSpectre=np.delete(rSpectre, i)
			i=np.argmin(f2)
			f2=np.delete(f2, i)
			rSpectre=np.delete(rSpectre, i)			
		
	#Division spectrale brute (calcul de la fonction de transfert)
	H=rSpectre/mSpectre

	if 'smooth' in kwargs:
		H=smooth(H, kwargs['smooth'])
	else:
		H=smooth(H, int(len(f1)*0.0001))
	
	return (H,f1) 
Exemple #7
0
def TemporalNormalization(trace):
    if normalization_method == 1:
        trace.data = np.sign(trace.data)

    if normalization_method == 2:
        winsize = period_max / 2.0 * trace.stats.sampling_rate
        tmp = util.smooth(abs(trace.data), round(winsize))
        trace.data = trace.data / tmp

    return trace
Exemple #8
0
def env_norm(stream, N):
    stream2 = copy.deepcopy(stream)

    for trace in arange(len(stream2)):
        data = stream2[trace].data
        norm = util.smooth(absolute(data), N)
        #normdata = cpxtrace.normEnvelope(data, fs=stream2[trace].stats.sampling_rate, smoothie=N, fk=[1, 1, 1, 1, 1] )

        normdata = true_divide(data, norm)
        stream2[trace].data = normdata

    return stream2
def env_norm(stream, N):
    stream2 = copy.deepcopy(stream)
    
    for trace in arange(len(stream2)):
        data = stream2[trace].data
        norm = util.smooth(absolute(data), N)
        #normdata = cpxtrace.normEnvelope(data, fs=stream2[trace].stats.sampling_rate, smoothie=N, fk=[1, 1, 1, 1, 1] )
        
        normdata = true_divide(data,norm)
        stream2[trace].data = normdata
        
    return stream2
def _get_cut_times(config, tr):
    """Get trace cut times between P arrival and end of envelope coda."""
    tr_env = tr.copy()
    # remove the mean...
    tr_env.detrend(type='constant')
    # ...and the linear trend...
    tr_env.detrend(type='linear')
    # ...filter
    freqmin = 1.
    freqmax = 20.
    nyquist = 1./(2. * tr.stats.delta)
    if freqmax >= nyquist:
        freqmax = nyquist * 0.999
        msg = '%s: maximum frequency for bandpass filtering ' % tr.id
        msg += 'in local magnitude computation is larger than or equal '
        msg += 'to Nyquist. Setting it to %s Hz' % freqmax
        logger.warning(msg)
    cosine_taper(tr_env.data, width=config.taper_halfwidth)
    tr_env.filter(type='bandpass', freqmin=freqmin, freqmax=freqmax)
    tr_env.data = envelope(tr_env.data)
    tr_env.data = smooth(tr_env.data, 100)

    # Skip traces which do not have arrivals
    try:
        p_arrival_time = tr.stats.arrivals['P'][1]
    except Exception:
        logger.warning('%s: Trace has no P arrival: skipping trace' % tr.id)
        raise RuntimeError
    t1 = p_arrival_time - config.win_length
    t2 = p_arrival_time + config.win_length

    tr_noise = tr_env.copy()
    tr_signal = tr_env.copy()
    tr_noise.trim(starttime=t1, endtime=p_arrival_time,
                  pad=True, fill_value=0)
    tr_signal.trim(starttime=p_arrival_time, endtime=t2,
                   pad=True, fill_value=0)
    ampmin = tr_noise.data.mean()
    ampmax = tr_signal.data.mean()
    if ampmax <= ampmin:
        logger.warning(
            '%s: Trace has too high noise before P arrival: '
            'skipping trace' % tr.id)
        raise RuntimeError

    trigger = trigger_onset(tr_env.data, ampmax, ampmin,
                            max_len=9e99, max_len_delete=False)[0]
    t0 = p_arrival_time
    t1 = t0 + trigger[-1] * tr.stats.delta
    if t1 > tr.stats.endtime:
        t1 = tr.stats.endtime
    return t0, t1
Exemple #11
0
def start_end(tr):
    """
    Returns start and end times of signal using signal 2 noise ratio
    """

    # set noise level as 5th percentile on envelope amplitudes
    env = envelope(tr.data)
    env = smooth(env, 100)
    noise_level = np.percentile(env, 5.0)

    # trigger
    t_list = triggerOnset(env, 1.5 * noise_level, 1.5 * noise_level)
    i_start = t_list[0][0]
    i_end = t_list[0][1]

    return i_start, i_end
Exemple #12
0
def central_frequency(data, fs, smoothie, fk):
    """
    Central frequency of a signal.

    Computes the central frequency of the given data which can be windowed or
    not. The central frequency is a measure of the frequency where the
    power is concentrated. It corresponds to the second moment of the power
    spectral density function.

    The central frequency is returned.

    :type data: :class:`~numpy.ndarray`
    :param data: Data to estimate central frequency from.
    :param fs: Sampling frequency in Hz.
    :param smoothie: Factor for smoothing the result.
    :param fk: Coefficients for calculating time derivatives
        (calculated via central difference).
    :return: **cfreq[, dcfreq]** - Central frequency, Time derivative of center
        frequency (windowed only).
    """
    # for windowed data
    if np.size(data.shape) > 1:
        cfreq = np.zeros(data.shape[0])
        i = 0
        for row in data:
            cfreq[i] = central_frequency_unwindowed(row, fs)
            i = i + 1
        cfreq = util.smooth(cfreq, smoothie)
        # cfreq_add = \
        #        np.append(np.append([cfreq[0]] * (np.size(fk) // 2), cfreq),
        #        [cfreq[np.size(cfreq) - 1]] * (np.size(fk) // 2))
        # faster alternative
        cfreq_add = np.hstack(
            ([cfreq[0]] * (np.size(fk) // 2), cfreq,
             [cfreq[np.size(cfreq) - 1]] * (np.size(fk) // 2)))
        dcfreq = signal.lfilter(fk, 1, cfreq_add)
        # dcfreq = dcfreq[np.size(fk) // 2:(np.size(dcfreq) -
        #         np.size(fk) // 2)]
        # correct start and end values of time derivative
        dcfreq = dcfreq[np.size(fk) - 1:np.size(dcfreq)]
        return cfreq, dcfreq
    # for unwindowed data
    else:
        cfreq = central_frequency_unwindowed(data, fs)
        return cfreq
Exemple #13
0
def cfrequency(data, fs, smoothie, fk):
    """
    Central frequency of a signal.

    Computes the central frequency of the given data which can be windowed or
    not. The central frequency is a measure of the frequency where the
    power is concentrated. It corresponds to the second moment of the power
    spectral density function.

    The central frequency is returned.

    :type data: :class:`~numpy.ndarray`
    :param data: Data to estimate central frequency from.
    :param fs: Sampling frequency in Hz.
    :param smoothie: Factor for smoothing the result.
    :param fk: Coefficients for calculating time derivatives
        (calculated via central difference).
    :return: **cfreq[, dcfreq]** - Central frequency, Time derivative of center
        frequency (windowed only).
    """
    # for windowed data
    if np.size(data.shape) > 1:
        cfreq = np.zeros(data.shape[0])
        i = 0
        for row in data:
            cfreq[i] = cfrequency_unwindowed(row, fs)
            i = i + 1
        cfreq = util.smooth(cfreq, smoothie)
        # cfreq_add = \
        #        np.append(np.append([cfreq[0]] * (np.size(fk) // 2), cfreq),
        #        [cfreq[np.size(cfreq) - 1]] * (np.size(fk) // 2))
        # faster alternative
        cfreq_add = np.hstack(
            ([cfreq[0]] * (np.size(fk) // 2), cfreq, [cfreq[np.size(cfreq) - 1]] * (np.size(fk) // 2))
        )
        dcfreq = signal.lfilter(fk, 1, cfreq_add)
        # dcfreq = dcfreq[np.size(fk) // 2:(np.size(dcfreq) -
        #         np.size(fk) // 2)]
        # correct start and end values of time derivative
        dcfreq = dcfreq[np.size(fk) - 1 : np.size(dcfreq)]
        return cfreq, dcfreq
    # for unwindowed data
    else:
        cfreq = cfrequency_unwindowed(data, fs)
        return cfreq
Exemple #14
0
def duration_exceed_RMS(x, ampthresh, RMSlen, dt):
    """
    Noise level metric that calcualtes the total duration of the RMS
    function above a theshold (ampthresh).
    RMSlen = window length used to calculate RMS (sec)
    x: np array or list of numbers
    st = an ObsPy stream
    dt = timeseries increment (sec)
    """
    from obspy.signal.util import smooth
    duration = 0
    if (len(x) > int(RMSlen / dt)):
        iRMSwinlen = int(RMSlen / dt)
        RMS = np.sqrt(smooth((x**2), iRMSwinlen))
        duration = ((RMS > ampthresh).sum()) * dt
    else:
        duration = []
        duration = -1
        print("Error duration_exceed_RMS: len(x)=" + str(len(x) * dt) +
              " must be greater than RMSlen=" + str(RMSlen))

    return duration
Exemple #15
0
             + frq_bnd + 'Hz_' + cpnt + '_smooth')

# create the directory path_rslt in case it does not exist
if not os.path.isdir(path_rslt):
    try:
        os.makedirs(path_rslt)
    except OSError:
        print('Creation of the directory {} failed'.format(path_rslt))
    else:
        print('Successfully created the directory {}'.format(path_rslt))
else:
    print('{} is already existing'.format(path_rslt))

# pick the envelopes from the directory path_data
lst_fch = os.listdir(path_data)

print('Smoothing of the envelopes')
for s in lst_fch:
    os.chdir(path_data)
    # load the envelope
    st = read(s)
    # smooth the envelope
    tr = smooth(st[0].data, int(l_smooth/st[0].stats.delta))
    # preparation for SAC format
    tr = Trace(tr, st[0].stats)
    # save the file
    os.chdir(path_rslt)
    tr.write(s[:-4] + '_smooth.sac', format = 'SAC')
    print('The envelope of the station {}'.format(s[:6]),
            'has been successfully smoothed')
Exemple #16
0
list_fich = [
    a for a in list_fich if ('UD' in a) == True and ('UD1' in a) == False
]

for station in list_fich:
    print(station)
    os.chdir(path_data)
    st = read(station)
    st.detrend(type='constant')
    tstart = st[0].stats.starttime + st[0].stats.sac.a - 5
    tend = tstart + 50
    tr = st[0].trim(tstart, tend, pad=True, fill_value=0)
    st[0].stats.sac.nzyear = st[0].stats.starttime.year
    st[0].stats.sac.nzjday = st[0].stats.starttime.julday
    st[0].stats.sac.nzhour = st[0].stats.starttime.hour
    st[0].stats.sac.nzmin = st[0].stats.starttime.minute
    st[0].stats.sac.nzsec = st[0].stats.starttime.second
    st[0].stats.sac.nzmsec = st[0].stats.starttime.microsecond
    st[0].stats.sac.t0 = st[0].stats.sac.t0 - st[0].stats.sac.a + 5
    st[0].stats.sac.a = 5
    tr = tr.filter('bandpass',
                   freqmin=0.2,
                   freqmax=10,
                   corners=4,
                   zerophase=True)
    tr = [a**2 for a in tr]
    tr = np.asarray(smooth(tr, 20))
    tr = Trace(tr, st[0].stats)
    os.chdir(path_env)
    tr.write('env_' + station, format='SAC')
def make_station_figure_eew_stationreport(st1, st2, st3, st4, st5, label1,
                                          label2, label3, label4, label5,
                                          thresh1, thresh2, thresh3, thresh4,
                                          thresh5, RMSwinlen):

    net = st1[0].stats.network
    stat = st1[0].stats.station
    loc = st1[0].stats.location
    chan = st1[0].stats.channel

    fig = plt.figure(figsize=(8, 8), dpi=180)

    gs1 = gridspec.GridSpec(1, 1)
    gs1.update(left=0.15, right=0.92, bottom=0.81, top=0.94, wspace=0.01)
    ax1 = plt.subplot(gs1[:, :])
    gs2 = gridspec.GridSpec(1, 1)
    gs2.update(left=0.15, right=0.92, bottom=0.62, top=0.78, wspace=0.01)
    ax2 = plt.subplot(gs2[:, :])
    gs3 = gridspec.GridSpec(1, 1)
    gs3.update(left=0.15, right=0.92, bottom=0.43, top=0.59, wspace=0.01)
    ax3 = plt.subplot(gs3[:, :])
    gs4 = gridspec.GridSpec(1, 1)
    gs4.update(left=0.15, right=0.92, bottom=0.24, top=0.40, wspace=0.01)
    ax4 = plt.subplot(gs4[:, :])
    gs5 = gridspec.GridSpec(1, 1)
    gs5.update(left=0.15, right=0.92, bottom=0.08, top=0.21, wspace=0.01)
    ax5 = plt.subplot(gs5[:, :])

    tlast = st1[len(st1) - 1].stats.endtime
    timediffinsec = (tlast - st1[0].stats.starttime)
    tadd = timediffinsec * 0.01
    t1 = st1[0].stats.starttime - datetime.timedelta(seconds=tadd)
    t2 = tlast + datetime.timedelta(seconds=tadd)
    t = t1
    t1 = datetime.datetime(t.year, t.month, t.day, t.hour, t.minute, t.second,
                           t.microsecond)
    t = t2
    t2 = datetime.datetime(t.year, t.month, t.day, t.hour, t.minute, t.second,
                           t.microsecond)

    for ii in range(0, len(st1)):
        timearray = np.arange(st1[ii].stats.npts) * st1[ii].stats.delta
        t = st1[ii].stats.starttime
        x1 = np.array([
            datetime.datetime(t.year, t.month, t.day, t.hour, t.minute,
                              t.second, t.microsecond) +
            datetime.timedelta(seconds=jj) for jj in timearray
        ])
        ax1.plot(x1, st1[ii].data, color='k', linewidth=0.2)
        if (thresh1 > 0):
            ax1.plot([t1, t2], [thresh1, thresh1], color='r', linewidth=0.5)
            ax1.plot([t1, t2], [-1 * thresh1, -1 * thresh1],
                     color='r',
                     linewidth=0.5)
        ax1.xaxis.set_major_formatter(DateFormatter('%H:%M'))
        tlast = st1[ii].stats.endtime
    for ii in range(0, len(st2)):
        timearray = np.arange(st2[ii].stats.npts) * st2[ii].stats.delta
        t = st2[ii].stats.starttime
        x2 = np.array([
            datetime.datetime(t.year, t.month, t.day, t.hour, t.minute,
                              t.second, t.microsecond) +
            datetime.timedelta(seconds=jj) for jj in timearray
        ])
        ax2.plot(x2, st2[ii].data, color='k', linewidth=0.2)
        if (thresh2 > 0):
            ax2.plot([t1, t2], [thresh2, thresh2], color='r', linewidth=0.5)
            ax2.plot([t1, t2], [-1 * thresh2, -1 * thresh2],
                     color='r',
                     linewidth=0.5)
        ax2.xaxis.set_major_formatter(DateFormatter('%H:%M'))
    for ii in range(0, len(st3)):
        timearray = np.arange(st3[ii].stats.npts) * st3[ii].stats.delta
        t = st3[ii].stats.starttime
        x3 = np.array([
            datetime.datetime(t.year, t.month, t.day, t.hour, t.minute,
                              t.second, t.microsecond) +
            datetime.timedelta(seconds=jj) for jj in timearray
        ])
        iRMSwinlen = int(RMSwinlen / st3[ii].stats.delta)
        if (st3[ii].stats.npts > iRMSwinlen):
            rmsthing = np.sqrt(smooth(((st3[ii].data)**2), iRMSwinlen))
            ax3.plot(x3, st3[ii].data, color='k', linewidth=0.2)
            ax3.plot(x3, rmsthing, color='c', linewidth=1)
        if (thresh3 > 0):
            ax3.plot([t1, t2], [thresh3, thresh3], color='r', linewidth=0.5)
        ax3.xaxis.set_major_formatter(DateFormatter('%H:%M'))
    for ii in range(0, len(st4)):
        timearray = np.arange(st4[ii].stats.npts) * st4[ii].stats.delta
        t = st4[ii].stats.starttime
        x4 = np.array([
            datetime.datetime(t.year, t.month, t.day, t.hour, t.minute,
                              t.second, t.microsecond) +
            datetime.timedelta(seconds=jj) for jj in timearray
        ])
        ax4.plot(x4, st4[ii].data, color='k', linewidth=0.2)
        if (thresh4 > 0):
            ax4.plot([t1, t2], [thresh4, thresh4], color='r', linewidth=0.5)
            ax4.plot([t1, t2], [-1 * thresh4, -1 * thresh4],
                     color='r',
                     linewidth=0.5)
        ax4.xaxis.set_major_formatter(DateFormatter('%H:%M'))

    timearray = np.arange(len(st5)) * st1[0].stats.delta
    t = st1[ii].stats.starttime
    x5 = np.array([
        datetime.datetime(t.year, t.month, t.day, t.hour, t.minute, t.second,
                          t.microsecond) + datetime.timedelta(seconds=jj)
        for jj in timearray
    ])
    if (thresh5 > 0):
        ax5.plot([t1, t2], [thresh5, thresh5], color='r', linewidth=0.5)
    ax5.plot(x5, st5, color='k', linewidth=0.2)
    ax5.xaxis.set_major_formatter(DateFormatter('%H:%M'))
    ax5.set_ylim(-1, 29)
    ttextL = t1 - datetime.timedelta(seconds=timediffinsec * 0.18)
    ttextR = t1 + datetime.timedelta(seconds=timediffinsec * 1.025)
    ttextR2 = t1 + datetime.timedelta(seconds=timediffinsec * 1.055)
    ttitle = t1 + datetime.timedelta(seconds=timediffinsec * 0.15)
    titletext = str(ttitle.year) + '/' + str(ttitle.month) + '/' + str(
        ttitle.day
    ) + ' (UTC)         ' + net + '.' + stat + '.' + loc + '.' + chan
    ytitle = ax1.get_ylim()[0] + (ax1.get_ylim()[1] - ax1.get_ylim()[0]) * 1.04
    ax1.text(ttitle, ytitle, titletext)
    ax1.set_xlim([t1, t2])
    ax2.set_xlim([t1, t2])
    ax3.set_xlim([t1, t2])
    ax4.set_xlim([t1, t2])
    ax5.set_xlim([t1, t2])
    ax1.set_xticklabels([])
    ax2.set_xticklabels([])
    ax3.set_xticklabels([])
    ax4.set_xticklabels([])

    if (thresh1 > 0 and ax1.get_ylim()[1] < thresh1):
        ax1.set_ylim([-1.05 * thresh1, 1.05 * thresh1])
    if (thresh2 > 0 and ax2.get_ylim()[1] < thresh2):
        ax2.set_ylim([-1.05 * thresh2, 1.05 * thresh2])
    if (thresh3 > 0 and ax3.get_ylim()[1] < thresh3):
        ax3.set_ylim([-1.05 * thresh3, 1.05 * thresh3])
    if (thresh4 > 0 and ax4.get_ylim()[1] < thresh4):
        ax4.set_ylim([-1.05 * thresh4, 1.05 * thresh4])
    if (thresh5 > 0 and ax5.get_ylim()[1] < thresh5):
        ax5.set_ylim([-1.05 * thresh5, 1.05 * thresh5])

    ytext1 = ax1.get_ylim()[0] + (ax1.get_ylim()[1] - ax1.get_ylim()[0]) * 0.85
    ytext2 = ax2.get_ylim()[0] + (ax2.get_ylim()[1] - ax2.get_ylim()[0]) * 0.85
    ytext3 = ax3.get_ylim()[0] + (ax3.get_ylim()[1] - ax3.get_ylim()[0]) * 0.85
    ytext4 = ax4.get_ylim()[0] + (ax4.get_ylim()[1] - ax4.get_ylim()[0]) * 0.85
    ytext5 = ax5.get_ylim()[0] + (ax5.get_ylim()[1] - ax5.get_ylim()[0]) * 0.85
    ttextLsat = t1 - datetime.timedelta(seconds=timediffinsec * 0.05)

    if (len(label1) < 18):
        ax1.text(ttextR, ytext1, label1, color='k', rotation=270)
    else:
        ax1.text(ttextR2, ytext1, label1.split()[0], color='k', rotation=270)
        ax1.text(ttextR,
                 ytext1,
                 " ".join(label1.split()[1:]),
                 color='k',
                 rotation=270)
    if (len(label2) < 18):
        ax1.text(ttextR, ytext2, label2, color='k', rotation=270)
    else:
        ax2.text(ttextR2, ytext2, label2.split()[0], color='k', rotation=270)
        ax2.text(ttextR,
                 ytext2,
                 " ".join(label2.split()[1:]),
                 color='k',
                 rotation=270)
    if (len(label3) < 18):
        ax3.text(ttextR, ytext3, label3, color='k', rotation=270)
    else:
        ax3.text(ttextR2, ytext3, label3.split()[0], color='k', rotation=270)
        ax3.text(ttextR,
                 ytext3,
                 " ".join(label3.split()[1:]),
                 color='k',
                 rotation=270)
    if (len(label4) < 18):
        ax4.text(ttextR, ytext4, label4, color='k', rotation=270)
    else:
        ax4.text(ttextR2, ytext4, label4.split()[0], color='k', rotation=270)
        ax4.text(ttextR,
                 ytext4,
                 " ".join(label4.split()[1:]),
                 color='k',
                 rotation=270)
    if (len(label5) < 18):
        ax5.text(ttextR, ytext5, label5, color='k', rotation=270)
        ax5.text(ttextLsat, 28, ">30", color='k')
    else:
        ax5.text(ttextR2, ytext5, label5.split()[0], color='k', rotation=270)
        ax5.text(ttextR,
                 ytext5,
                 " ".join(label5.split()[1:]),
                 color='k',
                 rotation=270)
        ax5.text(ttextLsat, 28, ">30", color='k')

    locname = loc
    if (loc == "--"):
        locname = ""
    figname = 'WAVEFORMS.' + str(ttitle.year) + '.' + str(
        ttitle.month) + '.' + str(ttitle.day) + '.' + str(
            ttitle.hour
        ) + '.' + net + '.' + stat + '.' + locname + '.' + chan + '.png'
    plt.savefig(figname, dpi=180)
    plt.close("all")
ax_env_all.set_xlabel('time (s)')

cpt = 0

for fichier in list_file_used:
    os.chdir(path_data)
    st = read(fichier)
    st = st.detrend(type='constant')  #retirer la moyenne
    tr_brut = st[0]
    tr_filt = tr_brut.filter('bandpass',
                             freqmin=0.2,
                             freqmax=10,
                             corners=4,
                             zerophase=True)
    envelop = abs(hilbert(tr_filt))
    env_smoothed = smooth(envelop, 20)

    t = np.arange(tr_brut.stats.npts) / tr_brut.stats.sampling_rate

    os.chdir(path_env)

    fig_env, ax_env = plt.subplots(1, 1)
    ax_env.set_xlabel('time (s)')
    ax_env.plot(t, tr_brut, linewidth=0.2, color='black')
    ax_env.plot(t, env_smoothed, linewidth=1, color='red')
    fig_env.savefig('envelope_' + str(st[0].stats.station) + '.pdf')

    ax_env_all.plot(t, env_smoothed + cpt, linewidth=0.5)

    cpt = cpt + 2000
plt.grid()
if (flagSave==1):
    fig.savefig('cumul.png')
plt.show()

fig=plt.figure()
plt.plot(tempo[:-1],enend)
ax=plt.gca()
plt.xlabel("time [s]")
plt.ylabel("first derivative of cumulative")
plt.grid()
if (flagSave==1):
    plt.savefig("derivCumuOrig.png")
plt.show()

pr=smooth(enend,100)
plt.plot(pr[5000:10000])
plt.show()

yhat = savitzky_golay(pr, 801, 3)
plt.plot(yhat[5000:15000])
plt.show()



# CREATE MAXIMA AND MINIMA:


maxima_num=0
minima_num=0
max_locations=[]
            f"{ct+1}/{len(pred_list)}: {idx[k].numpy().decode('utf-8')}")
        trc_id_decode = idx[k].numpy().decode('utf-8').split('.')
        evid = trc_id_decode[0]
        chn = trc_id_decode[1]
        sta_info = '.'.join(trc_id_decode[2:])

        # predictions information
        pred_pick_T = pred_pick[k].T
        predict_P = pred_pick_T[0]
        predict_S = pred_pick_T[1]
        predict_nz = pred_pick_T[2]

        pred_mask_T = pred_mask[k].T
        pred_eq_mask = pred_mask_T[0]
        pred_nz_mask = pred_mask_T[1]
        trigger_mask = trigger_onset(smooth(pred_eq_mask, 10), 0.3, 0.3)

        # labeled P&S arrival time
        label_info = label[k].numpy()
        try:
            labeled_P = np.where(label_info.T[0] == 1)[0][0] * dt
            labeled_S = np.where(label_info.T[1] == 1)[0][0] * dt
            raw_tp_ts_diff = labeled_S - labeled_P
            p_peak, p_value = pick_peaks(predict_P,
                                         labeled_P,
                                         dt,
                                         search_win=1)
            s_peak, s_value = pick_peaks(predict_S,
                                         labeled_S,
                                         dt,
                                         search_win=1)
Exemple #21
0
ax_env_norm[1].set_ylabel('Normalized squared amplitude')
ax_env_norm[0].ticklabel_format(style = 'sci', axis = 'y', scilimits = (0, 0))
ax_env_norm[1].ticklabel_format(style = 'sci', axis = 'y', scilimits = (0, 0))
ax_env_norm[2].ticklabel_format(style = 'sci', axis = 'y', scilimits = (0, 0))

os.chdir(path_data)
for station in list_sta:
    st = read(station)
    st.detrend(type = 'constant')
    tstart = st[0].stats.starttime + st[0].stats.sac.t0 - 15
    tend = tstart + 50
    st[0].trim(tstart, tend, pad=True, fill_value=0)
    tr_brut = st[0]
    tr_filt = tr_brut.filter('bandpass', freqmin=0.2, freqmax=10, corners=4, zerophase=True)
    squared_tr = [a**2 for a in tr_filt]
    env_smoothed = norm1(smooth(squared_tr, 20))

    t = np.arange(tr_brut.stats.npts)/tr_brut.stats.sampling_rate
    #traces brute, filtree, au carre, smoothee
    ista = list_sta.index(station)
    ax_brute[ista].plot(t, tr_brut)#, aspect = 50)#, aspect = 50/(abs(1.1*tr_brut.max()) + abs(1.1*tr_brut.max())))
    ax_filtree[ista].plot(t, tr_filt)#, aspect = 50)#, aspect = 50/(abs(1.1*tr_filt.max()) + abs(1.1*tr_filt.max())))
    ax_filt_sqr[ista].plot(t, squared_tr)#, aspect = 50)#, aspect = 50/(abs(1.1*squared_tr.max()) + abs(1.1*squared_tr.max())))
    ax_env_norm[ista].plot(t, env_smoothed)#, aspect = 50)#, aspect = 50/(abs(1.1*env_smoothed.max()) + abs(1.1*env_smoothed.max())))

    if st[0].stats.channel == 'EW':
        ax_brute[ista].text(45, abs(tr_brut.max())/2, 'EW')
        ax_filtree[ista].text(45, abs(tr_filt.max())/2, 'EW')
        ax_filt_sqr[ista].text(45, max(squared_tr)/2, 'EW')
        ax_env_norm[ista].text(45, max(env_smoothed)/2, 'EW')
    elif st[0].stats.channel == 'NS':
Exemple #22
0
def spectrum_gen(ts_in,
                 pick,
                 args,
                 mt_tb=4,
                 debug=0,
                 return_timeseries=False,
                 usedecon=False,
                 ts_in2=None,
                 pick2=None,
                 npick=None,
                 npick2=None,
                 npickp=None,
                 npickp2=None):
    """
	returns the spectrum of a timeseries
	INPUT
	ts_in timeseries as an obspy trace
	pick pick as time
	station string
	args see 
	"""
    from mtspec import mtspec, mt_deconvolve
    timeseries = ts_in.copy()
    if usedecon:
        timeseries2 = ts_in2.copy()
    #arguments
    #fftype=args.ft
    winlength = args.W
    shift = args.S
    stype = args.P
    nwins = args.N
    snrtype = args.snrtype
    nlogbins = args.lb
    smoothfactor = 3
    flims = [-2, 1.2]
    specs = []
    ffreq = []
    if usedecon:
        msnrs = []
        esnrs = []
        mspecs = []
        especs = []
        decons = []
        esnrps = []
        msnrps = []
        noisewin = timeseries.copy()
        noisewin.trim(npick, npick + winlength)
        noisewin2 = timeseries2.copy()
        noisewin2.trim(npick2, npick2 + winlength)
        noisewinpcoda = timeseries.copy()
        noisewinpcoda.trim(npickp, npickp + winlength)
        noisewinpcoda2 = timeseries2.copy()
        noisewinpcoda2.trim(npickp2, npickp2 + winlength)
    lenwin = 0
    for i in range(1, nwins + 1):
        clipwin = timeseries.copy()
        clipstart = pick + (i - 1) * shift
        clipend = clipstart + winlength
        if clipwin.stats.endtime - clipend < 0:
            if debug > 1:
                print('at the end of the data')
            continue
        if clipstart - clipwin.stats.starttime < 0:
            if debug > 1:
                print('starting before the data')
            continue
        clipwin.trim(clipstart, clipend)
        lenwin = len(clipwin.data)
        if lenwin <= 256:
            nopts = 256
        elif lenwin <= 512:
            nopts = 512
        elif lenwin < 1024:
            nopts = 1024
        else:
            nopts = 2048

        if not usedecon:
            spec, freq, jackknife, _, _ = mtspec(data=clipwin.data,
                                                 delta=clipwin.stats.delta,
                                                 time_bandwidth=mt_tb,
                                                 nfft=nopts,
                                                 statistics=True)
            specs.append(np.sqrt(spec))
            ffreq = freq
        else:
            clipwin2 = timeseries2.copy()
            clipstart2 = pick2 + (i - 1) * shift
            clipend2 = clipstart2 + winlength
            if clipwin2.stats.endtime - clipend2 < 0:
                if debug > 1:
                    print('at the end of the data')
                continue
            if clipstart2 - clipwin2.stats.starttime < 0:
                if debug > 1:
                    print('starting before the data')
                continue
            clipwin2.trim(clipstart2, clipend2)
            freq, spec, spec1, spec2, decon = specrat_gen(
                clipwin, clipwin2, nopts, mt_tb)
            freqnL, msnr, _, _, denoiseL = specrat_gen(clipwin, noisewin,
                                                       nopts, mt_tb)
            freqnS, esnr, _, _, denoiseS = specrat_gen(clipwin2, noisewin2,
                                                       nopts, mt_tb)
            freqnpL, msnrp, _, _, denoisepL = specrat_gen(
                clipwin, noisewinpcoda, nopts, mt_tb)
            freqnpS, esnrp, _, _, denoisepS = specrat_gen(
                clipwin2, noisewinpcoda2, nopts, mt_tb)
            #			specs.append([spec,spec1,spec2,msnr,esnr,msnrp,esnrp])
            msnrs.append(msnr)
            esnrs.append(esnr)
            specs.append(spec)
            mspecs.append(spec1)
            especs.append(spec2)
            decons.append(decon)
            msnrps.append(msnrp)
            esnrps.append(esnrp)
            ffreq = freq
    specs = np.average(specs, axis=0)
    if usedecon:
        msnrs = np.average(msnrs, axis=0)
        esnrs = np.average(esnrs, axis=0)
        mspecs = np.average(mspecs, axis=0)
        especs = np.average(especs, axis=0)
        decons = np.average(decons, axis=0)
        msnrps = np.average(msnrps, axis=0)
        esnrps = np.average(esnrps, axis=0)
    #smooth the individual spectra before taking spectral ratio.
    if len(ffreq) == 0:
        print('the spectrum has length 0')
        return
    ffreq1, specs = logbin(ffreq, specs, nbins=nlogbins, flims=flims)
    if usedecon:
        ffreq1, msnrs = logbin(ffreq, msnrs, nbins=nlogbins, flims=flims)
        ffreq1, esnrs = logbin(ffreq, esnrs, nbins=nlogbins, flims=flims)
        ffreq1, mspecs = logbin(ffreq, mspecs, nbins=nlogbins, flims=flims)
        ffreq1, especs = logbin(ffreq, especs, nbins=nlogbins, flims=flims)
        ffreq1, msnrps = logbin(ffreq, msnrps, nbins=nlogbins, flims=flims)
        ffreq1, esnrps = logbin(ffreq, esnrps, nbins=nlogbins, flims=flims)
    if args.sm:
        specs = smooth(specs, smoothfactor)
    if usedecon:
        msnrs = smooth(msnrs, smoothfactor)
        esnrs = smooth(esnrs, smoothfactor)
        mspecs = smooth(mspecs, smoothfactor)
        especs = smooth(especs, smoothfactor)
        msnrps = smooth(msnrps, smoothfactor)
        esnrps = smooth(esnrps, smoothfactor)
        return ffreq1, specs, mspecs, especs, decons, msnrs, esnrs, msnrps, esnrps
    else:
        return ffreq1, specs
Exemple #23
0
            #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
            df=1/(n*dt)
            freq=np.linspace(0,(n+1)/2,(n+1)/2)*df
            specN=np.fft.rfft(trN.data)
            specE=np.fft.rfft(trE.data)
            
            Hspec=np.sqrt((specN**2+specE**2)/2)
            
            smooth_Hspec=smooth(Hspec,smth)
<<<<<<< HEAD
            '''
=======
<<<<<<< HEAD
            
=======
            '''
>>>>>>> d2ecf1f1dcdc0faedb0ee9378140a19249a90d73
>>>>>>> casa
            #Graficando log-espectro
            plt.plot(np.log10(freq),np.log10(abs(smooth_Hspec)),'k')
            plt.title('Espectro de desplazamiento onda S '+trN.stats.station)
            plt.xlim(0,2)
            plt.ylabel('log(A)')
            plt.xlabel('log(frecuencia [Hz])')
Exemple #24
0
    for fichier in list_fichier:
        st = read(fichier)
        st = st.detrend(type='constant')
        tstart = st[0].stats.starttime + st[0].stats.sac.t0 - 15
        tend = tstart + 50
        st[0].trim(tstart, tend, pad=True, fill_value=0)
        tr_brut = st[0]
        tr_filt = tr_brut.filter('bandpass',
                                 freqmin=0.2,
                                 freqmax=10,
                                 corners=4,
                                 zerophase=True)
        #envelop = abs(hilbert(tr_filt))
        #env_smoothed = smooth(envelop, 20)
        squared_tr = [a**2 for a in tr_filt]
        env_smoothed = smooth(squared_tr, 20)

        t = np.arange(tr_brut.stats.npts) / tr_brut.stats.sampling_rate

        ordo = dist(st[0].stats.sac.stla, st[0].stats.sac.stlo,
                    0.001 * st[0].stats.sac.stel, st[0].stats.sac.evla,
                    st[0].stats.sac.evlo, -st[0].stats.sac.evdp)

        ax.plot(t, norm(env_smoothed) + ordo, linewidth=0.2)
        ax.text(40, ordo, st[0].stats.station, fontsize=3)

        ax2.plot(t, norm(env_smoothed) + ordo, linewidth=0.2)
        ax2.text(40, ordo, st[0].stats.station, fontsize=3)

    os.chdir(path_results)
    ax2.axvline(15)