Example #1
0
def cwt_conv(x, srange=[1, 10], steps=20, wavelet="morlet"):
    # set variables
    n_pnts = len(x)
    v_scales = np.zeros(steps)

    # scale increment - linear
    n_ds = (srange[1] - srange[0]) / float(steps - 1)

    if len(srange) < 2:
        return 1

    v_scales = np.arange(srange[0], srange[1],
                         (srange[1] - srange[0]) / float(steps - 1))
    v_scales.resize(len(v_scales) + 1)
    v_scales[-1] = v_scales[-2] + n_ds

    # create output matrix
    ar_out = np.array(np.zeros((steps, n_pnts)), dtype=complex)

    # create spectrum
    for i in range(steps):
        n_len = min(10 * v_scales[i], n_pnts)
        if wavelet == "morlet":
            mo = ssig.morlet(v_scales[i], w=6)
        else:
            mo = ssig.morlet(v_scales[i], w=6)
        ar_out[i, :] = ssig.convolve(x, mo, mode='same')
    #done

    return ar_out
def make_morlet_of_right_size(freq, dt, with_t=False, s=5.):
    """
    returns a ricker of size int(factor_freq*/(freq*dt))
    centered in the middle of the array (for use with convolve)

    Note factor_freq = 2 covers well the extent of the ricker
    """
    tstop = 2. * np.pi / freq
    t = np.arange(int(tstop / dt)) * dt
    # sigma = from_fourier_to_morlet(freq)
    w = len(t) * freq * dt / (2. * s)

    if with_t:
        return t - tstop / 2., np.real(signal.morlet(len(t), w, s=s))
    else:
        return np.real(signal.morlet(len(t), w, s=1.))
Example #3
0
def morlet_filter_bank(samplerate,
                       kernel_size,
                       scale,
                       scaling_factor,
                       normalize=True):
    """
    Create a bank of finite impulse response filters, with
    frequencies centered on the sub-bands of scale
    """
    basis_size = len(scale)
    basis = np.zeros((basis_size, kernel_size), dtype=np.complex128)

    try:
        if len(scaling_factor) != len(scale):
            raise ValueError('scaling factor must have same length as scale')
    except TypeError:
        scaling_factor = np.repeat(float(scaling_factor), len(scale))

    sr = int(samplerate)

    for i, band in enumerate(scale):
        scaling = scaling_factor[i]
        w = band.center_frequency / (scaling * 2 * sr / kernel_size)
        basis[i] = morlet(M=kernel_size, w=w, s=scaling)
    basis = basis.real

    if normalize:
        basis /= np.linalg.norm(basis, axis=-1, keepdims=True) + 1e-8

    basis = ArrayWithUnits(
        basis, [FrequencyDimension(scale),
                TimeDimension(*samplerate)])

    return basis
Example #4
0
def morlcwt(data, M, w, s, complete, widths):
    """
    Continuous wavelet transform.
    Adapted from scipy and modified by Junwoo and Mintaek to use morlet wavelet 
    Performs a continuous wavelet transform on `data`,
    using the `wavelet` function. A CWT performs a convolution
    with `data` using the `wavelet` function, which is characterized
    by a width parameter and length parameter.
    
    Parameters
    ----------
    data : (N,) ndarray
        data on which to perform the transform.
    M : int
        Length of morlet waveform
    w : float, optional
        Omega0
    s : float, optional
        scaling factor, windowed from -s*2*pi to +s*2*pi. Default is 1.
    Returns
    -------
    cwt: (M, N) ndarray
        Will have shape of (len(widths), len(data)).
    """

    output = np.zeros([len(widths), len(data)])
    for ind, width in enumerate(widths):
        wavelet_data = morlet(M, w=w, s=s, complete=complete)
        output[ind, :] = convolve(data, wavelet_data, mode='same')
    return output
def wvfilt(signal,mfreq,sr=1250.):

        # computing the length of the wavelet for the desired frequency
        wavelen = int(np.round(10.*sr/mfreq))

        # constructs morlet wavelet with given parameters
        wave = sig.morlet(wavelen,w=5,s=1,complete=True)

        # cutting borders
        cumulativeEnvelope = np.cumsum(np.abs(wave))/np.sum(np.abs(wave))
        Cut1 = next(i for (i,val) in enumerate(cumulativeEnvelope[::-1]) if val<=(1./2000)) 
        Cut2 = Cut1
        Cut1 = len(cumulativeEnvelope)-Cut1-1
        wave = wave[range(Cut1,Cut2)]

        # normalizes wavelet energy
        wave = wave/(.5*sum(abs(wave)))
        
        if (len(wave))>len(signal):
                print('ERROR: input signal needs at least '+str(len(wave))+\
                                                            ' time points for '+str(mfreq)+\
                                                                      'Hz-wavelet convolution')
                return None
                
        # convolving signal with wavelet
        fsignal = np.convolve(signal,wave,'same')
        return fsignal
