Example #1
0
def symmetrydemo():
    a=sin(linspace(-5*pi,5*pi,10000))
    b=a+2
    c=a-0.5
    ah,bh,ch=hilbert(a),hilbert(b),hilbert(c)
    ph_a,ph_b,ph_c=unwrap(angle(ah)),unwrap(angle(bh)),unwrap(angle(ch))
    omega_a=diff(ph_a)
    omega_b=diff(ph_b)
    omega_c=diff(ph_c)
    subplot(211),plot(ph_a),plot(ph_b),plot(ph_c)
    subplot(212),plot(omega_a),plot(omega_b),plot(omega_c)
    grid()
    show()
    return a,b,c
Example #2
0
def symmetrydemo():
    a = sin(linspace(-5 * pi, 5 * pi, 10000))
    b = a + 2
    c = a - 0.5
    ah, bh, ch = hilbert(a), hilbert(b), hilbert(c)
    ph_a, ph_b, ph_c = unwrap(angle(ah)), unwrap(angle(bh)), unwrap(angle(ch))
    omega_a = diff(ph_a)
    omega_b = diff(ph_b)
    omega_c = diff(ph_c)
    subplot(211), plot(ph_a), plot(ph_b), plot(ph_c)
    subplot(212), plot(omega_a), plot(omega_b), plot(omega_c)
    grid()
    show()
    return a, b, c
 def get_fft(self, fs, taps, Npts):
     Ts = 1.0 / fs
     fftpts = fftpack.fft(taps, Npts)
     self.freq = scipy.arange(0, fs, 1.0 / (Npts * Ts))
     self.fftdB = 20.0 * scipy.log10(abs(fftpts))
     self.fftDeg = scipy.unwrap(scipy.angle(fftpts))
     self.groupDelay = -scipy.diff(self.fftDeg)
Example #4
0
def ACphase(tf, unit='deg', unwrapTol=0.5):
    """
	Return the phase in desired *unit* of a transfer function *tf*
	
	* ``deg`` stands for degrees
	* ``rad`` stands for radians
	
	The phase is unwrapped (discontinuities are stiched together to make it 
	continuous). The tolerance of the unwrapping (in radians) is 
	*unwrapTol* times ``pi``. 
	"""
    # Get argument
    ph = angle(tf)

    # Unwrap if requested
    if (unwrapTol > 0) and (unwrapTol < 1):
        ph = unwrap(ph, unwrapTol * pi)

    # Convert to requested unit
    if unit == 'deg':
        return ph / pi * 180.0
    elif unit == 'rad':
        return ph
    else:
        raise Exception, "Bad phase unit."
Example #5
0
 def get_fft(self, fs, taps, Npts):
     Ts = 1.0/fs
     fftpts = fftpack.fft(taps, Npts)
     self.freq = scipy.arange(0, fs, 1.0/(Npts*Ts))        
     self.fftdB = 20.0*scipy.log10(abs(fftpts))
     self.fftDeg = scipy.unwrap(scipy.angle(fftpts))
     self.groupDelay = -scipy.diff(self.fftDeg)
 def test_phasez_1(self):
     # Testcase for return radian form
     fil = FIRDesign.fir1(self.order, self.cut)
     w, h = signal.freqz(fil[0], fil[1], worN=512, fs=2 * np.pi)
     phase = sp.unwrap(sp.angle(h))
     ww, pp = FilterSpec.phasez(fil)
     self.assertTrue(np.all(w == ww) and np.all(pp == phase))
Example #7
0
def HilbertSpectrum(IMF, Fs, NF=100):
    # to get the Hilbert Energy Spectrum

    # Hilbert Transform
    out = analyticSignal(IMF, axis=0)
    amp = out['amplitude']
    amp = amp**2
    phase = unwrap(out['phase'], axis=0)
    omega = (Fs * np.diff(phase, axis=0)) / (2 * np.pi)

    # frequencies
    W = np.linspace(0, Fs / 2, NF)

    # times
    NT = omega.shape[0]
    T = np.linspace(0, (NT - 1) / Fs, NT)

    # organize into matrix
    matrix = np.zeros([NF, NT], dtype=float)
    for i in range(IMF.shape[1]):
        for t in range(NT):
            k = 1
            while (k < NF) & (omega[t, i] > W[k]):
                k = k + 1

            if k < NF:
                matrix[k, t] = matrix[k, t] + amp[t, i]

    return T, W, matrix
