def test_basic(self): assert_allclose(windows.hamming(6, False), [0.08, 0.31, 0.77, 1.0, 0.77, 0.31]) assert_allclose(windows.hamming(7, sym=False), [0.08, 0.2531946911449826, 0.6423596296199047, 0.9544456792351128, 0.9544456792351128, 0.6423596296199047, 0.2531946911449826]) assert_allclose(windows.hamming(6), [0.08, 0.3978521825875242, 0.9121478174124757, 0.9121478174124757, 0.3978521825875242, 0.08]) assert_allclose(windows.hamming(7, sym=True), [0.08, 0.31, 0.77, 1.0, 0.77, 0.31, 0.08])
def get_spec_power(sig, sr, bands): min_f = np.min(bands[np.nonzero(bands)]) winsize = sr * 10 if 1 / min_f > winsize / sr: raise WelchWindowError(winsize) elif len(sig) < winsize + sr: raise SignalTooShortError(len(sig)) else: power_bands = np.full(bands.shape[0], np.nan) # nfft is the greater of 256 or the next power of 2 greater than the length of the segments. nfft = max(256, 2**math.ceil(np.log2(winsize))) f, pxx = welch(sig, window=windows.hamming(winsize), nfft=nfft, fs=sr, detrend=False) eps = np.finfo(float).eps for i in range(len(bands)): power_bands[i] = np.log( sum(pxx[np.flatnonzero((f > bands[i, 0]) & (f <= bands[i, 1]))]) + eps) return power_bands
def test_hamming_window(random_state=None): from scipy.signal.windows import hamming n_window = 1024 np_window = hamming(n_window, False).astype(np.float64) tr_window = torch.hamming_window(n_window, periodic=True, dtype=torch.float64) assert torch.allclose(tr_window, torch.from_numpy(np_window)) np_window = hamming(n_window, True).astype(np.float64) tr_window = torch.hamming_window(n_window, periodic=False, dtype=torch.float64) assert torch.allclose(tr_window, torch.from_numpy(np_window))
def get_windows(self): rectangle_windows = [ boxcar(self.rc_lengths[0]), boxcar(self.rc_lengths[1]) ] hanning_windows = hanning(self.hn_length) hamming_windows = hamming(self.hm_length) self.windows = [rectangle_windows, hanning_windows, hamming_windows]
def window_function_transform(frames): from scipy.signal.windows import hamming # Construct a Hamming window with the same number of datapoints as 1 frame. window = hamming(frames.shape[1]) # Multiply all frames with our window function new_frames = np.array([frame*window for frame in frames]) return new_frames
def signal_ramp(n, percent): if percent > 49: percent = 49 length = int(numpy.floor((n * percent) / 100)) window = windows.hamming(length * 2 + 1) window = window - numpy.min(window) window = window / numpy.max(window) left = window[0:length + 1] right = window[length:] buffer = numpy.ones(n - 2 * left.size) total = numpy.hstack((left, buffer, right)) return total
def __init__(self, samples): self.frame_size = len(samples) self.samples = np.array(samples) self.classification = 0 self.zcr = 0 self.ste = 0 self.classification_vector = [] # Hamming window init for each frame self.hamm_window = hamming(self.frame_size)
def get_standard_tune(file): # read wav first frame_per_second, data = wavfile.read(file) if len(data.shape) == 2: data = data[:, 0] # then set some basic factors frequency_resolution = 1 slice_length = frame_per_second // frequency_resolution n_fft = slice_length interval = slice_length // 4 frame_number = (len(data) - slice_length) // interval + 1 fft_amplitude = np.zeros([n_fft // 2 + 1, frame_number]) hamming = windows.hamming(slice_length) # process fft for each frame for frame in range(frame_number): frame_start = interval * frame data_slice = data[frame_start:frame_start + slice_length] data_windowed = data_slice * hamming fft_result = fft(data_windowed, slice_length) / slice_length # fft result's amplitude is symmetric, so we just get half data of result # by the way, plus 1e-16 to avoid -inf warning in log function fft_amplitude[:, frame] = 2 * abs(fft_result[:n_fft // 2 + 1]) + 1e-16 # use log to suppress the amplitude fft_amplitude_log = np.log(fft_amplitude) # expect a4 tune to be 339 to 445, which is prior a4 = np.arange(439, 446) # a4 to g3: 2^(-14/12), a4 to c7: 2^(27/12) coefficient = np.power(2, np.arange(-14, 28) / 12) # here we use around to get closest frequency point mat = np.around(np.outer(a4, coefficient) / frequency_resolution).astype(int) # notice that score[0] for 339Hz, score[-1] is score[6] for 445Hz score = np.zeros(len(a4)) # set lower limit for amplitude, here just omit negative number # otherwise -inf can destroy the analysis min_amp = 0 # now sum up for each frequency for i in range(len(score)): aim = fft_amplitude_log[mat[i]] # here divide frame_number to normalize the score score[i] = aim[aim > min_amp].sum() / frame_number # avoid overflow in softmax score -= score.max() # use softmax to evaluate probability probability = np.exp(score) / np.exp(score).sum() # then output the result for i in range(len(probability)): print("{}Hz: {:.2f}%".format(a4[i], probability[i] * 100)) return
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))
def spectrogram(x, fs, fc, m=None, dbf=60): if not m: m = 1024 isreal_bool = np.isreal(x).all() lx = len(x) nt = (lx + m - 1) // m x = np.append(x, np.zeros(-lx + nt * m)) x = x.reshape((int(m / 2), nt * 2), order='F') x = np.concatenate((x, x), axis=0) x = x.reshape((m * nt * 2, 1), order='F') x = x[np.r_[m // 2:len(x), np.ones(m // 2) * (len(x) - 1)].astype(int)].reshape( (m, nt * 2), order='F') xmw = x * windows.hamming(m)[:, None] t_range = [0.0, lx / fs] if isreal_bool: f_range = [fc, fs / 2.0 + fc] xmf = np.fft.fft(xmw, len(xmw), axis=0) xmf = xmf[0:m / 2, :] else: f_range = [-fs / 2.0 + fc, fs / 2.0 + fc] xmf = np.fft.fftshift(np.fft.fft(xmw, len(xmw), axis=0), axes=0) f_range = np.linspace(*f_range, xmf.shape[0]) t_range = np.linspace(*t_range, xmf.shape[1]) h = xmf.shape[0] each = int(h * .10) xmf = xmf[each:-each, :] xmf = np.sqrt(np.power(xmf.real, 2) + np.power(xmf.imag, 2)) xmf = np.abs(xmf) xmf /= xmf.max() #throw away sides xmf = 20 * np.log10(xmf) xmf = np.clip(xmf, -dbf, 0) xmf = MinMaxScaler().fit_transform( StandardScaler(with_mean=True, with_std=True).fit_transform(xmf)) xmf = np.abs(xmf) #xmf-=np.median(xmf) xmf /= xmf.max() print(xmf.min(), xmf.max()) return f_range, t_range, xmf
def __init__(self, samples, classification): self.frame_size = len(samples) self.samples = np.array(samples) self.classification = classification self.prediction = 0 self.zcr = 0 self.ste = 0 self.full_band_energy = 0 self.hamming_window = hamming(self.frame_size) # vectors to plots self.classification_vector = [] self.prediction_vector = []
def wav_coefs_morceaux(nom_fichier, N= N, T= 0.01): """ Fonction pour faire la transformée de Fourier depuis un fichier :param nom_fichier: fichier .wav à lire :param N: nombre de coefficients de Fourier réels positifs voulus :param T: fenêtre temporelle pour la FFT (10ms par défaut) :return: T*(sample rate) listes de N coefficients (matrice 2D) """ fe, audio = read(nom_fichier) # on lit chaque fichier audio morceaux = np.array_split(audio, len(audio) // (fe * T)) # on coupe en 100 morceaux de taille a peu prs egale coefs = [] for morceau in morceaux: window = hamming(len(morceau)) coefs.append(np.abs(fft(morceau * window, N)[0:N // 2])) # partie réelle positive return coefs
def get_temporal_waveform2(Nt): Nt2 = Nt + np.random.randint(10) mod_lim = [0.4, 0.9] skip_chance = 0.8 sec_height = [0.0, 0.3] mod3_height = [0.0, 0.1] mod_max = np.random.uniform(mod_lim[0], mod_lim[1]) mod_max = int(mod_max * Nt) mod = windows.cosine(mod_max) if np.random.rand() < skip_chance: mod = mod[1:] N2 = Nt2 - mod.size height2 = np.random.uniform(sec_height[0], sec_height[1]) mod2 = np.ones(N2) * height2 height3 = np.random.uniform(mod3_height[0], mod3_height[1]) mod3 = height3 * windows.hamming(N2) mod2 += mod3 mod_upper = mod.copy() mod_upper[mod < height2] = height2 mod[mod_max // 2:] = mod_upper[mod_max // 2:] mod[mod.size - 1] = (mod[mod.size - 2] + height2) / 1.9 mod = np.hstack((0.0, mod, mod2)) x_stop = np.linspace(np.pi, -np.random.rand() * np.pi, np.random.randint(3, 7)) y_stop = (np.tanh(x_stop) + 1) / 2 y_stop = np.hstack([y_stop, np.zeros(np.random.randint(3))]) y_stop = np.hstack((np.ones(mod.size - y_stop.size), y_stop)) mod *= y_stop mod += np.random.uniform(0.0, 0.03) * np.random.standard_normal(mod.size) mod[0] = 0 # mod[np.random.randint(1,3)] += np.random.uniform(0.0, 3.0) t2 = np.cumsum(mod) t2 *= 2 * np.pi / t2[-1] t2 = t2[:Nt] return t2
def song_recipe(filename): """ Run the entire algorithm on a particular song :param filename: :return filtered_spectrogram_data: """ rate, audio_data = read_audio_file(filename) if audio_data.ndim != 1: # Checks no. of channels. Some samples are already mono audio_data = stereo_to_mono(audio_data) filtered_data = butter_lowpass_filter( audio_data, CUTOFF_FREQUENCY, DEFAULT_SAMPLING_RATE) decimated_data = downsample_signal( filtered_data, DEFAULT_SAMPLING_RATE // SAMPLING_RATE) hamming_window = hamming(SAMPLES_PER_WINDOW, sym=False) windows = apply_window_function( decimated_data, SAMPLES_PER_WINDOW, hamming_window) filtered_spectrogram_data = filter_spectrogram(windows, SAMPLES_PER_WINDOW) return filtered_spectrogram_data
def get_tachogram_power(ibi, sr): ws = sr * 20 if len(ibi) < ws + 1: raise SignalTooShortError(len(ibi)) else: nfft = max(256, 2**math.ceil(np.log2(ws))) f, pxx = welch(ibi, window=windows.hamming(ws), nfft=nfft, fs=sr, detrend=False) eps = np.finfo(float).eps lf = np.log(sum(pxx[np.flatnonzero((f > 0.01) & (f <= 0.08))]) + eps) mf = np.log(sum(pxx[np.flatnonzero((f > 0.08) & (f <= 0.15))]) + eps) hf = np.log(sum(pxx[np.flatnonzero((f > 0.15) & (f <= 0.5))]) + eps) tachogram_er = mf / (lf + hf) return lf, mf, hf, tachogram_er
def plot_spectrum(*, log=True, **signals): plt.title('Spectrum') plt.grid() plt.xlabel('Frequency [Hz]') plt.ylabel('Amplitude') if log: plt.yscale("log") plt.figure(1, (20, 10)) for name, s in signals.items(): N = int(samplerate * duration) window = hamming(len(s)) yf = fft((s - np.average(s)) * window) tf = np.linspace(.0, (len(s) / duration / 2), int(N / 2)) spectrum = 2. / N * np.abs(yf[0:N // 2]) plt.plot(tf, spectrum, label=name) plt.legend() plt.show()
def main(): if len(sys.argv)>1: fileName = sys.argv[1] else: fileName = None """ write_wav_test('wav_test.wav') wav2guitar_distortion('wav_test.wav') """ fileName = 'music.wav' with CPlotter(fileName) as plot,CAudioSource(fileName) as sound: FFTLEN = fft.next_fast_len(sound.blockLen,True) image_freq = fft.rfftfreq(FFTLEN,1./sound.fps) repeat = True while repeat!=False: data,repeat = sound.readData() w = hamming(len(data),False) image_fft = fft.rfft(data*w,FFTLEN) plot.replot(image_fft,image_freq,FFTLEN)
def get_psd(bvp, sr): ws = sr * 20 if len(bvp) < ws + 1: raise SignalTooShortError(len(bvp)) else: nfft = max(256, 2**math.ceil(np.log2(ws))) f, pxx = welch(bvp, window=windows.hamming(ws), nfft=nfft, fs=sr, detrend=False) pxx, eps = pxx / sum(pxx), np.finfo(float).eps sp0001 = np.log(sum(pxx[np.flatnonzero((f > 0) & (f <= 0.1))]) + eps) sp0102 = np.log(sum(pxx[np.flatnonzero((f > 0.1) & (f <= 0.2))]) + eps) sp0203 = np.log(sum(pxx[np.flatnonzero((f > 0.2) & (f <= 0.3))]) + eps) sp0304 = np.log(sum(pxx[np.flatnonzero((f > 0.3) & (f <= 0.4))]) + eps) sp_er = np.log( sum(pxx[np.flatnonzero(f < 0.08)]) / sum(pxx[np.flatnonzero((f > 0.15) & (f < 0.5))]) + eps) return sp0001, sp0102, sp0203, sp0304, sp_er
def get_fft_window(window_type, window_length): # Generate the window with the right number of points window = None if window_type == "Bartlett": window = windows.bartlett(window_length) if window_type == "Blackman": window = windows.blackman(window_length) if window_type == "Blackman Harris": window = windows.blackmanharris(window_length) if window_type == "Flat Top": window = windows.flattop(window_length) if window_type == "Hamming": window = windows.hamming(window_length) if window_type == "Hanning": window = windows.hann(window_length) # If no window matched, use a rectangular window if window is None: window = np.ones(window_length) # Return the window return window
def _plot_spectrum(fs, num_samples, signal): """ Plot time signal and frequency spectrum :param fs: Sampling rate of signal :param num_samples: Number of samples to analyze :param signal: Input signal :return: """ fig, (ax, ax2) = plt.subplots(2, figsize=(15, 8)) ax.plot(signal[:num_samples + 1], '-') sliced_signal = signal[:num_samples] hamming_window = hamming(num_samples) windowed_signal = sliced_signal * hamming_window complex_spectrum = fft(windowed_signal) magnitude_spectrum = np.abs(complex_spectrum[:(num_samples // 2)]) ax2.plot(magnitude_spectrum) # frequency_range = np.linspace(0, fs, num_samples) # ax2.plot(frequency_range, magnitude_spectrum, '-', lw=2) # ax2.set_xlim(0, fs / 2) plt.show()
def FFT(signal, sr): w = np.linspace(0, 2 * sr, len(signal)) f1 = 20 * np.log10(np.abs(fft(signal))) N = len(signal) w1 = windows.hann(N) w2 = windows.hamming(N) w3 = windows.blackman(N) f2 = 20 * np.log10(np.abs(fft(signal * w1))) f3 = 20 * np.log10(np.abs(fft(signal * w2))) f4 = 20 * np.log10(np.abs(fft(signal * w3))) fig, (ax0, ax1, ax2, ax3) = plt.subplots(nrows=4, sharex=True, constrained_layout=True) ax0.plot(w[0:len(signal) // 2], f1[0:len(f1) // 2]) ax0.set(title='FFT sin ventana', ylabel='dB') ax1.plot(w[0:len(signal) // 2], f2[0:len(f2) // 2]) ax1.set(title='FFT con ventana hann', ylabel='dB') ax2.plot(w[0:len(signal) // 2], f3[0:len(f3) // 2]) ax2.set(title='FFT con ventana hamming', ylabel='dB') ax3.plot(w[0:len(signal) // 2], f4[0:len(f4) // 2]) ax3.set(title='FFT con ventana blackman', ylabel='dB', xlabel='Frecuencia [Hz]') return fig
def toneProfileGen(s, wl, numtones, numsemitones, fmin, fmax, fratio, fs): """build the tone profiles for calculating note salience matrix each sinusoidal at frequency 'ftone' is generated via sin(2*pi*n*f/fs) the true frequency of the tone is supposed to lie on bin notenum*numsemitones-1, e.g. A4 is bin 49*numsemitones-1 = 146, C4 is bin 40*numsemitones-1 = 119 (note that notenum is not midinum, note num is the index of the key on an 88 key piano with A0 = 1) Mauch p.57""" w = hamming(wl) Ms, Mc = [], [] # simple and complex tone profiles for tone_id in range(numtones): f_tone = fmin * (pow(fratio, (tone_id - 1))) # frequency of current tone s_tone = sin_in_window(wl, f_tone, fs) * w.T c_tone = (pow(s, 0) * sin_in_window(wl, f_tone, fs) + pow(s, 1) * sin_in_window(wl, 2 * f_tone, fs) + pow(s, 2) * sin_in_window(wl, 3 * f_tone, fs) + pow(s, 3) * sin_in_window(wl, 4 * f_tone, fs)) * w.T fft_tone = fft(s_tone)[:int(wl / 2)] fft_ctone = fft(c_tone)[:int(wl / 2)] Ms.append(fft_tone) Mc.append(fft_ctone) return Ms, Mc
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()
def _update_canvas(self): """ Update the figure when the user changes and input value. :return: """ # Get the parameters from the form x_span = float(self.x_span.text()) y_span = float(self.y_span.text()) z_span = float(self.z_span.text()) nx_ny_nz = self.nx_ny_nz.text().split(',') self.nx = int(nx_ny_nz[0]) self.ny = int(nx_ny_nz[1]) self.nz = int(nx_ny_nz[2]) az_start_end = self.az_start_end.text().split(',') az_start = int(az_start_end[0]) az_end = int(az_start_end[1]) el_start_end = self.el_start_end.text().split(',') el_start = int(el_start_end[0]) el_end = int(el_start_end[1]) # Get the selected window from the form window_type = self.window_type.currentText() # Get the polarization from the form polarization = self.polarization.currentText() x = linspace(-0.5 * x_span, 0.5 * x_span, self.nx) y = linspace(-0.5 * y_span, 0.5 * y_span, self.ny) z = linspace(-0.5 * z_span, 0.5 * z_span, self.nz) self.x_image, self.y_image, self.z_image = meshgrid(x, y, z, indexing='ij') fft_length = 8192 # el 18 - 43 (-1) # az 66 - 115 (-1) # Initialize the image self.bp = 0 # Loop over the azimuth and elevation angles for el in range(el_start, el_end + 1): for az in range(az_start, az_end + 1): print('El {0:d} Az {1:d}'.format(el, az)) filename = '../../Backhoe_CP/3D_Challenge_Problem/3D_K_Space_Data/backhoe_el{0:03d}_az{1:03d}.mat'.format(el, az) b = loadmat(filename) # build a list of keys and values for each entry in the structure vals = b['data'][0, 0] # <-- set the array you want to access. keys = b['data'][0, 0].dtype.descr # Assemble the keys and values into variables with the same name as that used in MATLAB for i in range(len(keys)): key = keys[i][0] val = squeeze(vals[key]) exec(key + '=val', locals(), globals()) # Select the polarization if polarization == 'VV': signal = vv elif polarization == 'HH': signal = hh else: signal = vhhv sensor_az = radians(azim) sensor_el = radians(elev) frequency = FGHz * 1e9 nf = len(frequency) na = len(sensor_az) ne = len(sensor_el) coefficients = ones([nf, ne, na]) # Get the window if window_type == 'Hanning': h1 = hanning(nf, True) h2 = hanning(na, True) h3 = hanning(ne, True) for i in range(nf): for j in range(ne): for k in range(na): coefficients[i, j, k] = (h1[i] * h2[k] * h3[j]) ** (1.0 / 3.0) elif window_type == 'Hamming': h1 = hamming(nf, True) h2 = hamming(na, True) h3 = hamming(ne, True) for i in range(nf): for j in range(ne): for k in range(na): coefficients[i, j, k] = (h1[i] * h2[k] * h3[j]) ** (1.0 / 3.0) # Apply the window coefficients signal *= coefficients # Reconstruct the image self.bp += backprojection.reconstruct3(signal, sensor_az, sensor_el, self.x_image, self.y_image, self.z_image, frequency, fft_length) # Update the image self._update_image_only()
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()
def _update_canvas(self): """ Update the figure when the user changes and input value. :return: """ # Get the parameters from the form x_span = float(self.x_span.text()) y_span = float(self.y_span.text()) nx_ny = self.nx_ny.text().split(',') nx = int(nx_ny[0]) ny = int(nx_ny[1]) az_start_end = self.az_start_end.text().split(',') az_start = float(az_start_end[0]) az_end = float(az_start_end[1]) # Load the selected target target = self.target.currentText() base_path = Path(__file__).parent if target == 'Backhoe Elevation 0': b = loadmat(base_path / "backhoe_0.mat") elif target == 'Backhoe Elevation 30': b = loadmat(base_path / "backhoe_30.mat") elif target == 'Camry Elevation 30': b = loadmat(base_path / "Camry_el30.0000.mat") elif target == 'Camry Elevation 40': b = loadmat(base_path / "Camry_el40.0000.mat") elif target == 'Camry Elevation 50': b = loadmat(base_path / "Camry_el50.0000.mat") elif target == 'Camry Elevation 60': b = loadmat(base_path / "Camry_el60.0000.mat") elif target == 'Tacoma Elevation 30': b = loadmat(base_path / "ToyotaTacoma_el30.0000.mat") elif target == 'Tacoma Elevation 40': b = loadmat(base_path / "ToyotaTacoma_el40.0000.mat") elif target == 'Tacoma Elevation 50': b = loadmat(base_path / "ToyotaTacoma_el50.0000.mat") elif target == 'Tacoma Elevation 60': b = loadmat(base_path / "ToyotaTacoma_el60.0000.mat") elif target == 'Jeep Elevation 30': b = loadmat(base_path / "Jeep99_el30.0000.mat") elif target == 'Jeep Elevation 40': b = loadmat(base_path / "Jeep99_el40.0000.mat") elif target == 'Jeep Elevation 50': b = loadmat(base_path / "Jeep99_el50.0000.mat") elif target == 'Jeep Elevation 60': b = loadmat(base_path / "eep99_el60.0000.mat") # Build a list of keys and values for each entry in the structure vals = b['data'][0, 0] keys = b['data'][0, 0].dtype.descr # Assemble the keys / values into variables with the same name as used in MATLAB for i in range(len(keys)): key = keys[i][0] val = squeeze(vals[key]) exec(key + '=val', locals(), globals()) # Set up the image space self.xi = linspace(-0.5 * x_span, 0.5 * x_span, nx) self.yi = linspace(-0.5 * y_span, 0.5 * y_span, ny) x_image, y_image = meshgrid(self.xi, self.yi) z_image = zeros_like(x_image) # Set the data from the file polarization = self.polarization.currentText() if polarization == 'VV': signal = vv elif polarization == 'HH': signal = hh else: signal = hv # Choose the pulses in the azimuth range sensor_az = [] index = [] i = 0 for az in azim: if az_start <= az <= az_end: sensor_az.append(radians(az)) index.append(i) i += 1 signal1 = signal[:, index] sensor_el = radians(elev) * ones(len(sensor_az)) frequency = FGHz * 1e9 nf = len(frequency) na = len(sensor_az) fft_length = next_fast_len(4 * len(frequency)) # Get the selected window from the form window_type = self.window_type.currentText() if window_type == 'Hanning': h1 = hanning(nf, True) h2 = hanning(na, True) coefficients = sqrt(outer(h1, h2)) elif window_type == 'Hamming': h1 = hamming(nf, True) h2 = hamming(na, True) coefficients = sqrt(outer(h1, h2)) elif window_type == 'Rectangular': coefficients = ones([nf, na]) # Apply the selected window signal1 *= coefficients # Reconstruct the image self.bp_image = backprojection.reconstruct2(signal1, sensor_az, sensor_el, x_image, y_image, z_image, frequency, fft_length) # Update the image self._update_image_only()
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()
fft_wave_complex = np.zeros((ch_number,all_sample_number,extraction_freq),dtype="complex128") """ f = fft(data_x[0][0]) g = fftfreq(n=data_x[0][0].size, d=1/sampling_freq) print(f.shape) print(g.shape) """ #窓関数処理 N = extraction_freq #データ数 #ハニング窓 #hanning_window = windows.hann(N) hanning_window = np.hanning(N) #ハミング窓 hamming_window = windows.hamming(N) #ブラックマン窓 black_window = windows.blackmanharris(N) """ plt.plot(x,hanning_window) plt.plot(x,hamming_window) plt.plot(x,black_window) plt.show() """ a = 0 plt.plot(x,data_x[0][a]) plt.show() data_x *= hanning_window
def calc_residual(x,x_lpc,ord_lpc,GCI): # Function to carry out LPC analysis and inverse filtering, used in IAIF.m # function. # USAGE: # Input: # x : signal to be inverse filtered # x_lpc : signal to carry out LPC analysis on # ord_lpc : LPC prediction order # GCI : Glottal closure instants (in samples) # # Output: # vector_res : residual after inverse filtering # # ######################################################################### ## Function Coded by John Kane @ The Phonetics and Speech Lab ########### ## Trinity College Dublin, August 2012 ################################## ######################################################################### ######################################################################### ## Function transalated to Python by J. C. Vasquez-Correa @ University of Erlangen-Nuremberg ########### ######################################################################### vector_res=np.zeros(len(x)) ze_lpc=np.zeros(ord_lpc) ar_lpc=np.zeros((ord_lpc+1, len(GCI))) e_lpc=np.zeros((ord_lpc+1, len(GCI))) for n in range(len(GCI)-1): if n>1: T0_cur=GCI[n]-GCI[n-1] else: T0_cur=GCI[n+1]-GCI[n] if GCI[n]-T0_cur>0 and GCI[n]+T0_cur<=len(x) and T0_cur>0: start=int(GCI[n]-T0_cur) stop=int(GCI[n]+T0_cur) frame_lpc=x_lpc[start:stop] if len(frame_lpc)>ord_lpc*1.5: frame_wind=frame_lpc*hamming(len(frame_lpc)) ar,e=lpcauto(frame_wind, ord_lpc) ar_par=np.real(ar) #ar_par[0]=1 ar_lpc[:,n]=ar_par # inverse filtering try: if n>1 and ('frame_res' in locals()) and ('residual' in locals()): last_input=frame_res[::-1] last_output=residual[::-1] ze_lpc=lfiltic(ar_par, np.sqrt(e), last_output, last_input) frame_res=x[start:stop] residual=lfilter(b=ar_par,a=np.sqrt(e), x=frame_res, zi=ze_lpc) except: residual=[frame_res] residual_win=residual[0]*hamming(len(residual[0])) vector_res[start:stop]=vector_res[start:stop]+residual_win return vector_res
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