Exemple #1
0
 def calcFFT(self):
     #Länge des zu transformierenden Vectors bestimmen
     N = len(self.volt)
     #Optimale FFT-Länge bestimmen und ggf Zeropadding
     N_fast = next_fast_len(N)
     #Kaiser-Bessel-Fenster bestimmen
     w = win.kaiser(N,12)
     w = w / w.sum() * N #Normierung damit Amplituden wieder stimmen
     #Transformieren
     yf = fft(self.volt*w, N_fast)
     yf = fftshift(yf)
     #Abschneiden
     yf = yf[N_fast//2:]
     #Skalieren
     yf = 2/N_fast*abs(yf)
     #Frequenzachse erzeugen
     xf = fftfreq(N_fast)
     xf = fftshift(xf)
     #Abschneiden
     xf = xf[N_fast//2:]
     #Skalieren
     xf = xf*self.samplingrate
     #Veröffentlichen der Werte
     self.spectrum = yf
     self.freq = xf
     return '-DONE-'
Exemple #2
0
 def test_basic(self):
     assert_allclose(windows.kaiser(6, 0.5),
                     [0.9403061933191572, 0.9782962393705389,
                      0.9975765035372042, 0.9975765035372042,
                      0.9782962393705389, 0.9403061933191572])
     assert_allclose(windows.kaiser(7, 0.5),
                     [0.9403061933191572, 0.9732402256999829,
                      0.9932754654413773, 1.0, 0.9932754654413773,
                      0.9732402256999829, 0.9403061933191572])
     assert_allclose(windows.kaiser(6, 2.7),
                     [0.2603047507678832, 0.6648106293528054,
                      0.9582099802511439, 0.9582099802511439,
                      0.6648106293528054, 0.2603047507678832])
     assert_allclose(windows.kaiser(7, 2.7),
                     [0.2603047507678832, 0.5985765418119844,
                      0.8868495172060835, 1.0, 0.8868495172060835,
                      0.5985765418119844, 0.2603047507678832])
     assert_allclose(windows.kaiser(6, 2.7, False),
                     [0.2603047507678832, 0.5985765418119844,
                      0.8868495172060835, 1.0, 0.8868495172060835,
                      0.5985765418119844])
Exemple #3
0
def array_factor(number_of_elements, scan_angle, element_spacing, frequency,
                 theta, window_type, side_lobe_level):
    """
    Calculate the array factor for a linear binomial excited array.
    :param window_type: The string name of the window.
    :param side_lobe_level: The sidelobe level for Tschebyscheff window (dB).
    :param number_of_elements: The number of elements in the array.
    :param scan_angle: The angle to which the main beam is scanned (rad).
    :param element_spacing: The distance between elements.
    :param frequency: The operating frequency (Hz).
    :param theta: The angle at which to evaluate the array factor (rad).
    :return: The array factor as a function of angle.
    """
    # Calculate the wavenumber
    k = 2.0 * pi * frequency / c

    # Calculate the phase
    psi = k * element_spacing * (cos(theta) - cos(scan_angle))

    # Calculate the coefficients
    if window_type == 'Uniform':
        coefficients = ones(number_of_elements)
    elif window_type == 'Binomial':
        coefficients = binom(number_of_elements - 1,
                             range(0, number_of_elements))
    elif window_type == 'Tschebyscheff':
        warnings.simplefilter("ignore", UserWarning)
        coefficients = chebwin(number_of_elements,
                               at=side_lobe_level,
                               sym=True)
    elif window_type == 'Kaiser':
        coefficients = kaiser(number_of_elements, 6, True)
    elif window_type == 'Blackman-Harris':
        coefficients = blackmanharris(number_of_elements, True)
    elif window_type == 'Hanning':
        coefficients = hanning(number_of_elements, True)
    elif window_type == 'Hamming':
        coefficients = hamming(number_of_elements, True)

    # Calculate the offset for even/odd
    offset = int(floor(number_of_elements / 2))

    # Odd case
    if number_of_elements & 1:
        coefficients = roll(coefficients, offset + 1)
        coefficients[0] *= 0.5
        af = sum(coefficients[i] * cos(i * psi) for i in range(offset + 1))
        return af / amax(abs(af))
    # Even case
    else:
        coefficients = roll(coefficients, offset)
        af = sum(coefficients[i] * cos((i + 0.5) * psi) for i in range(offset))
        return af / amax(abs(af))
Exemple #4
0
 def test_basic(self):
     assert_allclose(windows.kaiser(6, 0.5),
                     [0.9403061933191572, 0.9782962393705389,
                      0.9975765035372042, 0.9975765035372042,
                      0.9782962393705389, 0.9403061933191572])
     assert_allclose(windows.kaiser(7, 0.5),
                     [0.9403061933191572, 0.9732402256999829,
                      0.9932754654413773, 1.0, 0.9932754654413773,
                      0.9732402256999829, 0.9403061933191572])
     assert_allclose(windows.kaiser(6, 2.7),
                     [0.2603047507678832, 0.6648106293528054,
                      0.9582099802511439, 0.9582099802511439,
                      0.6648106293528054, 0.2603047507678832])
     assert_allclose(windows.kaiser(7, 2.7),
                     [0.2603047507678832, 0.5985765418119844,
                      0.8868495172060835, 1.0, 0.8868495172060835,
                      0.5985765418119844, 0.2603047507678832])
     assert_allclose(windows.kaiser(6, 2.7, False),
                     [0.2603047507678832, 0.5985765418119844,
                      0.8868495172060835, 1.0, 0.8868495172060835,
                      0.5985765418119844])
Exemple #5
0
def sinusoid(size, frequency, angle, beta=0):
    '''Generate an image with pure sinusoid.

    The amplitude and DC offset are set so that the minimum and maximum values
    are 0 and 1, respectively.

    Parameters
    ----------
    size : tuple
        width and height of the output image
    frequency : float
        frequency in cycles per pixel
    angle : float
        value in degrees indicating the orientation of the sinusoid
    beta : float
        value of the Kaiser window 'beta' parameter

    Returns
    -------
    numpy.ndarray
        the generated output image
    '''
    if frequency < 0:
        raise ValueError('Frequency must be a positive value.')

    omega = 2.0 * np.pi * frequency / np.min(size)
    theta = np.deg2rad(angle)

    y, x = np.meshgrid(np.arange(size[1]), np.arange(size[0]))
    u = x * np.cos(theta) + y * np.sin(theta)
    out = np.cos(omega * u) / 2.0 + 0.5

    w1 = kaiser(size[0], beta)
    w2 = kaiser(size[1], beta)

    window = w1[np.newaxis, :].T @ w2[np.newaxis, :]
    out *= window

    return out
def proc_im(im, N_im = 256, noise_scale = 50, kaiser_beta = 4):
    

    k0 = np.fft.ifftshift(np.fft.fft2(np.fft.fftshift(im)))
    k0 += noise_scale * (np.random.standard_normal(k0.shape) + 1j * np.random.standard_normal(k0.shape))
    
    # if np.random.rand() < blur_chance:
    #     win_beta = np.random.rand() * (beta_lims[1] - beta_lims[0]) + beta_lims[0]
    #     window = kaiser(N_im, win_beta, sym=False)
    #     k0 *= np.outer(window, window)

    window = kaiser(N_im, kaiser_beta, sym=False)
    k0 *= np.outer(window, window)

    im = np.fft.ifftshift(np.fft.ifft2(np.fft.fftshift(k0)))
    
    return im
    def _update_canvas(self):
        """
        Update the figure when the user changes an input value
        :return:
        """
        # Get the parameters from the form
        number_of_steps = int(self.number_of_steps.text())
        frequency_step = float(self.frequency_step.text())
        prf = float(self.prf.text())
        target_range = self.target_range.text().split(',')
        target_rcs = self.target_rcs.text().split(',')
        target_velocity = self.target_velocity.text().split(',')

        t_range = [float(r) for r in target_range]
        t_rcs = [float(r) for r in target_rcs]
        t_velocity = [float(v) for v in target_velocity]

        # Get the selected window from the form
        window_type = self.window_type.currentText()

        if window_type == 'Kaiser':
            coefficients = kaiser(number_of_steps, 6, True)
        elif window_type == 'Blackman-Harris':
            coefficients = blackmanharris(number_of_steps, True)
        elif window_type == 'Hanning':
            coefficients = hanning(number_of_steps, True)
        elif window_type == 'Hamming':
            coefficients = hamming(number_of_steps, True)
        elif window_type == 'Rectangular':
            coefficients = ones(number_of_steps)

        # Calculate the base band return signal
        s = zeros(number_of_steps, dtype=complex)

        for rng, rcs, v in zip(t_range, t_rcs, t_velocity):
            s += [sqrt(rcs) * exp(-1j * 4.0 * pi / c * (i * frequency_step) * (rng - v * (i / prf)))
                  for i in range(number_of_steps)]

            n = next_fast_len(10 * number_of_steps)
            sf = ifft(s * coefficients, n) * float(n) / float(number_of_steps)

        # range_resolution = c / (2.0 * number_of_steps * frequency_step)
        range_unambiguous = c / (2.0 * frequency_step)

        range_window = linspace(0, range_unambiguous, n)

        # Clear the axes for the updated plot
        self.axes1.clear()

        # Create the line plot
        self.axes1.plot(range_window, 20.0 * log10(abs(sf) + finfo(float).eps), '')

        # Set the x and y axis labels
        self.axes1.set_xlabel("Range (m)", size=12)
        self.axes1.set_ylabel("Amplitude (dBsm)", size=12)

        # Turn on the grid
        self.axes1.grid(linestyle=':', linewidth=0.5)

        # Set the plot title and labels
        self.axes1.set_title('Stepped Frequency Range Profile', size=14)

        # Set the tick label size
        self.axes1.tick_params(labelsize=12)

        # Update the canvas
        self.my_canvas.draw()
sig_xmitt *= hann(tsig.size)
# create an interpolator, this allows for sub sample timing of arrivals
sig_ier = interp1d(tsig, sig_xmitt, kind=3, bounds_error=False, fill_value=0.)

# create time series as a sum of all arrivals
x_sig = np.zeros_like(taxis)
x_sig += sig_ier(taxis - time_dir) / r_dir
x_sig -= sig_ier(taxis - time_surf) / r_surf
x_sig -= sig_ier(taxis - time_bottom) / r_bottom

# create some noise
x_sig += np.random.randn(x_sig.size) * np.sqrt(noise_level)

# construct a window for the FFT. This is necassary when we don't know where
# the edges of the signal will be.
window = kaiser(winwidth, 2.5 * pi)
num_overlap = int(np.ceil(winwidth * overlap))

# construct a time axis for the single frequency power
num_windows = int(np.floor((taxis.size - winwidth) / (winwidth - num_overlap)))
win_position = np.arange(num_windows) * (winwidth - num_overlap)
win_time = (win_position + winwidth / 2) / fs
win_time += taxis[0]

# take a sliding position FFT. This will be done on the DSP processing board.
# This is used to extract the single frequency content of the signal over time
sig_FT = []
for wp in win_position:
    sig_FT.append(np.fft.rfft(x_sig[wp: wp + winwidth] * window))
sig_FT = np.array(sig_FT)
faxis = np.arange(winwidth // 2 + 1) / winwidth * fs
Exemple #9
0
def spec_track(signal, pitch, parameters):

    #---------------------------------------------------------------
    # Set parameters.
    #---------------------------------------------------------------
    nframe_size = pitch.frame_size * 2
    maxpeaks = parameters['shc_maxpeaks']
    delta = signal.new_fs / pitch.nfft

    window_length = int(np.fix(parameters['shc_window'] / delta))
    half_window_length = int(np.fix(float(window_length) / 2))
    if not (window_length % 2):
        window_length += 1

    max_SHC = int(
        np.fix((parameters['f0_max'] + parameters['shc_pwidth'] * 2) / delta))
    min_SHC = int(np.ceil(parameters['f0_min'] / delta))
    num_harmonics = parameters['shc_numharms']

    #---------------------------------------------------------------
    # Main routine.
    #---------------------------------------------------------------
    cand_pitch = np.zeros((maxpeaks, pitch.nframes))
    cand_merit = np.ones((maxpeaks, pitch.nframes))

    data = np.append(
        signal.filtered,
        np.zeros((1, nframe_size +
                  ((pitch.nframes - 1) * pitch.frame_jump - signal.size))))

    #Compute SHC for voiced frame
    window = kaiser(nframe_size, 0.5)
    SHC = np.zeros((max_SHC))
    row_mat_list = np.array([
        np.empty((max_SHC - min_SHC + 1, window_length))
        for x in range(num_harmonics + 1)
    ])

    magnitude = np.zeros(int((half_window_length + (pitch.nfft / 2) + 1)))

    for frame in np.where(pitch.vuv)[0].tolist():
        fir_step = frame * pitch.frame_jump

        data_slice = data[fir_step:fir_step + nframe_size] * window
        data_slice -= np.mean(data_slice)

        magnitude[half_window_length:] = np.abs(
            np.fft.rfft(data_slice, pitch.nfft))

        for idx, row_mat in enumerate(row_mat_list):
            row_mat[:, :] = stride_matrix(magnitude[min_SHC * (idx + 1):],
                                          max_SHC - min_SHC + 1, window_length,
                                          idx + 1)
        SHC[min_SHC - 1:max_SHC] = np.sum(np.prod(row_mat_list, axis=0),
                                          axis=1)

        cand_pitch[:, frame], cand_merit[:, frame] = \
            peaks(SHC, delta, maxpeaks, parameters)

    #Extract the pitch candidates of voiced frames for the future pitch selection.
    spec_pitch = cand_pitch[0, :]
    voiced_cand_pitch = cand_pitch[:, cand_pitch[0, :] > 0]
    voiced_cand_merit = cand_merit[:, cand_pitch[0, :] > 0]
    num_voiced_cand = len(voiced_cand_pitch[0, :])
    avg_voiced = np.mean(voiced_cand_pitch[0, :])
    std_voiced = np.std(voiced_cand_pitch[0, :])

    #Interpolation of the weigthed candidates.
    delta1 = abs(
        (voiced_cand_pitch - 0.8 * avg_voiced)) * (3 - voiced_cand_merit)
    index = delta1.argmin(0)

    voiced_peak_minmrt = voiced_cand_pitch[index, range(num_voiced_cand)]
    voiced_merit_minmrt = voiced_cand_merit[index, range(num_voiced_cand)]

    voiced_peak_minmrt = medfilt(voiced_peak_minmrt,
                                 max(1, parameters['median_value'] - 2))

    #Replace the lowest merit candidates by the median smoothed ones
    #computed from highest merit peaks above.
    voiced_cand_pitch[index, range(num_voiced_cand)] = voiced_peak_minmrt
    voiced_cand_merit[index, range(num_voiced_cand)] = voiced_merit_minmrt

    #Use dynamic programming to find best overal path among pitch candidates.
    #Dynamic weight for transition costs balance between local and
    #transition costs.
    weight_trans = parameters['dp5_k1'] * std_voiced / avg_voiced

    if num_voiced_cand > 2:
        voiced_pitch = dynamic5(voiced_cand_pitch, voiced_cand_merit,
                                weight_trans, parameters['f0_min'])
        voiced_pitch = medfilt(voiced_pitch,
                               max(1, parameters['median_value'] - 2))

    else:
        if num_voiced_cand > 0:
            voiced_pitch = (np.ones((num_voiced_cand))) * 150.0
        else:
            voiced_pitch = np.array([150.0])
            cand_pitch[0, 0] = 0

    pitch_avg = np.mean(voiced_pitch)
    pitch_std = np.std(voiced_pitch)
    spec_pitch[cand_pitch[0, :] > 0] = voiced_pitch[:]

    if (spec_pitch[0] < pitch_avg / 2):
        spec_pitch[0] = pitch_avg

    if (spec_pitch[-1] < pitch_avg / 2):
        spec_pitch[-1] = pitch_avg

    spec_voiced = np.array(np.nonzero(spec_pitch)[0])
    spec_pitch = scipy_interp.pchip(spec_voiced, spec_pitch[spec_voiced])(
        range(pitch.nframes))

    spec_pitch = lfilter(np.ones((3)) / 3, 1.0, spec_pitch)

    spec_pitch[0] = spec_pitch[2]
    spec_pitch[1] = spec_pitch[3]

    return spec_pitch, pitch_std
Exemple #10
0
# We can compare the window to `kaiser`, which was invented as an alternative
# that was easier to calculate [Re991e28c1f6b-3]_ (example adapted from
# `here <https://ccrma.stanford.edu/~jos/sasp/Kaiser_DPSS_Windows_Compared.html>`_):

import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import windows, freqz
N = 51
fig, axes = plt.subplots(3, 2, figsize=(5, 7))
for ai, alpha in enumerate((1, 3, 5)):
    win_dpss = windows.dpss(N, alpha)
    beta = alpha*np.pi
    win_kaiser = windows.kaiser(N, beta)
    for win, c in ((win_dpss, 'k'), (win_kaiser, 'r')):
        win /= win.sum()
        axes[ai, 0].plot(win, color=c, lw=1.)
        axes[ai, 0].set(xlim=[0, N-1], title=r'$\alpha$ = %s' % alpha,
                        ylabel='Amplitude')
        w, h = freqz(win)
        axes[ai, 1].plot(w, 20 * np.log10(np.abs(h)), color=c, lw=1.)
        axes[ai, 1].set(xlim=[0, np.pi],
                        title=r'$\beta$ = %0.2f' % beta,
                        ylabel='Magnitude (dB)')
for ax in axes.ravel():
    ax.grid(True)
axes[2, 1].legend(['DPSS', 'Kaiser'])
fig.tight_layout()
plt.show()

# And here are examples of the first four windows, along with their
# concentration ratios:
Exemple #11
0
def run(r, srcpd, layout):
    initial_model_filename = "overthrust_3D_initial_model.h5"
    tn = 5
    so = 6
    dtype = np.float32
    datakey = "m0"
    nbl = 40
    dt = 1.75

    time_axis = TimeAxis(start=0, stop=tn, step=dt)
    nt = time_axis.num
    model = overthrust_model_iso(initial_model_filename, datakey, so, nbl,
                                 dtype)
    shape = model.shape
    grid = model.grid
    origin = (0, 0, 0)
    spacing = model.spacing

    coeffs = kaiser(M=r, beta=6.31)

    # What we accepted as a parameter was sources per dimension. We are going to lay them out on a grid so square the number
    nsrc = srcpd * srcpd

    if layout == 'grid':
        src_coordinates = define_sources_grid(srcpd, model, r)
    elif layout == 'hemisphere':
        src_coordinates = define_sources_hemisphere(srcpd, model)
    else:
        print("Invalid layout: %s" % layout)
        return

    gridpoints = [
        tuple((int(floor((point[i] - origin[i]) / grid.spacing[i])) - r / 2)
              for i in range(len(point))) for point in src_coordinates
    ]

    src = PrecomputedSparseTimeFunction(name="src",
                                        grid=grid,
                                        npoint=nsrc,
                                        r=r,
                                        gridpoints=gridpoints,
                                        interpolation_coeffs=coeffs,
                                        nt=nt)

    ricker = RickerSource(time_range=time_axis,
                          grid=grid,
                          name="ricker",
                          f0=0.008)
    for p in range(nsrc):
        src.data[:, p] = ricker.wavelet

    m = model.m

    # Create symbols for forward wavefield, source and receivers
    u = TimeFunction(name='u',
                     grid=grid,
                     save=None,
                     time_order=2,
                     space_order=so)

    rec = Receiver(name='rec', grid=grid, time_range=time_axis, npoint=nsrc)

    s = model.grid.stepping_dim.spacing

    # Define PDE and update rule
    eq_time = solve(model.m * u.dt2 - u.laplace + model.damp * u.dt, u.forward)

    # Time-stepping stencil.
    eqns = [
        Eq(u.forward, eq_time, subdomain=model.grid.subdomains['physdomain'])
    ]

    # Construct expression to inject source values
    src_term = src.inject(field=u.forward, expr=src * s**2 / m)

    # Create interpolation expression for receivers
    rec_term = rec.interpolate(expr=u)
    # Substitute spacing terms to reduce flops
    op = Operator(eqns + src_term + rec_term,
                  subs=model.spacing_map,
                  name='Forward')

    op.apply(dt=dt)

    print("u_norm", np.linalg.norm(u.data))
Exemple #12
0
    def _update_canvas(self):
        """
        Update the figure when the user changes an input value
        :return:
        """
        # Get the parameters from the form
        bandwidth = float(self.bandwidth.text())
        pulsewidth = float(self.pulsewidth.text())
        target_range = self.target_range.text().split(',')
        target_rcs = self.target_rcs.text().split(',')

        t_range = [float(r) for r in target_range]
        t_rcs = [float(r) for r in target_rcs]

        # Get the selected window from the form
        window_type = self.window_type.currentText()

        # Number of samples
        N = int(2 * bandwidth * pulsewidth) * 8

        if window_type == 'Kaiser':
            coefficients = kaiser(N, 6, True)
        elif window_type == 'Blackman-Harris':
            coefficients = blackmanharris(N, True)
        elif window_type == 'Hanning':
            coefficients = hanning(N, True)
        elif window_type == 'Hamming':
            coefficients = hamming(N, True)
        elif window_type == 'Rectangular':
            coefficients = ones(N)

        # Set up the time vector
        t = linspace(-0.5 * pulsewidth, 0.5 * pulsewidth, N)

        # Calculate the baseband return signal
        s = zeros(N, dtype=complex)

        # Chirp slope
        alpha = 0.5 * bandwidth / pulsewidth

        for r, rcs in zip(t_range, t_rcs):
            s += sqrt(rcs) * exp(1j * 2.0 * pi * alpha * (t - 2.0 * r / c)**2)

        # Transmit signal
        st = exp(1j * 2 * pi * alpha * t**2)

        # Impulse response and matched filtering
        Hf = fft(conj(st * coefficients))
        Si = fft(s)
        so = fftshift(ifft(Si * Hf))

        # Range window
        range_window = linspace(-0.25 * c * pulsewidth, 0.25 * c * pulsewidth,
                                N)

        # Clear the axes for the updated plot
        self.axes1.clear()

        # Create the line plot
        self.axes1.plot(range_window,
                        20.0 * log10(abs(so) / N + finfo(float).eps), '')
        self.axes1.set_xlim(0, max(t_range) + 100)
        self.axes1.set_ylim(-60, max(20.0 * log10(abs(so) / N)) + 10)

        # Set the x and y axis labels
        self.axes1.set_xlabel("Range (m)", size=12)
        self.axes1.set_ylabel("Amplitude (dBsm)", size=12)

        # Turn on the grid
        self.axes1.grid(linestyle=':', linewidth=0.5)

        # Set the plot title and labels
        self.axes1.set_title('Matched Filter Range Profile', size=14)

        # Set the tick label size
        self.axes1.tick_params(labelsize=12)

        # Update the canvas
        self.my_canvas.draw()
Exemple #13
0
#
# a1 = 1
# a2 = 1
# a3 = 1
#
# x = np.real(a1 * x1 + a2 * x2 + a3 * x3)
# x = x / np.max(np.abs(x))
#
# decomposer = EMD(x)
# imf = decomposer.decompose()
#
# n_freq_bins = 256

short_window_length = 127
beta = 3 * np.pi
window = kaiser(short_window_length, beta=beta)
plt.figure(figsize=(15, 15))
plt.plot(x)
plt.show()
f, t, Sxx = signal.spectrogram(x, freq)
print('f')
print(f)
print('t')
print(t.shape)
print('Sxx')
print(Sxx.shape)

# for i in range(0,5):
#      print(Sxx[0][i])
_positon = np.argmax(Sxx)
print(_positon)
Exemple #14
0
alpha_max = 5
plot_no = 1
fig = plt.figure(1, figsize=(9.5, 7))

M = 21
hM1 = M // 2
hM2 = M // 2 + 1

N = 40
hN = N // 2

fig.suptitle('Kaiser window, M = %i, fft size = %i' % (M, N))

for alpha in range(alpha_max + 1):
    beta = alpha * np.pi
    w = kaiser(M, beta, M % 2 == 0)

    fftbuffer = np.zeros(N)
    fftbuffer[:hM1] = w[hM2:]
    fftbuffer[N - hM2:] = w[:hM2]

    W = fft(fftbuffer)

    mX = np.zeros(N)
    mX[:hN] = np.abs(W)[hN:]
    mX[hN:] = np.abs(W)[:hN]

    pX = np.zeros(N)
    pX[:hN] = np.angle(W)[hN:]
    pX[hN:] = np.angle(W)[:hN]
Exemple #15
0
    def pre_processing(self):
        """
        Complete various pre-processing steps for encoded protein sequences before
        doing any of the DSP-related functions or transformations. Zero-pad
        the sequences, remove any +/- infinity or NAN values, get the approximate
        protein spectra and window function parameter names.

        Parameters
        ----------
        :self (PyDSP object): 
            instance of PyDSP class.
            
        Returns
        -------
        None

        """
        #zero-pad encoded sequences so they are all the same length
        self.protein_seqs = zero_padding(self.protein_seqs)

        #get shape parameters of proteins seqs
        self.num_seqs = self.protein_seqs.shape[0]
        self.signal_len = self.protein_seqs.shape[1]

        #replace any positive or negative infinity or NAN values with 0
        self.protein_seqs[self.protein_seqs == -np.inf] = 0
        self.protein_seqs[self.protein_seqs == np.inf] = 0
        self.protein_seqs[self.protein_seqs == np.nan] = 0

        #replace any NAN's with 0's
        #self.protein_seqs.fillna(0, inplace=True)
        self.protein_seqs = np.nan_to_num(self.protein_seqs)

        #initialise zeros array to store all protein spectra
        self.fft_power = np.zeros((self.num_seqs, self.signal_len))
        self.fft_real = np.zeros((self.num_seqs, self.signal_len))
        self.fft_imag = np.zeros((self.num_seqs, self.signal_len))
        self.fft_abs = np.zeros((self.num_seqs, self.signal_len))

        #list of accepted spectra, window functions and filters
        all_spectra = ['power', 'absolute', 'real', 'imaginary']
        all_windows = [
            'hamming', 'blackman', 'blackmanharris', 'gaussian', 'bartlett',
            'kaiser', 'barthann', 'bohman', 'chebwin', 'cosine', 'exponential'
            'flattop', 'hann', 'boxcar', 'hanning', 'nuttall', 'parzen',
            'triang', 'tukey'
        ]
        all_filters = [
            'savgol', 'medfilt', 'symiirorder1', 'lfilter', 'hilbert'
        ]

        #set required input parameters, raise error if spectrum is none
        if self.spectrum == None:
            raise ValueError(
                'Invalid input Spectrum type ({}) not available in valid spectra: {}'
                .format(self.spectrum, all_spectra))
        else:
            #get closest correct spectra from user input, if no close match then raise error
            spectra_matches = (get_close_matches(self.spectrum,
                                                 all_spectra,
                                                 cutoff=0.4))

            if spectra_matches == []:
                raise ValueError(
                    'Invalid input Spectrum type ({}) not available in valid spectra: {}'
                    .format(self.spectrum, all_spectra))
            else:
                self.spectra = spectra_matches[0]  #closest match in array

        if self.window_type == None:
            self.window = 1  #window = 1 is the same as applying no window
        else:
            #get closest correct window function from user input
            window_matches = (get_close_matches(self.window,
                                                all_windows,
                                                cutoff=0.4))

            #check if sym=True or sym=False
            #get window function specified by window input parameter, if no match then window = 1
            if window_matches != []:
                if window_matches[0] == 'hamming':
                    self.window = hamming(self.signal_len, sym=True)
                    self.window_type = "hamming"
                elif window_matches[0] == "blackman":
                    self.window = blackman(self.signal_len, sym=True)
                    self.window = "blackman"
                elif window_matches[0] == "blackmanharris":
                    self.window = blackmanharris(self.signal_len,
                                                 sym=True)  #**
                    self.window_type = "blackmanharris"
                elif window_matches[0] == "bartlett":
                    self.window = bartlett(self.signal_len, sym=True)
                    self.window_type = "bartlett"
                elif window_matches[0] == "gaussian":
                    self.window = gaussian(self.signal_len, std=7, sym=True)
                    self.window_type = "gaussian"
                elif window_matches[0] == "kaiser":
                    self.window = kaiser(self.signal_len, beta=14, sym=True)
                    self.window_type = "kaiser"
                elif window_matches[0] == "hanning":
                    self.window = hanning(self.signal_len, sym=True)
                    self.window_type = "hanning"
                elif window_matches[0] == "barthann":
                    self.window = barthann(self.signal_len, sym=True)
                    self.window_type = "barthann"
                elif window_matches[0] == "bohman":
                    self.window = bohman(self.signal_len, sym=True)
                    self.window_type = "bohman"
                elif window_matches[0] == "chebwin":
                    self.window = chebwin(self.signal_len, sym=True)
                    self.window_type = "chebwin"
                elif window_matches[0] == "cosine":
                    self.window = cosine(self.signal_len, sym=True)
                    self.window_type = "cosine"
                elif window_matches[0] == "exponential":
                    self.window = exponential(self.signal_len, sym=True)
                    self.window_type = "exponential"
                elif window_matches[0] == "flattop":
                    self.window = flattop(self.signal_len, sym=True)
                    self.window_type = "flattop"
                elif window_matches[0] == "boxcar":
                    self.window = boxcar(self.signal_len, sym=True)
                    self.window_type = "boxcar"
                elif window_matches[0] == "nuttall":
                    self.window = nuttall(self.signal_len, sym=True)
                    self.window_type = "nuttall"
                elif window_matches[0] == "parzen":
                    self.window = parzen(self.signal_len, sym=True)
                    self.window_type = "parzen"
                elif window_matches[0] == "triang":
                    self.window = triang(self.signal_len, sym=True)
                    self.window_type = "triang"
                elif window_matches[0] == "tukey":
                    self.window = tukey(self.signal_len, sym=True)
                    self.window_type = "tukey"

            else:
                self.window = 1  #window = 1 is the same as applying no window

        #calculate convolution from protein sequences
        if self.convolution is not None:
            if self.window is not None:
                self.convoled_seqs = signal.convolve(
                    self.protein_seqs, self.window, mode='same') / sum(
                        self.window)

        if self.filter != None:
            #get closest correct filter from user input
            filter_matches = (get_close_matches(self.filter,
                                                all_filters,
                                                cutoff=0.4))

            #set filter attribute according to approximate user input
            if filter_matches != []:
                if filter_matches[0] == 'savgol':
                    self.filter = savgol_filter(self.signal_len,
                                                self.signal_len)
                elif filter_matches[0] == 'medfilt':
                    self.filter = medfilt(self.signal_len)
                elif filter_matches[0] == 'symiirorder1':
                    self.filter = symiirorder1(self.signal_len, c0=1, z1=1)
                elif filter_matches[0] == 'lfilter':
                    self.filter = lfilter(self.signal_len)
                elif filter_matches[0] == 'hilbert':
                    self.filter = hilbert(self.signal_len)
            else:
                self.filter = ""  #no filter
Exemple #16
0
 def test_kaiser_float(self):
     win1 = windows.get_window(7.2, 64)
     win2 = windows.kaiser(64, 7.2, False)
     assert_allclose(win1, win2)
    def _update_canvas(self):
        """
        Update the figure when the user changes an input value
        :return:
        """
        # Get the parameters from the form
        bandwidth = float(self.bandwidth.text())
        pulsewidth = float(self.pulsewidth.text())
        range_window_length = float(self.range_window_length.text())
        target_range = self.target_range.text().split(',')
        target_rcs = self.target_rcs.text().split(',')

        t_range = [float(r) for r in target_range]
        t_rcs = [float(r) for r in target_rcs]

        # Get the selected window from the form
        window_type = self.window_type.currentText()

        # Number of samples
        number_of_samples = int(ceil(4 * bandwidth * range_window_length / c))

        if window_type == 'Kaiser':
            coefficients = kaiser(number_of_samples, 6, True)
        elif window_type == 'Blackman-Harris':
            coefficients = blackmanharris(number_of_samples, True)
        elif window_type == 'Hanning':
            coefficients = hanning(number_of_samples, True)
        elif window_type == 'Hamming':
            coefficients = hamming(number_of_samples, True)
        elif window_type == 'Rectangular':
            coefficients = ones(number_of_samples)

        # Time sampling
        t, dt = linspace(-0.5 * pulsewidth,
                         0.5 * pulsewidth,
                         number_of_samples,
                         retstep=True)

        # Sampled signal after mixing
        so = zeros(number_of_samples, dtype=complex)
        for r, rcs in zip(t_range, t_rcs):
            so += sqrt(rcs) * exp(1j * 2.0 * pi * bandwidth / pulsewidth *
                                  (2 * r / c) * t)

        # Fourier transform
        so = fftshift(fft(so * coefficients, 4 * number_of_samples))

        # FFT frequencies
        frequencies = fftshift(fftfreq(4 * number_of_samples, dt))

        # Range window
        range_window = 0.5 * frequencies * c * pulsewidth / bandwidth

        # Clear the axes for the updated plot
        self.axes1.clear()

        # Create the line plot
        self.axes1.plot(
            range_window,
            20.0 * log10(abs(so) / number_of_samples + finfo(float).eps), '')
        self.axes1.set_xlim(min(t_range) - 5, max(t_range) + 5)
        self.axes1.set_ylim(
            -60,
            max(20.0 * log10(abs(so) / number_of_samples)) + 10)

        # Set the x and y axis labels
        self.axes1.set_xlabel("Range (m)", size=12)
        self.axes1.set_ylabel("Amplitude (dBsm)", size=12)

        # Turn on the grid
        self.axes1.grid(linestyle=':', linewidth=0.5)

        # Set the plot title and labels
        self.axes1.set_title('Stretch Processor Range Profile', size=14)

        # Set the tick label size
        self.axes1.tick_params(labelsize=12)

        # Update the canvas
        self.my_canvas.draw()
Exemple #18
0
 def test_kaiser_float(self):
     win1 = windows.get_window(7.2, 64)
     win2 = windows.kaiser(64, 7.2, False)
     assert_allclose(win1, win2)
Exemple #19
0
def spec_track(signal, pitch, parameters):

    #---------------------------------------------------------------
    # Set parameters.
    #---------------------------------------------------------------
    nframe_size = pitch.frame_size*2
    maxpeaks = parameters['shc_maxpeaks']
    delta = signal.new_fs/pitch.nfft

    window_length = int(np.fix(parameters['shc_window']/delta))
    half_window_length = int(np.fix(float(window_length)/2))
    if not(window_length % 2):
        window_length += 1

    max_SHC = int(np.fix((parameters['f0_max']+parameters['shc_pwidth']*2)/delta))
    min_SHC = int(np.ceil(parameters['f0_min']/delta))
    num_harmonics = parameters['shc_numharms']

    #---------------------------------------------------------------
    # Main routine.
    #---------------------------------------------------------------
    cand_pitch = np.zeros((maxpeaks, pitch.nframes))
    cand_merit = np.ones((maxpeaks, pitch.nframes))

    data = np.append(signal.filtered,
                  np.zeros((1, nframe_size +
                         ((pitch.nframes-1)*pitch.frame_jump-signal.size))))

    #Compute SHC for voiced frame
    window = kaiser(nframe_size, 0.5)
    SHC = np.zeros((max_SHC))
    row_mat_list = np.array([np.empty((max_SHC-min_SHC+1, window_length))
                            for x in range(num_harmonics+1)])

    magnitude = np.zeros(int((half_window_length+(pitch.nfft/2)+1)))

    for frame in np.where(pitch.vuv)[0].tolist():
        fir_step = frame*pitch.frame_jump

        data_slice = data[fir_step:fir_step+nframe_size]*window
        data_slice -= np.mean(data_slice)

        magnitude[half_window_length:] = np.abs(np.fft.rfft(data_slice,
                                                pitch.nfft))

        for idx,row_mat in enumerate(row_mat_list):
            row_mat[:, :] = stride_matrix(magnitude[min_SHC*(idx+1):],
                                          max_SHC-min_SHC+1,
                                          window_length, idx+1)
        SHC[min_SHC-1:max_SHC] = np.sum(np.prod(row_mat_list,axis=0),axis=1)

        cand_pitch[:, frame], cand_merit[:, frame] = \
            peaks(SHC, delta, maxpeaks, parameters)

    #Extract the pitch candidates of voiced frames for the future pitch selection.
    spec_pitch = cand_pitch[0, :]
    voiced_cand_pitch = cand_pitch[:, cand_pitch[0, :] > 0]
    voiced_cand_merit = cand_merit[:, cand_pitch[0, :] > 0]
    num_voiced_cand = len(voiced_cand_pitch[0, :])
    avg_voiced = np.mean(voiced_cand_pitch[0, :])
    std_voiced = np.std(voiced_cand_pitch[0, :])

    #Interpolation of the weigthed candidates.
    delta1 = abs((voiced_cand_pitch - 0.8*avg_voiced))*(3-voiced_cand_merit)
    index = delta1.argmin(0)

    voiced_peak_minmrt = voiced_cand_pitch[index, range(num_voiced_cand)]
    voiced_merit_minmrt = voiced_cand_merit[index, range(num_voiced_cand)]

    voiced_peak_minmrt = medfilt(voiced_peak_minmrt,
                                 max(1, parameters['median_value']-2))

    #Replace the lowest merit candidates by the median smoothed ones
    #computed from highest merit peaks above.
    voiced_cand_pitch[index, range(num_voiced_cand)] = voiced_peak_minmrt
    voiced_cand_merit[index, range(num_voiced_cand)] = voiced_merit_minmrt

    #Use dynamic programming to find best overal path among pitch candidates.
    #Dynamic weight for transition costs balance between local and
    #transition costs.
    weight_trans = parameters['dp5_k1']*std_voiced/avg_voiced

    if num_voiced_cand > 2:
        voiced_pitch = dynamic5(voiced_cand_pitch, voiced_cand_merit,
                                weight_trans, parameters['f0_min'])
        voiced_pitch = medfilt(voiced_pitch, max(1, parameters['median_value']-2))

    else:
        if num_voiced_cand > 0:
            voiced_pitch = (np.ones((num_voiced_cand)))*150.0
        else:
            voiced_pitch = np.array([150.0])
            cand_pitch[0, 0] = 0

    pitch_avg = np.mean(voiced_pitch)
    pitch_std = np.std(voiced_pitch)
    spec_pitch[cand_pitch[0, :] > 0] = voiced_pitch[:]

    if (spec_pitch[0] < pitch_avg/2):
        spec_pitch[0] = pitch_avg

    if (spec_pitch[-1] < pitch_avg/2):
        spec_pitch[-1] = pitch_avg

    spec_voiced = np.array(np.nonzero(spec_pitch)[0])
    spec_pitch = scipy_interp.pchip(spec_voiced,
                                    spec_pitch[spec_voiced])(range(pitch.nframes))

    spec_pitch = lfilter(np.ones((3))/3, 1.0, spec_pitch)

    spec_pitch[0] = spec_pitch[2]
    spec_pitch[1] = spec_pitch[3]

    return spec_pitch, pitch_std