Example #8
0
def ACphase(tf, unit='deg', unwrapTol=0.5):
	"""
	Return the phase in desired *unit* of a transfer function *tf*
	
	* ``deg`` stands for degrees
	* ``rad`` stands for radians
	
	The phase is unwrapped (discontinuities are stiched together to make it 
	continuous). The tolerance of the unwrapping (in radians) is 
	*unwrapTol* times ``pi``. 
	"""
	# Get argument
	ph=angle(tf)
	
	# Unwrap if requested
	if (unwrapTol>0) and (unwrapTol<1):
		ph=unwrap(ph, unwrapTol*pi)
	
	# Convert to requested unit
	if unit=='deg':
		return ph/pi*180.0
	elif unit=='rad':
		return ph
	else:
		raise Exception, "Bad phase unit."
Example #9
0
def getinstfreq(imfs):
    omega = zeros((imfs.shape[0], imfs.shape[1] - 1), dtype=float)
    for i in range(imfs.shape[0]):
        h = hilbert(imfs[i, :])
        theta = unwrap(angle(h))
        omega[i, :] = diff(theta)

    return omega
Example #10
0
def getinstfreq(imfs):
    omega=zeros((imfs.shape[0],imfs.shape[1]-1),dtype=float)
    for i in range(imfs.shape[0]):
        h=hilbert(imfs[i,:])
        theta=unwrap(angle(h))
        omega[i,:]=diff(theta)
        
    return omega
Example #11
0
def getinstfreq(imfs):
    # print 'freq:'
    omega = zeros((imfs.shape[0], imfs.shape[1]), dtype=float)
    for i in range(imfs.shape[0]):
        h = hilbert(imfs[i, :])
        theta = unwrap(angle(h))
        omega[i, 0:diff(theta).shape[0]] = diff(theta)
    # print 'freq:',np.shape(omega)
    return omega
Example #12
0
 def test_anaqpsk(self):
     """Test quaternary PSK signal."""
     signal, phases = ana.anaqpsk(512, 64, 0.25)
     self.assert_is_analytic(signal)
     # Count discontinuities in the signal and the phases and assert that
     # they appear in the same locations
     uphase = unwrap(angle(signal))
     dphase = np.diff(uphase)
     base_value = mode(dphase)[0][0]
     signal_phase_change = np.abs(dphase - base_value) > 0.0001
     ideal_phase_change = np.diff(phases) != 0
     np.testing.assert_allclose(signal_phase_change, ideal_phase_change)
Example #13
0
 def test_anaqpsk(self):
     """Test quaternary PSK signal."""
     signal, phases = ana.anaqpsk(512, 64, 0.25)
     self.assert_is_analytic(signal)
     # Count discontinuities in the signal and the phases and assert that
     # they appear in the same locations
     uphase = unwrap(angle(signal))
     dphase = np.diff(uphase)
     base_value = mode(dphase)[0][0]
     signal_phase_change = np.abs(dphase - base_value) > 0.0001
     ideal_phase_change = np.diff(phases) != 0
     np.testing.assert_allclose(signal_phase_change, ideal_phase_change)
Example #14
0
def phasez(system, worN: int = 512, fs=2 * np.pi, deg: bool = False) -> Tuple:
    """
    Phase response of a digital filter.
    
    Parameters
    ----------
        system : a tuple of array_like describing the system.
            The following gives the number of elements in the tuple and
            the interpretation:
                
                * (num, den)
                
        worN : {None, int, array_like}, optional
            If a single integer, then compute at that many frequencies 
            (default is N=512). This is a convenient alternative to:

                np.linspace(0, fs if whole else fs/2, N, endpoint=False)
            
            Using a number that is fast for FFT computations can result in 
            faster computations (see Notes).
            If an array_like, compute the response at the frequencies given. 
            These are in the same units as fs.
            
        fs : float, optional
            The sampling frequency of the digital system.
            Defaults to 2*pi radians/sample (so w is from 0 to pi).
            
        deg : bool, optional
            If True, the phase response is returned as degree.
            Default is False.
            
    Returns
    -------
        w : ndarray
            The frequencies at which h was computed, in the same units as fs.
            By default, w is normalized to the range [0, pi) (radians/sample).
            
        phase : ndarray
            The phase response.
    """

    # Calcurate the frequency response of the digital filter.
    w, h = freqz(system, worN=worN, fs=fs)

    # Calcurate the phase response from frequency response.
    phase = sp.unwrap(sp.angle(h))

    # If deg is True, return the phase response as degree
    if deg == True:
        phase = np.rad2deg(phase)

    return w, phase