Example #6
0
def morlet_wavelet(input_signal, dt=1, R=7, freq_interval=(), drawplot=1, eps=.0001, quick=False,COI = True):
    Ns = len(input_signal)
    try:
        minf = max(freq_interval[0], R / (Ns * dt))  # avoid wavelets with COI longer than the signal
    except:
        minf = R / (Ns * dt)
    try:
        maxf = min(freq_interval[1], .5 / dt)  # avoid wavelets above the Nyquist frequency
    except:
        maxf = .5 / dt
    try:
        Nf = freq_interval[2]
    except:
        Nf = int(np.ceil(np.log(maxf / minf) / np.log(1 / R + 1)))  # make spacing aproximately equal to sigma f
    
    alfa = (maxf / minf) ** (1 / Nf) - 1;  # According to the expression achived by fn = ((1+1/R)^n)*f0 where 1/R = alfa
    vf = ((1 + alfa) ** np.arange(0, Nf)) * minf;
    result = np.zeros((Nf, Ns), dtype='complex')

    # These for loops reaaally should be paralelied...
    if quick:
        for k in range(Nf):
            result[k, :] = exp_filter(input_signal, vf[k], dt, R)  # use the IIR filter exponetial wavelet instead of Morlet
    else:
        for k in range(Nf):
            N = int(2 * R / vf[k] / dt)  # Compute size of the wavelet
            wave = sg.morlet(N, w=R, s=1, complete=0) / N * np.pi * 2  # Normalize de amplitude returned by sg.morlet
            result[k, :] = sg.oaconvolve(input_signal, wave, mode='same')

    if drawplot:  # beautiful plots for matplotlib... too bad pyecog uses pyqtgraph! X'(
        plot_wavelet(result, dt, R, (minf,maxf,Nf), eps, COI)
    return result
 def test_draw_wavelet_morlet(self):
     w = 6
     s = 0.7
     points = int(100*w)
     w = sig.morlet(points, w, s)
     plt.plot(np.linspace(0., 1., points) * s, w, 'r-')
     plt.show()
Example #8
0
def morletf(x, f0, fs=1000, w=3, s=1, M=None, norm='sss'):
    """
    NOTE: This function is not currently ready to be interfaced with pacpy
    This is because the frequency input is not a range, which is a big
    assumption in how the api is currently designed

    Convolve a signal with a complex wavelet
    The real part is the filtered signal
    Taking np.abs() of output gives the analytic amplitude
    Taking np.angle() of output gives the analytic phase

    x : array
        Time series to filter
    f0 : float
        Center frequency of bandpass filter
    Fs : float
        Sampling rate
    w : float
        Length of the filter in terms of the number of 
        cycles of the oscillation with frequency f0
    s : float
        Scaling factor for the morlet wavelet
    M : integer
        Length of the filter. Overrides the f0 and w inputs
    norm : string
        Normalization method
        'sss' - divide by the sqrt of the sum of squares of points
        'amp' - divide by the sum of amplitudes divided by 2

    Returns
    -------
    x_trans : array
        Complex time series
    """

    if w <= 0:
        raise ValueError(
            'Number of cycles in a filter must be a positive number.')

    if M == None:
        M = 2 * s * w * fs / f0

    morlet_f = morlet(M, w=w, s=s)

    if norm == 'sss':
        morlet_f = morlet_f / np.sqrt(np.sum(np.abs(morlet_f)**2))
    elif norm == 'abs':
        morlet_f = morlet_f / np.sum(np.abs(morlet_f)) * 2
    else:
        raise ValueError('Not a valid wavelet normalization method.')

    x_filtR = np.convolve(x, np.real(morlet_f), mode='same')
    x_filtI = np.convolve(x, np.imag(morlet_f), mode='same')

    # Remove edge artifacts
    #x_filtR = _remove_edge(x_filtR, M/2.)
    #x_filtI = _remove_edge(x_filtI, M/2.)

    return x_filtR + 1j * x_filtI
Example #9
0
def morletf(x, f0, fs=1000, w=3, s=1, M=None, norm='sss'):
    """
    NOTE: This function is not currently ready to be interfaced with pacpy
    This is because the frequency input is not a range, which is a big
    assumption in how the api is currently designed

    Convolve a signal with a complex wavelet
    The real part is the filtered signal
    Taking np.abs() of output gives the analytic amplitude
    Taking np.angle() of output gives the analytic phase

    x : array
        Time series to filter
    f0 : float
        Center frequency of bandpass filter
    Fs : float
        Sampling rate
    w : float
        Length of the filter in terms of the number of 
        cycles of the oscillation with frequency f0
    s : float
        Scaling factor for the morlet wavelet
    M : integer
        Length of the filter. Overrides the f0 and w inputs
    norm : string
        Normalization method
        'sss' - divide by the sqrt of the sum of squares of points
        'amp' - divide by the sum of amplitudes divided by 2

    Returns
    -------
    x_trans : array
        Complex time series
    """

    if w <= 0:
        raise ValueError(
            'Number of cycles in a filter must be a positive number.')

    if M == None:
        M = 2 * s * w * fs / f0

    morlet_f = morlet(M, w=w, s=s)

    if norm == 'sss':
        morlet_f = morlet_f / np.sqrt(np.sum(np.abs(morlet_f)**2))
    elif norm == 'abs':
        morlet_f = morlet_f / np.sum(np.abs(morlet_f)) * 2
    else:
        raise ValueError('Not a valid wavelet normalization method.')

    x_filtR = np.convolve(x, np.real(morlet_f), mode='same')
    x_filtI = np.convolve(x, np.imag(morlet_f), mode='same')

    # Remove edge artifacts
    #x_filtR = _remove_edge(x_filtR, M/2.)
    #x_filtI = _remove_edge(x_filtI, M/2.)

    return x_filtR + 1j * x_filtI
