def detect_coughs( file='sounds/samples/vi95kMQ65UeU7K1wae12D1GUeXd2/sample-1613658921823.m4a' ): # Replace the below random code with something meaningful which # generates a one-column dataframe with a column named "peak_start" y, sr = librosa.load(file) # sr is the sampling rate N = y.shape[0] # N is number of samples yf = rfft(y) xf = rfftfreq(N, 1 / sr) # Going to frequency domain points_per_freq = len(xf1) / (sr / 2) target_idx_100 = int(points_per_freq * 100) target_idx_2000 = int(points_per_freq * 2000) # Removing all frequencies except 100-2000 Hz, as this is the typical range of frequencies for a cough from an adult. # Reference: https://pubmed.ncbi.nlm.nih.gov/12666872/ yf[:target_idx_100 + 1] = 0 yf[target_idx_2000 - 1:] = 0 new_sig = irfft(yf) # Going back to time domain with filtered signal peaks_array = find_peaks( new_sig, prominence=0.02 )[0] #Finding start of peaks in filtered signal, should correspond to coughs peaks = peaks_array / sr # The time instant of starting of peak is arrived at by dividing by sampling rate out = pd.DataFrame({'peak_start': peaks}) return (out)
def filter_sinogram(sinogram, filter_name, degree=None): """ Filter a sinogram for FBP reconstruction. Parameters ---------- sinogram : numpy.ndarray The raw sinogram. filter_name : str Type of filter, one of: ['None', 'Ram-Lak', 'Shepp-Logan', 'Cosine']. degree : int, optional Degree of the filter, when applicable, by default None Returns ------- numpy.ndarray The filtered sinogram. """ length = sinogram.shape[1] n = fft_size(length) filter_f, pre_filter = get_filter(n, filter_name, degree) filtered = fft.rfft(sinogram, n, axis=1) filter_f = make_broadcastable(filter_f[np.newaxis, ...], filtered) filtered *= filter_f filtered = fft.irfft(filtered, axis=1, overwrite_x=True) return filtered[:, :length], pre_filter
def lookForPeriodic(self, startMonth, months, harmonicThreshold): excerpt = self.columnData[startMonth:startMonth + months] dateExcerpts = self.dates[startMonth:startMonth + months] avg = np.mean(excerpt) normalisedExcerpt = excerpt - avg predictionSpectrum = self.plotHarmonicModels(harmonicThreshold, months, normalisedExcerpt) prediction = fft.irfft(predictionSpectrum) testLengthFactor = 2 # expressed as number of times the excerpt length totalLength = (testLengthFactor + 1) * months trueSignal = self.columnData[:totalLength] - avg periodic_prediction = np.tile(prediction, testLengthFactor + 1) plt.figure() plt.plot(trueSignal, label='true signal') excerptMonths = range(startMonth, startMonth + len(normalisedExcerpt)) plt.plot(excerptMonths, normalisedExcerpt, label='used excerpt') # self.dates, periodic_prediction[0:len(self.dates)], plt.plot(periodic_prediction, label='periodic prediction') plt.legend(loc='upper left') plt.grid() plt.xlabel("Months since 1871") plt.show() unseenData = trueSignal[months:] predictData = periodic_prediction[-len(unseenData):] rmse = np.sqrt(np.mean(np.power(unseenData - predictData, 2))) print(rmse)
def spectro_range(data, min, max): ft = rfft(data) begin_index = int((len(ft)) * min) end_index = int((len(ft)) * max) ft[0:begin_index] = 0 ft[end_index:len(ft)] = 0 output_signal = irfft(ft) return output_signal
def circ_convolve(signal1, signal2, num_points=None): samples1, samples2 = get_both_samples(signal1, signal2) if num_points == None: num_points = len(signal1) conv_samples = fft.irfft( fft.rfft(samples1, num_points) * fft.rfft(samples2, num_points)) # conv_samples = signal.convolve(signal1, np.concatenate([signal2, signal2]), mode='same') return same_type_as(conv_samples, signal1)
def test_identity(self): maxlen = 512 x = random(maxlen) + 1j*random(maxlen) xr = random(maxlen) for i in range(1,maxlen): assert_array_almost_equal(fft.ifft(fft.fft(x[0:i])), x[0:i], decimal=12) assert_array_almost_equal(fft.irfft(fft.rfft(xr[0:i]),i), xr[0:i], decimal=12)
def _omit_band_profiles(self, x, band_profiles): if self.patch_spectrum is None: raise ValueError( "This FreqDicePatchOmitter has no concrete patch_spectrum. " "Have you maybe forgotten to pass in X_bg?") spectra = np.tile(rfft(x), (len(band_profiles), 1)) replace_zero_slices(self.freq_slicing, self.patch_slices, self.patch_strat, spectra, band_profiles) return irfft(spectra)
def deprocess(data): new_samples = [] first = irfft(data[0]) print(len(first), len(data[0])) # First sample to append: new_samples = np.concatenate((new_samples, first)) samp_size = len(new_samples) print(samp_size - f_offset) lim = len(data) for i in range(1, lim): aud_data = irfft(data[i]) merge = aud_data[0:samp_size - f_offset] plot = merge x = np.arange(len(plot)) if(i == lim//2): plt.plot(x, plot) plt.plot(x, new_samples[(f_offset * i):(f_offset * (i-1) + samp_size)]) print((f_offset * i)/44100) coeff_step = 1/(len(merge) + 1) for j in range(len(merge)): val = (1 - ((j + 1) * coeff_step)) * new_samples[(f_offset * i) + j] + ((j + 1) * coeff_step * merge[j]) new_samples[(f_offset * i) + j] = val if(i == lim//2): plt.plot(x, new_samples[(f_offset * i):(f_offset * (i-1) + samp_size)]) plt.title("t = " + str((f_offset * i)/44100)) plt.savefig("latest_plot.png") non_merge = aud_data[samp_size - f_offset: samp_size] print(non_merge[0]/new_samples[-1], new_samples[-1]/new_samples[-2]) new_samples = np.concatenate((new_samples, non_merge)) if(i == 1): print(new_samples) return new_samples
def noise1d(NW, FALLOFF_LENGTH, FALLOFF_MIN): stutter_noise = np.random.normal(size=NW) stutter_spect = fft.rfft(stutter_noise) freqs = fft.fftfreq(NW)[:NW // 2 + 1][1:-2] stutter_spect_filtered = stutter_spect.copy() stutter_spect_filtered[1:-2] = stutter_spect[1:-2] * ( (freqs).min() / freqs**2) falloff = np.tanh(FALLOFF_LENGTH * np.arange(NW // 2 - 2) + FALLOFF_MIN) stutter_spect_filtered[1:-2] *= falloff stutter_filtered = fft.irfft(stutter_spect_filtered)[::NW // W] stutter_filtered /= abs(stutter_filtered).max() return stutter_filtered
def fourier(data, gain): signal = np.array(10 * [None]) new_magnitudes = [] data = np.array(data) ft = rfft(data) Magnitudes = np.abs(ft) k, m = divmod(len(Magnitudes), 10) for i in range(10): signal[i] = Magnitudes[i * k + min(i, m):(i + 1) * k + min(i + 1, m)] signal[i] = signal[i] * gain[i] new_magnitudes = new_magnitudes + list(signal[i]) new_magnitudes = np.array(new_magnitudes) modified = np.multiply(new_magnitudes, np.exp(1j * np.angle(ft))) output_signal = irfft(modified) return output_signal, Magnitudes
def playsound(self,v): global soundout f0=int(self.vrootf.getValue()) nsam2=8*44100//(2*f0) # 8x oversampling so high fundamental frequencies come out closer to correct print(f"play: {f0} ({nsam2})") svals=np.zeros_like(self.svals,shape=nsam2) if len(self.svals)>=nsam2//8: svals[::8]=self.svals[:(nsam2-1)//8+1] # interleave zeros for 8 repetitions of the wave. Gives better frequency accuracy at high frequency else: svals[:len(self.svals)*8:8]=self.svals # svals=self.svals.copy() # svals.resize(nsam2) # if len(self.svals)<nsam2: svals[len(self.svals):]=0.0 # zero fill if we extended the array total=fft.irfft(svals)*(len(svals)-1)*10000.0 self.assound=np.tile(total.astype("int16"),44100//nsam2) #print nsam2,len(self.svals),len(svals),len(total) initsound() soundout.start() soundout.write(self.assound) soundout.stop()
def update(i): if i: p_hat[:] = np.dot(Ad, p_hat) p = fft.irfft(p_hat[:(1 + args.Nx // 2)], norm='ortho') else: p = 1 + 0.6 * np.random.rand(x.size) p[np.abs(x + args.width / 2) >= 1] = 0 p_hat[:] = fft.fft(p, norm='ortho') line_0.set_ydata(p) line_t.set_ydata(p) timestamps[1:] = timestamps[:-1] timestamps[0] = time.time() dt = np.mean(timestamps[:-1] - timestamps[1:]) print(f'[{i:6d}/{Nt:6d}] Average FPS = {1 / dt:.4f}', end='\r') return [line_t, line_0]
def setSignal(self, t, u, dt): self.t = t self.u = u self.dt = dt self.t_phi_kernel = np.arange(-self.t[-1]/2, self.t[-1]/2 + self.dt, self.dt) if(self.t_phi_kernel.shape[0] > self.t.shape[0]): self.t_phi_kernel = self.t_phi_kernel[:-1] self.psi_kernel = rcosFilter(self.t_phi_kernel, self.gamma, self.Ts) self.phi_kernel = closedPhiFromRcos(self.t_phi_kernel, self.gamma, self.Ts, self.alpha) u_fourier = fft(u) ffreq = fftfreq(len(t), dt) mult = 2 * np.pi * ffreq * 1j + self.alpha v_fourier = u_fourier / mult self.v = irfft(v_fourier, len(t)) self.w_0 = self.v[0] self.status = Status.HAS_SIGNAL
def correct_signal(self, time, signal, tmin=None, tmax=None, r0=5e-2, correction="bassetbound", window="blackmanharris", impedance=None): if tmin is None: tmin =time[0] if tmax is None: tmax = time[-1] dt = time[1] - time[0] mask = np.logical_and(time>tmin, time<tmax) sig = signal[mask] t = time[mask] signal_length = len(sig) freq = rfftfreq(signal_length, dt)[1:] amp = getattr(self, f"amplitude_ratio_{correction}")(freq) phase = getattr(self, f"phase_{correction}")(freq) if impedance is None: impedance = np.ones_like(amp) else: impedance = getattr(self, f"{impedance}_impedance")(freq, r0) response = amp * np.exp(1j * phase) / impedance response = np.r_[1, response] win = get_window(window, signal_length) corrected_signal = irfft(rfft(sig * win) / response, n=signal_length) return TimeSeries(corrected_signal, t, name="Corrected")
def min_phase_conversion(self, HRIR, HRIR_length, index): ''' :param HRIR: the desired HRIR impulse response to convert into minimum phase :return: the minimum phase version of the original HRIR ''' HRIR_fft = fft(HRIR, 44100) #Check here the damned exception try: minimum_phase = np.imag(-hilbert(np.log(np.abs(HRIR_fft)))) except: print('error log zero \n') print('Printing HRIR spectrum: \n') print(HRIR_fft) min_phase_HRIR = irfft( np.abs(HRIR_fft) * np.exp(1j * minimum_phase), 44100) # |H(w)|*e^(jPhi(w)) min_phase_HRIR = min_phase_HRIR[0:HRIR_length] return min_phase_HRIR
def recompute(self,value=None): nsin=int(self.vnsin.getValue()) cell=int(self.vcell.getValue()) ncells=int(self.vncells.getValue()) oversamp=max(1,int(self.voversamp.getValue())) samples=int(cell*oversamp) # arrays since we're using them several ways self.svals=np.array([cmath.rect(self.wamp[i].getValue(),self.wpha[i].getValue()*pi/180.0) for i in range(nsin+1)]) #self.wamps=np.array([v.getValue() for v in self.wamp[:nsin+1]]) #self.wphas=np.array([v.getValue() for v in self.wpha[:nsin+1]]) self.xvals=np.array([xn/float(oversamp) for xn in range(samples)]) if samples//2>len(self.svals): svals=np.concatenate((self.svals,np.zeros(1+samples//2-len(self.svals)))) else: svals=self.svals self.total=fft.irfft(svals)*(len(svals)-1) if ncells>1: self.total=np.tile(self.total,ncells) self.synthplot.set_data((np.arange(0,len(self.total)/oversamp,1.0/oversamp),self.total),"Sum",replace=True,quiet=True,linewidth=2) if not self.targfn is None: self.synthplot.set_data((np.arange(len(self.targfn)),self.targfn),"Target",quiet=True,linewidth=1,linetype=2,symtype=0) # if self.cbshowall.isChecked() : # csum=self.total["minimum"]*1.1 # for i in range(nsin): # if self.wamps[i]==0: continue # csum-=self.wamps[i]*1.1 # if self.cbshifted.isChecked() : self.curves[i].add(csum) # self.synthplot.set_data((self.xvals,self.curves[i].get_data_as_vector()),"%d"%i,quiet=True,linewidth=1,color=2) # csum-=self.wamps[i]*1.1 self.synthplot.updateGL() self.fftplot.set_data((np.arange(len(self.svals)),np.abs(self.svals)),"Amp",color=0,linetype=0,linewidth=2) self.fftplot.set_data((np.arange(len(self.svals)),np.angle(self.svals)),"Pha",color=1,linetype=0,linewidth=2) self.fftplot.updateGL()
def test_irfft(self): x = random(30) assert_array_almost_equal(x, fft.irfft(fft.rfft(x))) assert_array_almost_equal( x, fft.irfft(fft.rfft(x, norm="ortho"), norm="ortho"))
def test_dtypes(self, dtype): # make sure that all input precisions are accepted x = random(30).astype(dtype) assert_array_almost_equal(fft.ifft(fft.fft(x)), x) assert_array_almost_equal(fft.irfft(fft.rfft(x)), x) assert_array_almost_equal(fft.hfft(fft.ihfft(x), len(x)), x)
# Equivalent to 400Hz * frequency resolution (i.e. 0.2) highest_freq_i = np.argmax(np.abs(yf)) # Since there is no spectrum leakage, the frequencies around the peaks are significantly attenuated print("Frequencies around the highest frequency bin") print(np.abs(yf)[highest_freq_i-1:highest_freq_i+2]) # Set the highest frequency to zero so that we can find the second highest frequency yf_no_highest = copy(np.abs(yf)) yf_no_highest[highest_freq_i] = 0 # idx of the 4000Hz noise, which has the second highest amplitude # Equivalent to 400Hz * frequency resolution (i.e. 0.2) second_highest_freq_i = np.argmax(yf_no_highest) yf[second_highest_freq_i - 1: second_highest_freq_i + 2] = 0 # plt.plot(xf, np.abs(yf)) # plt.show() """ Applying the Inverse FFT """ clean_tone = fft.irfft(yf) # plt.plot(clean_tone[:1000]) # plt.show() # Normalize and convert the tone to int26 for exporting WAV file normalized_tone = np.int16((clean_tone / clean_tone.max()) * 32767) # Export WAV file sp_io_wav.write("clean_tone.wav", SAMPLE_RATE, normalized_tone)
def test_irfft(self): x = random(30) assert_array_almost_equal(x, fft.irfft(fft.rfft(x))) for norm in ["backward", "ortho", "forward"]: assert_array_almost_equal( x, fft.irfft(fft.rfft(x, norm=norm), norm=norm))
yf = rfft(normalized_tone) xf = rfftfreq(N, 1 / SAMPLE_RATE) plt.plot(xf, np.abs(yf)) plt.xlabel('Frecuencia') plt.title('Calculado solo la mitad positiva') print('FFT más rápida calculado solo la mitad positiva con rfft() ') plt.show() # Filtrando la señal # The maximum frequency is half the sample rate points_per_freq = len(xf) / (SAMPLE_RATE / 2) # Our target frequency is 4000 Hz target_idx = int(points_per_freq * 4000) yf[target_idx - 1:target_idx + 2] = 0 plt.plot(xf, np.abs(yf)) plt.xlabel('Frecuencia') plt.title('Filtrado frecuencias de ruido') plt.show() # FFT Inversa new_sig = irfft(yf) plt.plot(new_sig[:1000]) plt.xlabel('Tiempo') plt.ylabel('Amplitud') plt.title('Resultado de aplicar FFT inversa') plt.show() # Generando audio filtrado (limpio) norm_new_sig = np.int16(new_sig * (32767 / new_sig.max())) write_wav(os.path.join(BASE_DIR, 'signal_filtered.wav'), SAMPLE_RATE, norm_new_sig)
def get_cepstrum(function): spectrum = rfft(function) return irfft(np.abs(spectrum))
def dpss_windows(N, half_nbw, Kmax, low_bias=True, interp_from=None, interp_kind='linear'): """Compute Discrete Prolate Spheroidal Sequences. Will give of orders [0,Kmax-1] for a given frequency-spacing multiple NW and sequence length N. .. note:: Copied from NiTime. Parameters ---------- N : int Sequence length. half_nbw : float Standardized half bandwidth corresponding to 2 * half_bw = BW*f0 = BW*N/dt but with dt taken as 1. Kmax : int Number of DPSS windows to return is Kmax (orders 0 through Kmax-1). low_bias : bool Keep only tapers with eigenvalues > 0.9. interp_from : int (optional) The dpss can be calculated using interpolation from a set of dpss with the same NW and Kmax, but shorter N. This is the length of this shorter set of dpss windows. .. note:: If SciPy 1.1 or greater is available, interpolating is likely not necessary as DPSS computations should be sufficiently fast. interp_kind : str (optional) This input variable is passed to scipy.interpolate.interp1d and specifies the kind of interpolation as a string ('linear', 'nearest', 'zero', 'slinear', 'quadratic, 'cubic') or as an integer specifying the order of the spline interpolator to use. Returns ------- v, e : tuple, The v array contains DPSS windows shaped (Kmax, N). e are the eigenvalues. Notes ----- Tridiagonal form of DPSS calculation from :footcite:`Slepian1978`. References ---------- .. footbibliography:: """ from scipy import interpolate from scipy.fft import rfft, irfft from scipy.signal.windows import dpss as sp_dpss from ..filter import next_fast_len # This np.int32 business works around a weird Windows bug, see # gh-5039 and https://github.com/scipy/scipy/pull/8608 Kmax = np.int32(operator.index(Kmax)) N = np.int32(operator.index(N)) W = float(half_nbw) / N nidx = np.arange(N, dtype='d') # In this case, we create the dpss windows of the smaller size # (interp_from) and then interpolate to the larger size (N) if interp_from is not None: if interp_from > N: e_s = 'In dpss_windows, interp_from is: %s ' % interp_from e_s += 'and N is: %s. ' % N e_s += 'Please enter interp_from smaller than N.' raise ValueError(e_s) dpss = [] d, e = dpss_windows(interp_from, half_nbw, Kmax, low_bias=False) for this_d in d: x = np.arange(this_d.shape[-1]) tmp = interpolate.interp1d(x, this_d, kind=interp_kind) d_temp = tmp( np.linspace(0, this_d.shape[-1] - 1, N, endpoint=False)) # Rescale: d_temp = d_temp / np.sqrt(sum_squared(d_temp)) dpss.append(d_temp) dpss = np.array(dpss) else: dpss = sp_dpss(N, half_nbw, Kmax) # Now find the eigenvalues of the original spectral concentration problem # Use the autocorr sequence technique from Percival and Walden, 1993 pg 390 # compute autocorr using FFT (same as nitime.utils.autocorr(dpss) * N) rxx_size = 2 * N - 1 n_fft = next_fast_len(rxx_size) dpss_fft = rfft(dpss, n_fft) dpss_rxx = irfft(dpss_fft * dpss_fft.conj(), n_fft) dpss_rxx = dpss_rxx[:, :N] r = 4 * W * np.sinc(2 * W * nidx) r[0] = 2 * W eigvals = np.dot(dpss_rxx, r) if low_bias: idx = (eigvals > 0.9) if not idx.any(): warn('Could not properly use low_bias, keeping lowest-bias taper') idx = [np.argmax(eigvals)] dpss, eigvals = dpss[idx], eigvals[idx] assert len(dpss) > 0 # should never happen assert dpss.shape[1] == N # old nitime bug return dpss, eigvals
t = np.arange(0, npts/samprate, 1/samprate) return t # Grafico de señal y su envolvente def graf_env(envolvente_num,st_dom_time_num,label): a = plt.plot(dates, envolvente_num,'k:', label="envolvente") b = plt.plot(dates, st_dom_time_num[1], 'k', label=label) plt.xticks(size=7) plt.yticks(size=7) plt.legend(fontsize=7) plt.xlabel("date: 2020-03-04", size=7) return a, b # BP e/ 0.5 - 1.5 Hz dom_time_01 = irfft(fft_01,n=len(evento)) # cálculo de la transformada inversa (parte real) # cambio el tipo de variable st_dom_time_01 = new_st(dom_time_01) t_01 = vec_tiempo(st_dom_time_01) # cálculo de la envolvente envolvente_01 = obspy.signal.filter.envelope(st_dom_time_01[1].data) # Grafico de señal y su envolvente plt.subplot(4, 2, 1) graf_env(envolvente_01,st_dom_time_01,"señal con BP 0.5 - 1.5 Hz") #---------------------------- # BP e/ 1.0 - 2.0 Hz
def istft(X, tstep=None, Tx=None): """ISTFT Inverse Short-Term Fourier Transform using a sine window. Parameters ---------- X : array, shape (..., wsize / 2 + 1, n_step) The STFT coefficients for positive frequencies. tstep : int Step between successive windows in samples (must be a multiple of 2, a divider of wsize and smaller than wsize/2) (default: wsize/2). Tx : int Length of returned signal. If None Tx = n_step * tstep. Returns ------- x : array, shape (Tx,) Array containing the inverse STFT signal. See Also -------- stft """ # Errors and warnings from scipy.fft import irfft X = np.asarray(X) if X.ndim < 2: raise ValueError(f'X must have ndim >= 2, got {X.ndim}') n_win, n_step = X.shape[-2:] signal_shape = X.shape[:-2] if n_win % 2 == 0: raise ValueError('The number of rows of the STFT matrix must be odd.') wsize = 2 * (n_win - 1) if tstep is None: tstep = wsize / 2 if wsize % tstep: raise ValueError('The step size must be a divider of two times the ' 'number of rows of the STFT matrix minus two.') if wsize % 2: raise ValueError('The step size must be a multiple of 2.') if tstep > wsize / 2: raise ValueError('The step size must be smaller than the number of ' 'rows of the STFT matrix minus one.') if Tx is None: Tx = n_step * tstep T = n_step * tstep x = np.zeros(signal_shape + (T + wsize - tstep, ), dtype=np.float64) if np.prod(signal_shape) == 0: return x[..., :Tx] # Defining sine window win = np.sin(np.arange(.5, wsize + .5) / wsize * np.pi) # win = win / norm(win); # Pre-processing for edges swin = np.zeros(T + wsize - tstep, dtype=np.float64) for t in range(n_step): swin[t * tstep:t * tstep + wsize] += win**2 swin = np.sqrt(swin / wsize) for t in range(n_step): # IFFT frame = irfft(X[..., t], wsize) # Overlap-add frame *= win / swin[t * tstep:t * tstep + wsize] x[..., t * tstep:t * tstep + wsize] += frame # Truncation x = x[..., (wsize - tstep) // 2:(wsize - tstep) // 2 + T + 1] x = x[..., :Tx].copy() return x
try: sampling_rate, input_clip = wavfile.read(fn) if sampling_rate != 44100: # sampling frequency of all files are made same input_clip = signal.resample(input_clip, int(len(input_clip) * 44100 / sampling_rate)) sampling_rate = 44100 clip_len = len(input_clip) time_points = np.linspace(0, len(input_clip) / sampling_rate, clip_len) fourier = fft.rfft(input_clip) # rfft used since we have real valued functions here fourier_freqs = fft.rfftfreq(clip_len, 1.0 / sampling_rate) pgram = np.zeros((numfrex, clip_len)) # empty matrix to hold the periodogram for i in range(numfrex): x = fourier_freqs - pgram_freq_range[i] fx = np.exp(-.5 * ((x / s) ** 2)) fx = fx / np.abs(max(fx)) filtered_sig = np.real(fft.irfft(fourier * fx)) hbert = abs(signal.hilbert(filtered_sig)) ** 2 pgram[i, :] = 10 * np.log10(hbert) fig, ax = plt.subplots(1, 1, figsize=(2.9, 2.92)) # to get a 224 by 224 image ax.axis('off') p = ax.pcolormesh(time_points, pgram_freq_range, pgram, cmap=plt.cm.cubehelix, shading='auto') fig.patch.set_visible(False) plt.savefig(pgram_file, bbox_inches='tight', pad_inches=0) # steps below are for memory use management ax.cla() fig.clear() plt.close("all") del pgram, p gc.collect()
# - print((fLO - 250e6) / 10000, (fLO + 250e6) / 10000) print(f[2640000], f[2790000]) N = 2790000 - 2640000 print(N) fNoise = np.zeros(len(f), dtype=np.cdouble) # + sigma = getNoiseSigma(4, 50, 1500e6) #4K, 50Ohm and 1500MHz noiseScale = sigma * np.sqrt(N / 2) fNoise[2640000:2790000] = np.random.normal( scale=noiseScale, size=N) + 1j * np.random.normal(scale=noiseScale, size=N) justNoise = irfft(fNoise) print(justNoise) # + fig, ax = plt.subplots(facecolor='w') print(np.log10(fs), np.log10(1e9)) f, Pxx_den = signal.periodogram(theSignal, fsFine) ax.semilogy(f, Pxx_den, label="Raw Signal (no noise)", alpha=0.5) f, Pxx_den = signal.periodogram(justNoise, fsFine) ax.semilogy(f, Pxx_den, label="Just Noise (no signal)", alpha=0.5) f, Pxx_den = signal.periodogram(mixedSignal, fsFine) ax.semilogy(f, Pxx_den, label="Mixed Signal (no noise)", alpha=0.5) f, Pxx_den = signal.periodogram(sigPlusNoise, fsFine) ax.semilogy(f, Pxx_den, label="Mixed Signal (with noise)", alpha=0.5) ax.legend(loc='upper right', prop={'size': 6})
def stft_to_mcep(S, M=24, alpha=0.42, n_iter=10, tol=1e-4, eps=0, sr=None): """Calculate mel-cepstral coefficients from a magnitude spectrogram. Parameters ---------- S : array-like [shape=(1 + n_fft / 2,) or (1 + n_fft / 2, T), non-negative] Input linear magnitude spectrogram. M : int >= 0 [scalar] Order of mel-cepstral coefficients. alpha : float in (-1, 1) [scalar] Frequency warping factor. n_iter : int >= 0 [scalar] Number of iterations of Newton-Raphson method. tol : float >= 0 [scalar]: Relative tolerance. eps : float >= 0 [scalar] A very small value added to periodogram to avoid NaN caused by log(). sr : float > 0 [scalar] Sampling rate in Hz. If not None, given alpha is overwritten with appropriate one computed by a simple algorithm. Returns ------- mc : np.ndarray [shape=(M + 1, T)] M-th order mel-cesptral coefficients. Notes ----- This implementation is based on an unpublished paper. See also -------- mcep_to_stft : Convert mel-cepstral coefficients to spectrum. horoscopy.utils.sr_to_alpha : Find appropriate alpha. """ # Perform coefficients frequency transform. def tilde(x, M, alpha): if 'A' not in dir(tilde): m = x.shape[0] tilde.A = np.zeros((M, m)) tilde.A[0, 0] = 1 if 1 < M: tilde.A[1:, 0] = (-alpha) ** np.arange(1, M) if 1 < M and 1 < m: tilde.A[1, 1:] = alpha ** np.arange(m - 1) * (1 - alpha * alpha) for i in range(2, M): i1 = i - 1 for j in range(1, m): j1 = j - 1 tilde.A[i, j] = (tilde.A[i1, j1] + alpha * (tilde.A[i, j1] - tilde.A[i1, j])) return np.matmul(tilde.A, x) S = _asarray(S) if S.ndim == 1: is_vector_input = True S = np.expand_dims(S, axis=-1) elif S.ndim == 2: is_vector_input = False else: raise ValueError('Input S must be 2-D matrix or 1-D vector') if S.shape[0] <= 1: raise ValueError('S.shape[0] must be greater than 1') if M < 0: raise ValueError('Order M must be a non-negative integer') if n_iter < 0: raise ValueError('Number of iterations must be a non-negative integer') if tol < 0: raise ValueError('Relative tolerance must be a non-negative number') if eps < 0: raise ValueError('Value eps must be a non-negative number') if sr is not None: alpha = sr_to_alpha(sr) check_alpha(alpha) n_fft = 2 * (S.shape[0] - 1) h_fft = n_fft // 2 L = M + 1 # Compute (-a)^0, (-a)^1, (-a)^2, ..., (-a)^M. a = np.expand_dims((-alpha) ** np.arange(L), axis=-1) # Compute log periodogram. log_I = 2 * np.log(S + eps if eps > 0 else S) # Make initial guess. c = irfft(log_I, axis=0)[:h_fft + 1] c[(0, -1), :] *= 0.5 mc = freqt(c, M=M, alpha=alpha, recursive=False) # Perform Newton-Raphson method. prev_epsilon = sys.float_info.max for n in range(n_iter): log_D = mcep_to_stft(mc, n_fft=n_fft, alpha=alpha, log=True) r = irfft(np.exp(log_I - 2 * log_D), axis=0)[:h_fft + 1] r_t = tilde(r, 2 * L - 1, alpha) r_a = r_t[:L] - a # Update mel-cepstral coefficients. t = (r_t[:L], r_t[:L]) h = (r_t[M:], r_t[:L]) b = r_a grad = solve_toeplitz_plus_hankel(t, h, b) mc += grad # Check convergence. epsilon = np.max(r_t[0]) relative_change = (prev_epsilon - epsilon) / epsilon if relative_change < tol: break prev_epsilon = epsilon if is_vector_input: mc = np.squeeze(mc, axis=-1) return mc
def read_and_resize(path_to_vols, vol_name, ntup, toDir='./'): ''' Open and pad (or truncate) the Chebyshev-Fourier-Fourier coefficients of the kxky fields stored in CheckPoints. As they are stored in physical space, the interpolation is done by cosine transform along z, followed by padding or truncation, then inverse cosine transform. Along x and y, the grid is evenly space, and we elect to use linear interpolation (which seems faster for large resolutions, according to a few tests). ''' ierror = 0 domain_decomp_infos = np.fromfile(path_to_vols + '../Geometry/domDecmp.core0000', dtype=np.int32) NX = ntup[0] NY = ntup[1] NZ = ntup[2] NXAA = domain_decomp_infos[3] NYAA = domain_decomp_infos[4] NZAA = domain_decomp_infos[5] print('----------- :: Resizing (' + str(NXAA) + ',' + str(NYAA) + ',' + str(NZAA) + ') into' + ' (' + str(NX) + ',' + str(NY) + ',' + str(NZ) + ').') curPhys = np.fromfile(path_to_vols + vol_name, dtype=np.float_).reshape(NXAA, NYAA, NZAA) coscoefs = dct(curPhys, axis=-1) if (NZ > NZAA): newcoefs = np.zeros((NXAA, NYAA, NZ), dtype=np.float_) newcoefs[:, :, :NZAA] = coscoefs else: newcoefs = coscoefs[:, :, :NZ] aux2 = idct(newcoefs, axis=-1) * NZ / NZAA ## now we need to interpolate in the xy-plane... aux1 = np.zeros((NXAA, ntup[1], ntup[2]), dtype=np.float_) if (NYAA == ntup[1]): aux1 = np.copy(aux2) elif (NYAA < ntup[1]): spectral_buffer = rfft(aux2, axis=1) padded_spectral_buffer = np.zeros((NXAA, ntup[1] // 2 + 1, ntup[2]), dtype=np.complex_) padded_spectral_buffer[:, :(NYAA // 2 + 1), :] = spectral_buffer aux1 = irfft(padded_spectral_buffer, axis=1) / NYAA * ntup[1] del padded_spectral_buffer, spectral_buffer else: spectral_buffer = rfft(aux2, axis=1) truncated_spectral_buffer = np.zeros((NXAA, ntup[1] // 2 + 1, ntup[2]), dtype=np.complex_) truncated_spectral_buffer[:, :(ntup[1] // 3), :] = spectral_buffer[:, :(ntup[1] // 3), :] truncated_spectral_buffer.imag[:, -1, :] = 0. truncated_spectral_buffer.imag[:, 0, :] = 0. aux1 = irfft(truncated_spectral_buffer, axis=1) / NYAA * ntup[1] del truncated_spectral_buffer, spectral_buffer del aux2 deaPhys = np.zeros((ntup[0], ntup[1], ntup[2]), dtype=np.float_) if (NXAA == ntup[0]): deaPhys = np.copy(aux1) elif (NXAA < ntup[0]): spectral_buffer = rfft(aux1, axis=0) padded_spectral_buffer = np.zeros((ntup[0] // 2 + 1, ntup[1], ntup[2]), dtype=np.complex_) padded_spectral_buffer[:(NXAA // 2 + 1), :, :] = spectral_buffer deaPhys = irfft(padded_spectral_buffer, axis=0) / NXAA * ntup[0] del padded_spectral_buffer, spectral_buffer else: spectral_buffer = rfft(aux1, axis=0) truncated_spectral_buffer = np.zeros( (ntup[0] // 2 + 1, ntup[1], ntup[2]), dtype=np.complex_) truncated_spectral_buffer[:(ntup[0] // 3), :, :] = spectral_buffer[:(ntup[0] // 3), :, :] truncated_spectral_buffer.imag[-1, :, :] = 0. truncated_spectral_buffer.imag[0, :, :] = 0. deaPhys = irfft(truncated_spectral_buffer, axis=0) / NXAA * ntup[0] del truncated_spectral_buffer, spectral_buffer del aux1 deaPhys.tofile(toDir + '/Restart/' + vol_name) return ierror
plt.xlabel('Frequency (Hz)') plt.ylabel('Power') plt.legend() ### FFT plot of return signals ### #Defines yf2clean = [] yf3clean = [] ### Filter the two received signals ### xf2 = rfftfreq(N, T) yf2 = rfft(dataJavelin) filter_data(3.5*10**7,np.abs(yf2),yf2clean) dataJavelinClean = irfft(yf2clean) #back to time domain xf3 = rfftfreq(N, T) yf3 = rfft(dataShotput) filter_data(2.0*10**7,np.abs(yf3),yf3clean) dataShotputClean = irfft(yf3clean) #back to time domain ### Plot the two received signals after filtering ### plt.figure() plt.title('Power vs Frequency') plt.xlabel('Frequency (Hz)') plt.ylabel('Power') plt.plot(xf2, np.abs(yf2clean),label='Received (Javelin)') plt.plot(xf3[100:], np.abs(yf3clean)[100:],label='Received (Shotput)') #From 100 onwards to get rid of the DC component value