Example #15
0
def frfplot(f, H):
    plt.subplot(211)
    plt.plot(f, 20 * sp.log10(sp.absolute(sp.sum(H, axis=1))), '-')
    plt.grid('on')
    plt.xlabel('Frequency (Hz)')
    plt.ylabel('FRF (dB)')
    axlim = plt.axis()
    plt.axis(
        axlim + sp.array([0, 0, -0.1 * (axlim[3] - axlim[2]), 0.1 * (axlim[3] - axlim[2])]))

    plt.subplot(212)
    plt.plot(f, sp.unwrap(sp.angle(sp.sum(H, axis=1))) / sp.pi * 180, '-')
    plt.grid('on')
    plt.xlabel('Frequency (Hz)')
    plt.ylabel('Phase (deg)')
    axlim = plt.axis()
    plt.axis(
        axlim + sp.array([0, 0, -0.1 * (axlim[3] - axlim[2]), 0.1 * (axlim[3] - axlim[2])]))
Example #16
0
 def plot_mode(self, mode1='power', mode2='wrap'):
     if mode1 == 'rms': 
         self.ymap1 = lambda x: numpy.sqrt(numpy.abs(x))
         self.ylabel1 = 'Power (RMS)'
     elif mode1=='raw':
         self.ymap1 = numpy.real
         self.ylabel1 = "Raw value"
     else: 
         self.ymap1 = numpy.abs
         self.ylabel1 = 'Power (r^2 + i^2)'
     if mode2 == 'unwrap':
         try:
             import scipy
             self.ymap2 = lambda x: scipy.unwrap(numpy.angle(x))
             self.ylabel2='Unwrapped Phase'
         except(ImportError): pass
     elif mode2=='raw':
         self.ymap2=numpy.imag
         self.ylabel2='Raw Value'
     else: 
         self.ymap2 = numpy.angle
         self.ylabel2='Wrapped Phase (rad/s)'
Example #17
0
def mfreqz(b, a=1, fs=22050.0):
    """Plot the frequency and phase response of an FIR filter.

    From http://mpastell.com/2010/01/18/fir-with-scipy/

    Parameters
    ----------
    b : float
        Forward terms of the FIR filter.
    a : float
        Feedback terms of the FIR filter. (Default value = 1)
    fs : float
        Sampling frequency of the filter. (Default value = 22050.0)

    Returns
    -------
    None

    """
    w, h = ss.freqz(b, a)
    h_db = 20 * np.log10(abs(h))
    plt.subplot(211)
    if fs:
        f = sp.linspace(0, fs / 2, len(w))
        plt.plot(f, h_db)
    else:
        plt.plot(w / max(w), h_db)
    plt.ylim(-150, 5)
    plt.ylabel('Magnitude (db)')
    plt.xlabel(r'Normalized Frequency (x$\pi$rad/sample)')
    plt.title(r'Frequency response')
    plt.subplot(212)
    h_phase = sp.unwrap(sp.arctan2(sp.imag(h), sp.real(h)))
    plt.plot(w / max(w), h_phase)
    plt.ylabel('Phase (radians)')
    plt.xlabel(r'Normalized Frequency (x$\pi$rad/sample)')
    plt.title(r'Phase response')
    plt.subplots_adjust(hspace=0.5)
Example #18
0
File: utils.py Project: Lx37/pambox
def mfreqz(b, a=1, fs=22050.0):
    """Plot the frequency and phase response of an FIR filter.

    From http://mpastell.com/2010/01/18/fir-with-scipy/

    Parameters
    ----------
    b : float
        Forward terms of the FIR filter.
    a : float
        Feedback terms of the FIR filter. (Default value = 1)
    fs : float
        Sampling frequency of the filter. (Default value = 22050.0)

    Returns
    -------
    None

    """
    w, h = ss.freqz(b, a)
    h_db = 20 * np.log10(abs(h))
    plt.subplot(211)
    if fs:
        f = sp.linspace(0, fs / 2, len(w))
        plt.plot(f, h_db)
    else:
        plt.plot(w / max(w), h_db)
    plt.ylim(-150, 5)
    plt.ylabel('Magnitude (db)')
    plt.xlabel(r'Normalized Frequency (x$\pi$rad/sample)')
    plt.title(r'Frequency response')
    plt.subplot(212)
    h_phase = sp.unwrap(sp.arctan2(sp.imag(h), sp.real(h)))
    plt.plot(w / max(w), h_phase)
    plt.ylabel('Phase (radians)')
    plt.xlabel(r'Normalized Frequency (x$\pi$rad/sample)')
    plt.title(r'Phase response')
    plt.subplots_adjust(hspace=0.5)