Example #10
0
def morlet2(s=1, w=5, width=11, **kwargs):
    #  http://en.wikipedia.org/wiki/Morlet_wavelet
    z = np.zeros((width, width))
    m = signal.morlet(M=width*2, s=s, w=w , **kwargs)
    for i in range(width):
        for j in range(width):
            r       = ( (i-w//2)**2 + (j-w//2)**2 )**.5
            z[i,j]  = m[r]
    return z
Example #11
0
def morlet(x, freqs, sample_rate, w=3, s=1):
    M = 3 * s * w * sample_rate / freqs
    cwt = np.zeros((len(M), x.shape[0]), dtype=complex)
    for ii in range(len(M)):
        mlt = signal.morlet(M[ii], w=w, s=s)
        a = signal.convolve(x, mlt.real, mode='same', method='fft')
        b = signal.convolve(x, mlt.imag, mode='same', method='fft')
        cwt[ii, :] = a + 1j * b
    return cwt
def preprocess(current_batch):
    out_batch = np.ndarray(shape=(3,), dtype=np.int16)
    for i in range(len((sigma))):
        sigma_term = e**(-(sigma[i]**2)/2)
        morlet = signal.morlet(t[i], w=2*pi)
        C_psi = 2 * pi * signal.correlate(np.fft.fft(current_batch), np.conj(np.fft.fft(current_batch)), mode='full').sum()
        F_W = signal.fftconvolve(current_batch, morlet - sigma_term, mode='same')
        F_W = np.dot(F_W[100:900], F_W[100:900]).real / (C_psi.real + 1)
        out_batch[i] = (F_W * 100).astype(np.int16)
    return out_batch
Example #13
0
def morlet_wavelet(input_signal,
                   dt=1,
                   R=7,
                   freq_interval=(),
                   progress_signal=None,
                   kill_switch=None):
    if kill_switch is None:
        kill_switch = [False]
    print('morlet_wavelet called')
    Ns = len(input_signal)
    if len(freq_interval) > 0:
        minf = max(freq_interval[0], R /
                   (Ns * dt))  # avoid wavelets with COI longer than the signal
    else:
        minf = R / (Ns * dt)
    if len(freq_interval) > 1:
        maxf = min(freq_interval[1],
                   .5 / dt)  # avoid wavelets above the Nyquist frequency
    else:
        maxf = .5 / dt
    if len(freq_interval) > 2:
        Nf = freq_interval[2]
    else:
        Nf = int(np.ceil(
            np.log(maxf / minf) /
            np.log(1 / R + 1)))  # make spacing aproximately equal to sigma f

    alfa = (maxf / minf)**(
        1 / Nf
    ) - 1  # According to the expression achived by fn = ((1+1/R)^n)*f0 where 1/R = alfa
    vf = ((1 + alfa)**np.arange(0, Nf)) * minf
    print(Nf, Ns)
    result = np.zeros((Nf, Ns), dtype='complex')

    for k in range(Nf):
        if kill_switch[0]:
            break
        N = int(2 * R / vf[k] /
                dt)  # Compute size of the wavelet: 2 standard deviations
        wave = sg.morlet(
            N, w=R, s=1, complete=0
        ) / N * np.pi * 2  # Normalize de amplitude returned by sg.morlet
        # result[k, :] = sg.fftconvolve(input_signal, wave, mode='same')
        result[k, :] = sg.oaconvolve(input_signal, wave, mode='same')
        if progress_signal is not None:
            progress_signal.emit(int(100 * k / Nf))

    mask = np.zeros(result.shape)

    Nlist = (.5 * R / vf / dt).astype('int')  # 3 sigma COI
    for k in range(len(Nlist)):
        mask[k, :Nlist[k]] = np.nan
        mask[k, -Nlist[k]:] = np.nan

    return (result, mask, vf, kill_switch)
Example #14
0
    def __init__(self, port=None, baud=115200):
        print("connecting to OpenBCI...")
        self.board = OpenBCIBoard(port, baud)

        self.bg_thread = None
        self.bg_draw_thread = None
        self.data = np.array([0] * 8)
        self.should_plot = False
        self.control = np.array([0, 0, 0])
        self.control_f = np.array([0])
        self.out_sig = np.array([0])
        self.controls = np.array([[0] * 4])

        M = 100
        r = 250
        f1, f2 = 6, 10

        self.wavelet1 = signal.morlet(M, w=(f1 * M) / (2.0 * r))
        self.wavelet2 = signal.morlet(M, w=(f2 * M) / (2.0 * r))

        print("connecting to teensy...")
Example #15
0
def morlet_filter_bank(samplerate,
                       kernel_size,
                       scale,
                       scaling_factor,
                       normalize=True):
    """
    Create a :class:`~zounds.core.ArrayWithUnits` instance with a
    :class:`~zounds.timeseries.TimeDimension` and a
    :class:`~zounds.spectral.FrequencyDimension` representing a bank of morlet
    wavelets centered on the sub-bands of the scale.

    Args:
        samplerate (SampleRate): the samplerate of the input signal
        kernel_size (int): the length in samples of each filter
        scale (FrequencyScale): a scale whose center frequencies determine the
            fundamental frequency of each filer
        scaling_factor (int or list of int): Scaling factors for each band,
            which determine the time-frequency resolution tradeoff.
            The number(s) should fall between 0 and 1, with smaller numbers
            achieving better frequency resolution, and larget numbers better
            time resolution
        normalize (bool): When true, ensure that each filter in the bank
            has unit norm

    See Also:
        :class:`~zounds.spectral.FrequencyScale`
        :class:`~zounds.timeseries.SampleRate`
    """
    basis_size = len(scale)
    basis = np.zeros((basis_size, kernel_size), dtype=np.complex128)

    try:
        if len(scaling_factor) != len(scale):
            raise ValueError('scaling factor must have same length as scale')
    except TypeError:
        scaling_factor = np.repeat(float(scaling_factor), len(scale))

    sr = int(samplerate)

    for i, band in enumerate(scale):
        scaling = scaling_factor[i]
        w = band.center_frequency / (scaling * 2 * sr / kernel_size)
        basis[i] = morlet(M=kernel_size, w=w, s=scaling)
    basis = basis.real

    if normalize:
        basis /= np.linalg.norm(basis, axis=-1, keepdims=True) + 1e-8

    basis = ArrayWithUnits(
        basis, [FrequencyDimension(scale),
                TimeDimension(*samplerate)])

    return basis
    def __init__(self, sampling_rate=250, box_width=250, M=25, wavelets_freqs=(10, 22),
                 input_dim=None, dtype=None):
        super(EEGFeatures, self).__init__(input_dim=input_dim, dtype=dtype)

        self.sampling_rate = sampling_rate
        self.box_width = box_width
        self.M = M
        self.wavelets_freqs = wavelets_freqs

        self.wavelets = list()
        for f in wavelets_freqs:
            wavelet = signal.morlet(M, w=(f*M)/(2.0*sampling_rate))
            self.wavelets.append(wavelet)
    def __init__(self, port=None, baud=115200):
        print("connecting to OpenBCI...")
        self.board = OpenBCIBoard(port, baud)
        
        self.bg_thread = None
        self.bg_draw_thread = None
        self.data = np.array([0]*8)
        self.should_plot = False
        self.control = np.array([0,0,0])
        self.control_f = np.array([0])
        self.out_sig = np.array([0])
        self.controls = np.array([[0]*4])

        M = 100
        r = 250
        f1, f2 = 6, 10
        
        self.wavelet1 = signal.morlet(M, w=(f1*M)/(2.0*r))
        self.wavelet2 = signal.morlet(M, w=(f2*M)/(2.0*r))

        
        print("connecting to teensy...")
Example #18
0
def morletf(x, f0, fs=1000, w=7, s=1, M=None, norm='sss'):
    """
    Convolve a signal with a complex wavelet
    The real part is the filtered signal
    Taking np.abs() of output gives the analytic amplitude
    Taking np.angle() of output gives the analytic phase

    x : array
        Time series to filter
    f0 : float
        Center frequency of bandpass filter
    Fs : float
        Sampling rate
    w : float
        Length of the filter in terms of the number of cycles of the oscillation
        with frequency f0
    s : float
        Scaling factor for the morlet wavelet
    M : integer
        Length of the filter. Overrides the f0 and w inputs
    norm : string
        Normalization method
        'sss' - divide by the sqrt of the sum of squares of points
        'amp' - divide by the sum of amplitudes divided by 2

    Returns
    -------
    x_trans : array
        Complex time series
    """
    if w <= 0:
        raise ValueError(
            'Number of cycles in a filter must be a positive number.')

    if M == None:
        M = 2 * s * w * fs / f0

    morlet_f = morlet(M, w=w, s=s)
    morlet_f = morlet_f

    if norm == 'sss':
        morlet_f = morlet_f / np.sqrt(np.sum(np.abs(morlet_f)**2))
    elif norm == 'abs':
        morlet_f = morlet_f / np.sum(np.abs(morlet_f)) * 2
    else:
        raise ValueError('Not a valid wavelet normalization method.')

    mwt_real = np.convolve(x, np.real(morlet_f), mode='same')
    mwt_imag = np.convolve(x, np.imag(morlet_f), mode='same')

    return mwt_real + 1j * mwt_imag
Example #19
0
def morletf(x, f0, fs = 1000, w = 7, s = 1, M = None, norm = 'sss'):
    """
    Convolve a signal with a complex wavelet
    The real part is the filtered signal
    Taking np.abs() of output gives the analytic amplitude
    Taking np.angle() of output gives the analytic phase

    x : array
        Time series to filter
    f0 : float
        Center frequency of bandpass filter
    Fs : float
        Sampling rate
    w : float
        Length of the filter in terms of the number of cycles of the oscillation
        with frequency f0
    s : float
        Scaling factor for the morlet wavelet
    M : integer
        Length of the filter. Overrides the f0 and w inputs
    norm : string
        Normalization method
        'sss' - divide by the sqrt of the sum of squares of points
        'amp' - divide by the sum of amplitudes divided by 2

    Returns
    -------
    x_trans : array
        Complex time series
    """
    if w <= 0:
        raise ValueError('Number of cycles in a filter must be a positive number.')
        
    if M == None:
        M = 2 * s * w * fs / f0

    morlet_f = morlet(M, w = w, s = s)
    morlet_f = morlet_f
    
    if norm == 'sss':
        morlet_f = morlet_f / np.sqrt(np.sum(np.abs(morlet_f)**2))
    elif norm == 'abs':
        morlet_f = morlet_f / np.sum(np.abs(morlet_f))*2
    else:
        raise ValueError('Not a valid wavelet normalization method.')

    mwt_real = np.convolve(x, np.real(morlet_f), mode = 'same')
    mwt_imag = np.convolve(x, np.imag(morlet_f), mode = 'same')

    return mwt_real + 1j*mwt_imag
Example #20
0
def morletf(x, f0, Fs, w = 7, s = .5, M = None, norm = 'sss'):
    if w <= 0:
        raise ValueError('Number of cycles in a filter must be a positive number.')
    if M == None:
        M = w * Fs / f0
    morlet_f = scsig.morlet(M, w = w, s = s)
    morlet_f = morlet_f    
    if norm == 'sss':
        morlet_f = morlet_f / np.sqrt(np.sum(np.abs(morlet_f)**2))
    elif norm == 'abs':
        morlet_f = morlet_f / np.sum(np.abs(morlet_f))
    else:
        raise ValueError('Not a valid wavelet normalization method.')
    mwt_real = np.convolve(x, np.real(morlet_f), mode = 'same')
    mwt_imag = np.convolve(x, np.imag(morlet_f), mode = 'same')
    return mwt_real + 1j*mwt_imag
Example #21
0
def morletcwtoriginal(data, scales, omega, samplerate=1):
    n = len(data)
    cwtout = np.zeros([len(scales), n])
    freqs = np.zeros(len(scales))

    for ind, width in enumerate(scales):
        normalization = np.sqrt(2 * np.pi * width * samplerate)
        wavelet = normalization * signal.morlet(n, omega, width)
        cwtout[ind, :] = signal.fftconvolve(data,
                                            np.real(wavelet),
                                            mode='same')
        # pseudo-frequencies corresponding to scales
        freqs[ind] = 2 * width * omega * samplerate / n

    coi = coneofinfluence(n, omega, timestep=1 / samplerate)

    return cwtout, freqs, coi
Example #22
0
    def __init__(self,
                 sampling_rate=250,
                 box_width=250,
                 M=25,
                 wavelets_freqs=(10, 22),
                 input_dim=None,
                 dtype=None):
        super(EEGFeatures, self).__init__(input_dim=input_dim, dtype=dtype)

        self.sampling_rate = sampling_rate
        self.box_width = box_width
        self.M = M
        self.wavelets_freqs = wavelets_freqs

        self.wavelets = list()
        for f in wavelets_freqs:
            wavelet = signal.morlet(M, w=(f * M) / (2.0 * sampling_rate))
            self.wavelets.append(wavelet)
Example #23
0
def MakePlot():
    Points = 5000
    MaxX = np.pi * 2
    XValues,dx = np.linspace(start=0,stop=MaxX,num=Points,retstep=True)
    num_steps = 3
    step = int(Points/num_steps)
    frequency_low = 1
    frequency_high = 10
    freqs = np.linspace( frequency_low, frequency_high,num=num_steps )
    Idx = [ slice(i*step,(i+1)*step,1) for i in range(step)]
    y_values = np.zeros(XValues.size)
    for f,idx_range in zip(freqs,Idx):
        x_tmp = XValues[idx_range]
        y_values[idx_range] = np.sin(2*np.pi*f*(x_tmp-x_tmp[0]))
    # Get the FFT of our function
    fft_coeffs = np.fft.rfft(y_values)
    fft_freq = np.fft.rfftfreq(n=y_values.size,d=dx)
    # get the CWT of our function 
    CoeffMax = frequency_high*5
    CoeffMin = 1/(frequency_low/5)
    NCoeffs = 50
    widths = np.linspace(CoeffMin,CoeffMax,NCoeffs)
    wavelet_signal = lambda n_points,width: \
            signal.morlet(M=n_points,w=width,complete=True,s=1.0)
    cwt_coeffs = signal.cwt(data=y_values,wavelet=signal.ricker,widths=widths)
    fudge = 0.5
    x_lim = np.array([0,max(XValues)])
    x_fudge = np.array([-fudge,fudge])
    plt.subplot(3,1,1)
    plt.plot(XValues,y_values)
    plt.xlim(x_lim+x_fudge)
    PlotUtilities.lazyLabel("Time","","")
    plt.subplot(3,1,2)
    plt.plot(fft_freq,fft_coeffs)
    PlotUtilities.lazyLabel("Frequency","FFT Coefficients","")
    plt.subplot(3,1,3)
    plt.imshow(cwt_coeffs, extent=[x_lim[0], x_lim[1], 
                                   min(widths), max(widths)], 
               cmap='PRGn', aspect='auto',
               vmax=abs(cwt_coeffs).max(), vmin=-abs(cwt_coeffs).max())
    plt.xlim(x_lim+x_fudge)
    PlotUtilities.lazyLabel("Time","Frequency","Morlet Coefficient Map")
def scaleogram(raw_signal, sample_rate, num_samps=128, log_low_freq=0, log_high_freq=1.6, num_freqs=32, width=6, sigma_factor=8, is_log=True):
    
    freqs = np.logspace(log_low_freq, log_high_freq, num_freqs, endpoint=True)
    sigma_array = width / (2. * np.pi * freqs)
    wavelet_len = min(math.ceil(np.max(sigma_array) * sample_rate * sigma_factor), len(raw_signal))
    scales = (freqs * wavelet_len) / (2. * width * sample_rate)
    
    wavelets = [sps.morlet(wavelet_len, width, s) for s in scales]
    
    time_indices = np.round(np.linspace(wavelet_len - 1, len(raw_signal) - 1, num_samps)).astype(np.dtype('int32'))
                        
    cwt_array = np.vstack([sample_cwt(raw_signal, w, time_indices) for w in wavelets])
    
    mag_cwt = np.absolute(cwt_array)
    phase_cwt = np.angle(cwt_array)
    
    if is_log:
        mag_cwt = 2 * np.where(mag_cwt > 0, np.log(mag_cwt), 0)
    else:
        mag_cwt = mag_cwt**2
    
    return [mag_cwt, phase_cwt]
Example #25
0
    chisquare = chi2.ppf(significance_level, dof) / dof
    signif = fft_theor * chisquare

    return signif


# ======================================================================================================================
if __name__ == "__main__":
    n = 10000

    import seaborn as sns
    # Image for thesis: sine and Morlet in both time and frequency spaces
    sns.set(context="talk", style="white", rc={'font.family': [u'serif']})
    f, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(10, 8))

    ax1.plot(signal.morlet(1000, 5, 1))
    ax1.set_title("Morlet Wavelet in Time Domain")
    ax1.set_xlabel("Time")

    ax2.plot(np.fft.fftfreq(1000, 1),
             abs(np.fft.fft(signal.morlet(1000, 5, 1)).real)**2)
    ax2.set_xlim([0, 0.02])
    ax2.set_title("Morlet Wavelet in Frequency Domain")
    ax2.set_xlabel("Frequency")

    ax3.plot(np.linspace(0, 10, num=1000),
             np.sin(2 * np.pi * np.linspace(0, 10, num=1000)))
    ax3.set_title("Sinusoid in Time Domain")
    ax3.set_xlabel("Time")

    ax4.plot(
Example #26
0
    xp = []
    while (e > tol and itr < maxiter):
        x = f(x0)  # fixed point equation
        e = np.linalg.norm(x0 - x)  # error at the current step
        x0 = x
        xp.append(x0)  # save the solution of the current step
        itr = itr + 1
    return x, xp


"""
f = lambda x : np.sqrt(x)
x_start = .5
xf,xp = fixedp(f,x_start)

x = np.linspace(0,2,100)
y = f(x)

plt.plot(x,y,xp,f(xp),'bo',
     x_start,f(x_start),'ro',xf,f(xf),'go',x,x,'k')
"""

plt.close('all')
t = np.linspace(-1, 1, 500, endpoint=False)
m = morlet(500, w=5, s=1, complete=True)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot(t, np.real(m), np.imag(m))

plt.figure()
plt.plot(t, np.real(m))
Example #27
0
def morletSpline(N=200, **kwargs):
    morlet_x    = range(N//2-N, N//2)
    morlet_y    = signal.morlet(N, **kwargs)
    #return interpolate.UnivariateSpline(morlet_x, morlet_y)
    return interpolate.interp1d(morlet_x, morlet_y, kind="quadratic")
Example #28
0
def morlet(N, **kwargs):
    #http://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.morlet.html#scipy.signal.morlet
    return signal.morlet(N, **kwargs)
Example #29
0
def morlet_convolve(sig,
                    fs,
                    freq,
                    n_cycles=7,
                    scaling=0.5,
                    filt_len=None,
                    norm='sss'):
    """Convolve a signal with a complex wavelet.

    Parameters
    ----------
    sig : 1d array
        Time series to filter.
    fs : float
        Sampling rate, in Hz.
    freq : float
        Center frequency of bandpass filter.
    n_cycles : float, optional, default=7
        Length of the filter, as the number of cycles of the oscillation with specified frequency.
    scaling : float, optional, default=0.5
        Scaling factor for the morlet wavelet.
    filt_len : integer, optional
        Length of the filter. If not None, this overrides the freq and n_cycles inputs.
    norm : {'sss', 'amp'}, optional
        Normalization method:

        * 'sss' - divide by the sqrt of the sum of squares of points
        * 'amp' - divide by the sum of amplitudes divided by 2

    Returns
    -------
    array
        Complex time series.

    Notes
    -----

    * The real part of the returned array is the filtered signal.
    * Taking np.abs() of output gives the analytic amplitude.
    * Taking np.angle() of output gives the analytic phase.
    """

    if n_cycles <= 0:
        raise ValueError(
            'Number of cycles for morlet wavelets must be a positive number.')

    if filt_len is None:
        filt_len = n_cycles * fs / freq

    morlet_f = morlet(filt_len, w=n_cycles, s=scaling)

    # ToDo: there is an inconsistency between these methods, and the docs.
    if norm == 'sss':
        morlet_f = morlet_f / np.sqrt(np.sum(np.abs(morlet_f)**2))
    elif norm == 'abs':
        morlet_f = morlet_f / np.sum(np.abs(morlet_f))
    else:
        raise ValueError('Not a valid wavelet normalization method.')

    mwt_real = np.convolve(sig, np.real(morlet_f), mode='same')
    mwt_imag = np.convolve(sig, np.imag(morlet_f), mode='same')

    return mwt_real + 1j * mwt_imag
Example #30
0
def test_morlet(num_samps):
    cpu_window = signal.morlet(num_samps)
    gpu_window = cp.asnumpy(cusignal.morlet(num_samps))
    assert array_equal(cpu_window, gpu_window)
Example #31
0
 def cpu_version(self, num_samps):
     return signal.morlet(num_samps)
#what needs to be implemented
#   A if statement for multiprocessing/threading.

OPENBCI_PORT = '/dev/ttyACM0'
TEENSY_PORT = '/dev/ttyACM1'
TEENSY_ENABLED = False

look_back = 15

box_width = 125 # 250

M = 30
r = 250
f1, f2 = 10, 22

wavelet1 = signal.morlet(M, w=(f1*M)/(2.0*r))
wavelet2 = signal.morlet(M, w=(f2*M)/(2.0*r))

def extract_features(data):
    sigs = np.zeros((data.shape[0], 3))
    sigs[..., 0] = (data[..., 0] + data[..., 1])/2.0
    sigs[..., 1] = (data[..., 2] + data[..., 3])/2.0
    sigs[..., 2] = (data[..., 4] + data[..., 5])/2.0

    # fft_len = np.fft.rfft(data[..., 0]).shape[0]
    features = np.array([])


    for j in range(3):
        sig = sigs[..., j]
        conv1 = signal.convolve(sig, wavelet1, 'same')
Example #33
0
def convolve_wavelet(sig,
                     fs,
                     freq,
                     n_cycles=7,
                     scaling=0.5,
                     wavelet_len=None,
                     norm='sss'):
    """Convolve a signal with a complex wavelet.

    Parameters
    ----------
    sig : 1d array
        Time series to filter.
    fs : float
        Sampling rate, in Hz.
    freq : float
        Center frequency of bandpass filter.
    n_cycles : float, optional, default: 7
        Length of the filter, as the number of cycles of the oscillation with specified frequency.
    scaling : float, optional, default: 0.5
        Scaling factor for the morlet wavelet.
    wavelet_len : int, optional
        Length of the wavelet. If defined, this overrides the freq and n_cycles inputs.
    norm : {'sss', 'amp'}, optional
        Normalization method:

        * 'sss' - divide by the square root of the sum of squares
        * 'amp' - divide by the sum of amplitudes

    Returns
    -------
    array
        Complex time series.

    Notes
    -----

    * The real part of the returned array is the filtered signal.
    * Taking np.abs() of output gives the analytic amplitude.
    * Taking np.angle() of output gives the analytic phase.

    Examples
    --------
    Convolve a complex wavelet with a simulated signal:

    >>> from neurodsp.sim import sim_combined
    >>> sig = sim_combined(n_seconds=10, fs=500,
    ...                    components={'sim_powerlaw': {}, 'sim_oscillation' : {'freq': 10}})
    >>> cts = convolve_wavelet(sig, fs=500, freq=10)
    """

    check_param_options(norm, 'norm', ['sss', 'amp'])

    if wavelet_len is None:
        wavelet_len = int(n_cycles * fs / freq)

    if wavelet_len > sig.shape[-1]:
        raise ValueError(
            'The length of the wavelet is greater than the signal. Can not proceed.'
        )

    morlet_f = morlet(wavelet_len, w=n_cycles, s=scaling)

    if norm == 'sss':
        morlet_f = morlet_f / np.sqrt(np.sum(np.abs(morlet_f)**2))
    elif norm == 'amp':
        morlet_f = morlet_f / np.sum(np.abs(morlet_f))

    mwt_real = np.convolve(sig, np.real(morlet_f), mode='same')
    mwt_imag = np.convolve(sig, np.imag(morlet_f), mode='same')

    return mwt_real + 1j * mwt_imag
Example #34
0
def convolve_wavelet(sig,
                     fs,
                     freq,
                     n_cycles=7,
                     scaling=0.5,
                     wavelet_len=None,
                     norm='sss'):
    """Convolve a signal with a complex wavelet.

    Parameters
    ----------
    sig : 1d array
        Time series to filter.
    fs : float
        Sampling rate, in Hz.
    freq : float
        Center frequency of bandpass filter.
    n_cycles : float, optional, default=7
        Length of the filter, as the number of cycles of the oscillation with specified frequency.
    scaling : float, optional, default=0.5
        Scaling factor for the morlet wavelet.
    wavelet_len : integer, optional
        Length of the wavelet. If defined, this overrides the freq and n_cycles inputs.
    norm : {'sss', 'amp'}, optional
        Normalization method:

        * 'sss' - divide by the square root of the sum of squares
        * 'amp' - divide by the sum of amplitudes

    Returns
    -------
    array
        Complex time series.

    Notes
    -----

    * The real part of the returned array is the filtered signal.
    * Taking np.abs() of output gives the analytic amplitude.
    * Taking np.angle() of output gives the analytic phase.
    """

    if wavelet_len is None:
        wavelet_len = n_cycles * fs / freq

    if wavelet_len > sig.shape[-1]:
        raise ValueError(
            'The length of the wavelet is greater than the signal. Can not proceed.'
        )

    morlet_f = morlet(wavelet_len, w=n_cycles, s=scaling)

    if norm == 'sss':
        morlet_f = morlet_f / np.sqrt(np.sum(np.abs(morlet_f)**2))
    elif norm == 'amp':
        morlet_f = morlet_f / np.sum(np.abs(morlet_f))
    else:
        raise ValueError('Not a valid wavelet normalization method.')

    mwt_real = np.convolve(sig, np.real(morlet_f), mode='same')
    mwt_imag = np.convolve(sig, np.imag(morlet_f), mode='same')

    return mwt_real + 1j * mwt_imag
from PIL import Image
import numpy as np
from scipy.stats import norm
from scipy.signal import morlet

image_size = 1000
max_gray = 65535
dtype = np.uint16

wavelet = np.real(morlet(image_size))
wavelet = np.interp(wavelet, (wavelet.min(), wavelet.max()), (0, max_gray))
int_array = (np.repeat([wavelet], image_size, 0)).astype(dtype)

Image.fromarray(int_array).save("build/wavelet.png")
from scipy import signal
from math import pi, e
from DataGen import DataGen

fig, axs = plt.subplots(2, 2, figsize=(16, 4))
train_data_generator = DataGen(file_path='train.csv', chunk_size=10000000)
next_batch, end_of_file = train_data_generator.next_batch()
current_batch = next_batch['acoustic_data'][10000:11000]
next_batch[10000:11000].plot(x='time_to_failure', y='acoustic_data', ax=axs[0, 0])

sigma = [0.1, 0.5, 1]
t = M = [32, 48, 56] # windows sizes
w = 2*pi # Omega0 - base angular freq

sigma_term = e**(-(sigma[0]**2)/2)
morlet = signal.morlet(t[0], w=2*pi)
F_W = signal.fftconvolve(current_batch, morlet - sigma_term, mode='same')
axs[0, 1].plot(F_W, label="sigma = {}".format(sigma[0]))
axs[0, 1].legend()

sigma_term = e**(-(sigma[1]**2)/2)
morlet = signal.morlet(t[1], w=2*pi)
F_W = signal.fftconvolve(current_batch, morlet - sigma_term, mode='same')
axs[1, 0].plot(F_W, label="sigma = {}".format(sigma[1]))
axs[1, 0].legend()

sigma_term = e**(-(sigma[2]**2)/2)
morlet = signal.morlet(t[2], w=2*pi)
F_W = signal.fftconvolve(current_batch, morlet - sigma_term, mode='same')
axs[1, 1].plot(F_W, label="sigma = {}".format(sigma[2]))
axs[1, 1].legend()
Example #37
0
#
# Here, we provide an example plot of an individual Morlet wavelet. We'll use the
# `scipy.signal` function `morlet` to create a wavelet that is 5 cycles long.
#

###################################################################################################

# Define sampling rate, number of cycles, fundamental frequency, and length for the wavelet
n_cycles = 5
freq = 5
scaling = 1.0
omega = n_cycles
wavelet_len = int(n_cycles * fs / freq)

# Create wavelet
wavelet = signal.morlet(wavelet_len, omega, scaling)

###################################################################################################

# Plot the real part of the wavelet
_, ax = plt.subplots()
ax.plot(np.real(wavelet))
ax.set_axis_off()

###################################################################################################
# Real & Imaginary Dimensions
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# Note that wavelets have both real and imaginary dimensions.
#
Example #38
0
import numpy as np
from pprint import pprint
from pylab import *

import Oger
import mdp

d = pandas.read_csv("motor_data_jim_2.csv")
d = d.dropna()
d = d.reset_index(drop=True)

M = 30
r = 250 # sampling rate
f1, f2 = 10, 22

wavelet1 = signal.morlet(M, w=(f1*M)/(2.0*r))
wavelet2 = signal.morlet(M, w=(f2*M)/(2.0*r))

box_width = 250

features_arr = np.zeros( (len(d.index), # rows
                          # cols, FFT len * n_signals * n_wavelets * 1 (abs, no angle)
                          box_width * 3 * 3 * 1)  ) 

for i in range(box_width, len(d)-1):
    if i % 1000 == 0:
        print(i)
    
    data = np.array(d[(i - box_width+1):(i+1)])
    sigs = np.zeros((data.shape[0], 3))
    sigs[..., 0] = (data[..., 0] + data[..., 1])/2.0
Example #39
0
def abs_morlet(M, w=0.5, s=0.1):
    return np.abs(signal.morlet(M, w=0.5, s=0.1))