Example #19
0
 def plot_mode(self, mode1='power', mode2='wrap'):
     if mode1 == 'rms':
         self.ymap1 = lambda x: numpy.sqrt(numpy.abs(x))
         self.ylabel1 = 'Power (RMS)'
     elif mode1 == 'raw':
         self.ymap1 = numpy.real
         self.ylabel1 = "Raw value"
     else:
         self.ymap1 = numpy.abs
         self.ylabel1 = 'Power (r^2 + i^2)'
     if mode2 == 'unwrap':
         try:
             import scipy
             self.ymap2 = lambda x: scipy.unwrap(numpy.angle(x))
             self.ylabel2 = 'Unwrapped Phase'
         except (ImportError):
             pass
     elif mode2 == 'raw':
         self.ymap2 = numpy.imag
         self.ylabel2 = 'Raw Value'
     else:
         self.ymap2 = numpy.angle
         self.ylabel2 = 'Wrapped Phase (rad/s)'
Example #20
0
def euler_beam_frf(xin=0.22,
                   xout=0.32,
                   fmin=0.0,
                   fmax=1000.0,
                   zeta=0.02,
                   bctype=2,
                   npoints=2001,
                   beamparams=np.array([
                       7.31e10, 1 / 12 * 0.03 * .015**3, 2747.0, .015 * 0.03,
                       0.4
                   ])):
    """Frequency response function fo Euler-Bernoulli beam.

    Parameters
    ----------
    xin: float
        location of applied force
    xout: float
        location of displacement sensor
    fmin: float
        lowest frequency of interest
    fmax: float
        highest frequency of interest
    zeta: float
        damping ratio
    bctype: int
        bctype = 1 free-free
        bctype = 2 clamped-free
        bctype = 3 clamped-pinned
        bctype = 4 clamped-sliding
        bctype = 5 clamped-clamped
        bctype = 6 pinned-pinned
    beamparams: numpy array
        E, I, rho, A, L,
        Young's modulus, second moment of area, density, cross section area,
        length of beam
    npoints: int
        number of points for returned mode shape array

    Returns
    -------
    fout: numpy array
        array of driving frequencies (Hz)
    H: numpy array
        Frequency Response Function

    Examples
    --------
    >>> import matplotlib.pyplot as plt
    >>> import vibration_toolbox as vtb
    >>> _, _ = vtb.euler_beam_frf()

    """

    E = beamparams[0]
    I = beamparams[1]
    rho = beamparams[2]
    A = beamparams[3]
    L = beamparams[4]
    npoints = 2001
    i = 0
    w = sp.linspace(fmin, fmax, 2001) * 2 * sp.pi
    if min([xin, xout]) < 0 or max([xin, xout]) > L:
        print('One or both locations are not on the beam')
        return
    wn = sp.array((0, 0))
    # The number 100 is arbitrarily large and unjustified.
    a = sp.empty([npoints, 100], dtype=complex)
    f = sp.empty(100)

    while wn[-1] < 1.3 * (fmax * 2 * sp.pi):
        i = i + 1
        wn, xx, U = euler_beam_modes(n=i,
                                     bctype=bctype,
                                     beamparams=beamparams,
                                     npoints=5000)
        spl = UnivariateSpline(xx, U[:, i - 1])
        Uin = spl(xin)
        Uout = spl(xout)
        a[:, i - 1] = rho * A * Uin * Uout / \
            (wn[-1] ** 2 - w ** 2 + 2 * zeta * wn[-1] * w * sp.sqrt(-1))
        f[i] = wn[-1] / 2 / sp.pi
    a = a[:, 0:i]
    plt.figure()
    plt.subplot(211)
    plt.plot(w / 2 / sp.pi, 20 * sp.log10(sp.absolute(sp.sum(a, axis=1))), '-')
    # plt.hold('on')
    plt.plot(w / 2 / sp.pi, 20 * sp.log10(sp.absolute(a)), '-')
    plt.grid('on')
    plt.xlabel('Frequency (Hz)')
    plt.ylabel('FRF (dB)')
    axlim = plt.axis()

    plt.axis(axlim + sp.array(
        [0, 0, -0.1 * (axlim[3] - axlim[2]), 0.1 * (axlim[3] - axlim[2])]))

    plt.subplot(212)
    plt.plot(w / 2 / sp.pi,
             sp.unwrap(sp.angle(sp.sum(a, axis=1))) / sp.pi * 180, '-')
    plt.plot(w / 2 / sp.pi, sp.unwrap(sp.angle(a)) / sp.pi * 180, '-')
    plt.grid('on')
    plt.xlabel('Frequency (Hz)')
    plt.ylabel('Phase (deg)')
    axlim = plt.axis()
    plt.axis(axlim + sp.array(
        [0, 0, -0.1 * (axlim[3] - axlim[2]), 0.1 * (axlim[3] - axlim[2])]))
    plt.show()

    fout = w / 2 / sp.pi
    H = a
    return fout, H
Example #21
0
def calc_TEC(maindir,
             window=4096,
             incoh_int=100,
             sfactor=4,
             offset=0.,
             timewin=[0, 0],
             snrmin=0.):
    """
    Estimation of phase curve using coherent and incoherent integration.

    Args:
        maindir (:obj:`str`): Path for data.
        window (:obj:'int'): Window length in samples.
        incoh_int (:obj:'int'): Number of incoherent integrations.
        sfactor (:obj:'int'): Overlap factor.
        offset (:obj:'int'): Overlap factor.
        timewin ((:obj:'list'): Overlap factor.)
    Returns:
         outdict (dict[str, obj]): Output data dictionary::

             {
                        "rTEC": Relative TEC in TECU,
                        "rTEC_sig":Relative TEC STD in TECU,
                        "S4": The S4 parameter,
                        "snr0":snr0,
                        "snr1":snr1,
                        "time": Time for each measurement in posix format,
             }
    """

    e = ephem_doponly(maindir, offset)
    resid = calc_resid(maindir, e)
    Nr = int((incoh_int + sfactor - 1) * (window / sfactor))

    drfObj, chandict, start_indx, end_indx = open_file(maindir)

    chans = list(chandict.keys())
    sps = chandict[chans[0]]['sps']
    start_indx = start_indx + timewin[0] * sps
    end_indx = end_indx - timewin[1] * sps
    freq_ratio = chandict[chans[1]]['fo'] / chandict[chans[0]]['fo']
    om0, om1 = 2. * s_const.pi * sp.array(
        [chandict[chans[0]]['fo'], chandict[chans[1]]['fo']])
    start_vec = sp.arange(start_indx, end_indx - Nr, Nr, dtype=float)
    tvec = start_vec / sps

    soff = window / sfactor
    toff = soff / sps
    idx = sp.arange(window)
    n_t1 = sp.arange(0, incoh_int) * soff
    IDX, N_t1 = sp.meshgrid(idx, n_t1)
    Msamp = IDX + N_t1
    ls_samp = float(Msamp.flatten()[-1])

    wfun = sig.get_window('hann', window)
    wmat = sp.tile(wfun[sp.newaxis, :], (incoh_int, 1))

    phase_00 = sp.exp(1.0j * 0.0)
    phase_10 = sp.exp(1.0j * 0.0)

    phase0 = sp.zeros(len(start_vec), dtype=sp.complex64)
    phase1 = sp.zeros(len(start_vec), dtype=sp.complex64)

    phase_cs0 = sp.zeros(len(start_vec), dtype=float)
    phase_cs1 = sp.zeros(len(start_vec), dtype=float)
    snr0 = sp.zeros(len(start_vec))
    snr1 = sp.zeros(len(start_vec))

    std0 = sp.zeros(len(start_vec))
    std1 = sp.zeros(len(start_vec))
    fi = window // 2
    subchan = 0
    outspec0 = sp.zeros((len(tvec), window))
    outspec1 = sp.zeros((len(tvec), window))
    print("Start Beacon Processing")
    for i_t, c_st in enumerate(start_vec):

        update_progress(float(i_t) / float(len(start_vec)))
        t_cur = tvec[i_t]

        z00 = drfObj.read_vector(c_st, Nr, chans[0], subchan)[Msamp]
        z01 = drfObj.read_vector(c_st + soff, Nr, chans[0], subchan)[Msamp]
        z10 = drfObj.read_vector(c_st, Nr, chans[1], subchan)[Msamp]
        z11 = drfObj.read_vector(c_st + soff, Nr, chans[1], subchan)[Msamp]

        tphase = sp.float64(t_cur + toff)
        doppler0 = -1.0 * (150.0 / 400.0) * resid["doppler_residual"](
            t_cur) - e["dop1"](tphase)
        doppler1 = -1.0 * resid["doppler_residual"](t_cur) - e["dop2"](tphase)

        osc00 = phase_00 * wmat * sp.exp(1.0j * 2.0 * sp.pi * doppler0 *
                                         (Msamp / sps))
        osc01 = phase_00 * wmat * sp.exp(1.0j * 2.0 * sp.pi * doppler0 *
                                         (Msamp / sps + float(soff) / sps))
        osc10 = phase_10 * wmat * sp.exp(1.0j * 2.0 * sp.pi * doppler1 *
                                         (Msamp / sps))
        osc11 = phase_10 * wmat * sp.exp(1.0j * 2.0 * sp.pi * doppler1 *
                                         (Msamp / sps + float(soff) / sps))

        f00 = scfft.fftshift(scfft.fft(z00 * osc00.astype(z00.dtype), axis=-1),
                             axes=-1)
        f01 = scfft.fftshift(scfft.fft(z01 * osc01.astype(z01.dtype), axis=-1),
                             axes=-1)
        f00spec = sp.power(f00.real, 2).sum(0) + sp.power(f00.imag, 2).sum(0)
        outspec0[i_t] = f00spec.real
        f00_cor = f00[:, fi] * sp.conj(f01[:, fi])
        # Use prod to average the phases together.
        phase0[i_t] = sp.cumprod(sp.power(f00_cor, 1. / float(incoh_int)))[-1]
        phase_cs0[i_t] = sp.cumsum(sp.diff(sp.unwrap(sp.angle(f00[:,
                                                                  fi]))))[-1]

        f10 = scfft.fftshift(scfft.fft(z10 * osc10.astype(z10.dtype), axis=-1),
                             axes=-1)
        f11 = scfft.fftshift(scfft.fft(z11 * osc11.astype(z11.dtype), axis=-1),
                             axes=-1)
        f10spec = sp.power(f10.real, 2).sum(0) + sp.power(f10.imag, 2).sum(0)

        f10_cor = f10[:, fi] * sp.conj(f11[:, fi])
        outspec1[i_t] = f10spec.real
        phase1[i_t] = sp.cumprod(sp.power(f10_cor, 1. / float(incoh_int)))[-1]
        phase_cs1[i_t] = sp.cumsum(sp.diff(sp.unwrap(sp.angle(f10[:,
                                                                  fi]))))[-1]

        std0[i_t] = sp.std(sp.angle(f00_cor))
        std1[i_t] = sp.std(sp.angle(f10_cor))
        snr0[i_t] = f00spec.real[fi] / sp.median(f00spec.real)
        snr1[i_t] = f10spec.real[fi] / sp.median(f10spec.real)

        # Phases for next time through the loop
        phase_00 = phase_00 * sp.exp(1.0j * 2.0 * sp.pi * doppler0 *
                                     ((ls_samp + 1.) / sps))

        phase_10 = phase_10 * sp.exp(1.0j * 2.0 * sp.pi * doppler1 *
                                     ((ls_samp + 1.) / sps))

    #
    phasecurve = sp.cumsum(sp.angle(phase0) * freq_ratio - sp.angle(phase1))
    phasecurve_amp = phase_cs0 * freq_ratio - phase_cs1
    stdcurve = sp.sqrt(
        sp.cumsum(float(sfactor) * incoh_int * (std0**2.0 + std1**2.0)))

    # SNR windowing, picking values with minimum snr
    snrwin = sp.logical_and(snr0 > snrmin, snr1 > snrmin)
    phasecurve = phasecurve[snrwin]
    phasecurve_amp = phasecurve_amp[snrwin]
    stdcurve = stdcurve[snrwin]
    snr0 = snr0[snrwin]
    snr1 = snr1[snrwin]
    tvec = tvec[snrwin]

    dt = sp.diff(tvec).mean()
    Nside = int(1. / dt / 2.)
    lvec = sp.arange(-Nside, Nside)
    Lmat, Tmat = sp.meshgrid(lvec, sp.arange(len(tvec)))
    Sampmat = Lmat + Tmat
    Sampclip = sp.clip(Sampmat, 0, len(tvec) - 1)
    eps = s_const.e**2 / (8. * s_const.pi**2 * s_const.m_e * s_const.epsilon_0)
    aconst = s_const.e**2 / (2 * s_const.m_e * s_const.epsilon_0 * s_const.c)
    na = 9.
    nb = 24.
    f0 = 16.668e6

    #cTEC = f0*((na*nb**2)/(na**2-nb**2))*s_const.c/(2.*s_const.pi*eps)
    cTEC = 1e-16 * sp.power(om1 / om0**2 - 1. / om1, -1) / aconst
    rTEC = cTEC * phasecurve
    rTEC = rTEC - rTEC.min()
    rTEC_amp = cTEC * phasecurve_amp
    rTEC_amp = rTEC_amp - rTEC_amp.min()
    rTEC_sig = cTEC * stdcurve
    S4 = sp.std(snr0[Sampclip], axis=-1) / sp.median(snr0, axis=-1)

    outdict = {
        'rTEC': rTEC,
        'rTEC_amp': rTEC_amp,
        'rTEC_sig': rTEC_sig,
        'S4': S4,
        'snr0': snr0,
        'snr1': snr1,
        'time': tvec,
        'resid': resid,
        'phase': phasecurve,
        'phase_amp': phasecurve_amp,
        'phasestd': stdcurve,
        'outspec0': outspec0,
        'outspec1': outspec1
    }
    return outdict
Example #22
0
boxcar, triang, blackman, hamming, hann, bartlett, flattop, parzen, bohman, blackmanharris, nuttall, barthann, kaiser (needs beta), gaussian (needs std), general_gaussian (needs power, width), slepian (needs width), chebwin (needs attenuation)
'''
#%% HPF
#f = ss.firwin(numtaps=N, cutoff=fc/(Fs/2.), window='blackman', pass_zero=False)

#%% BPF
#e = ss.firwin(numtaps=N, cutoff=scipy.array([fc/(Fs/2.), fc2/(Fs/2.)]), window='blackman', pass_zero=False)

#%% BEF
#h = ss.firwin(numtaps=N, cutoff=scipy.array([fc/(Fs/2.), fc2/(Fs/2.)]), window='blackman', pass_zero=True)

#%% 表示
f = scipy.array(range(0, N)) * Fs / scipy.double(N)
tf = scipy.fft(h)
mag = scipy.absolute(tf)
phase = scipy.unwrap(scipy.angle(tf)) * 180. / scipy.pi

f2 = scipy.array(range(0, N2)) * Fs / scipy.double(N2)
tf2 = scipy.fft(h2)
mag2 = scipy.absolute(tf2)
phase2 = scipy.unwrap(scipy.angle(tf2)) * 180. / scipy.pi

f3 = scipy.array(range(0, N3)) * Fs / scipy.double(N3)
tf3 = scipy.fft(h3)
mag3 = scipy.absolute(tf3)
phase3 = scipy.unwrap(scipy.angle(tf3)) * 180. / scipy.pi

figure(1)
pp.plot(h)
pp.plot(h2)
pp.plot(h3)
Example #23
0
#%% BPF
e = ss.firwin(numtaps=N, cutoff=scipy.array([fc/(Fs/2.), fc2/(Fs/2.)]), window='blackman', pass_zero=False)

#%% BEF
h = ss.firwin(numtaps=N, cutoff=scipy.array([fc/(Fs/2.), fc2/(Fs/2.)]), window='blackman', pass_zero=True)

#%% 表示
f = scipy.array(range(0, N)) * Fs / scipy.double(N)

plt.plot(f)
plt.show()

tf = scipy.fft(h)
mag = scipy.absolute(tf)
phase = scipy.unwrap(scipy.angle(tf)) * 180. / scipy.pi

figure(1)
subplot(3,1,1)
pp.plot(h)
grid('on', 'both')
subplot(3,1,2)
pp.semilogx(f, mag)
xlim([20, 20000])
ylim([0, 1.2])
grid('on', 'both')
subplot(3,1,3)
pp.plot(f, phase)
xlim([0, 20000])
grid('on', 'both')
Example #24
0
def euler_beam_frf(xin=0.22, xout=0.22, fmin=0.0, fmax=1000.0, zeta=0.02,
                   beamparams=sp.array((7.31e10, 1 / 12 * 0.03 * .015 ** 3, 2747, .015 * 0.03, 0.4)), bctype=2):
    print(fmin)
    E = beamparams[0]
    I = beamparams[1]
    rho = beamparams[2]
    A = beamparams[3]
    L = beamparams[4]
    np = 2001
    i = 0
    w = sp.linspace(fmin, fmax, 2001) * 2 * sp.pi
    if min([xin, xout]) < 0 or max([xin, xout]) > L:
        disp_(char('One or both locations are not on the beam'))
        return
    wn = sp.array((0, 0))
    # The number 100 is arbitrarily large and unjustified.
    a = sp.empty([np, 100], dtype=complex)
    f = sp.empty(100)

    while wn[-1] < 1.3 * (fmax * 2 * sp.pi):
        i = i + 1
        # legtext[i + 1]=[char('Contribution of mode '),num2str_(i)]
        wn, xx, U = euler_beam_modes(i, bctype, beamparams, 5000)
        spl = UnivariateSpline(xx, U[:, i - 1])
        Uin = spl(xin)
        Uout = spl(xout)
        # Uin=spline_(xx,U,xin)
        # Uout=spline_(xx,U,xout)

        # print(wn[-1])
        # print(w)
        a[:, i - 1] = rho * A * Uin * Uout / \
            (wn[-1] ** 2 - w ** 2 + 2 * zeta * wn[-1] * w * sp.sqrt(-1))
        # print(a[0:10,i])
        # plt.plot(sp.log10(sp.absolute(a[:,i])))
        # input("Press Enter to continue...")
        f[i] = wn[-1] / 2 / sp.pi
    a = a[:, 0:i]
    plt.subplot(211)
    plt.plot(w / 2 / sp.pi, 20 * sp.log10(sp.absolute(sp.sum(a, axis=1))), '-')
    plt.hold('on')
    plt.plot(w / 2 / sp.pi, 20 * sp.log10(sp.absolute(a)), '-')
    plt.grid('on')
    plt.xlabel('Frequency (Hz)')
    plt.ylabel('FRF (dB)')
    axlim = plt.axis()

    plt.axis(
        axlim + sp.array([0, 0, -0.1 * (axlim[3] - axlim[2]), 0.1 * (axlim[3] - axlim[2])]))

    plt.subplot(212)
    plt.plot(w / 2 / sp.pi, sp.unwrap(sp.angle(sp.sum(a, axis=1))) /
             sp.pi * 180, '-')
    plt.hold('on')
    plt.plot(w / 2 / sp.pi, sp.unwrap(sp.angle(a)) / sp.pi * 180, '-')
    plt.grid('on')
    plt.xlabel('Frequency (Hz)')
    plt.ylabel('Phase (deg)')
    axlim = plt.axis()
    plt.axis(
        axlim + sp.array([0, 0, -0.1 * (axlim[3] - axlim[2]), 0.1 * (axlim[3] - axlim[2])]))

    fout = w / 2 / sp.pi
    H = a
    return fout, H
Example #25
0
from scipy import angle, unwrap
import numpy as np
import matplotlib.pyplot as plt

plt.grid(True)

x = np.linspace(0, 2 * np.pi, 1000)
s1 = np.sin(x)
s2 = np.sin(x) - 1
s3 = np.sin(x) + 2
# plt.plot(x, s1, 'b', x, s2, 'g', x, s3, 'r')

hs1 = hilbert(s1)
hs2 = hilbert(s2)
hs3 = hilbert(s3)
# plt.plot(np.real(hs1), np.imag(hs1), 'b')
# plt.plot(np.real(hs2), np.imag(hs2), 'g')
# plt.plot(np.real(hs3), np.imag(hs3), 'r')

omega_s1 = unwrap(angle(hs1))  # unwrapped instantaneous phase
omega_s2 = unwrap(angle(hs2))
omega_s3 = unwrap(angle(hs3))
f_inst_s1 = np.diff(omega_s1)  # instantaneous frequency
f_inst_s2 = np.diff(omega_s2)
f_inst_s3 = np.diff(omega_s3)
# plt.plot(x[1:], f_inst_s1, "b")
# plt.plot(x[1:], f_inst_s2, "g")
plt.plot(x[1:], f_inst_s3, "r")
plt.show()