# this is a polynomial_object temp_poly = polyn.Polynomial(poly_path.coeffs) plt.scatter(temp_poly.real, poly_vals.imag) poly_ls += temp_poly break # since this is list, back to poly # polynom = poly_ls # get fourier transform print(poly_ls) poly_vals = poly_ls(input_list) print(poly_vals) plt.scatter(poly_vals.real, poly_vals.imag) plt.show() for_ls = fft(poly_vals) four_size = for_ls.size four_freq = fftfreq(four_size, 1 / four_size).real four_mag = sum(np.abs(for_ls)) / 50 four_norm = for_ls # / four_mag four_dict = np.vstack((four_freq, four_norm)) # frequncy, amp print('\nfor in\n') # print(for_in) # np.savetxt(poly_file, polynom.coeffs)
def energy(data): return np.sqrt(sum(np.abs(fft(data))**2))
def __call__(self, iqdata): return self.fineTuner(ifft(np.roll(fft(iqdata), self.nstep)))
def overlap(self, sobo=False): """Calculate the overlap between atomic orbitals (Using Cartesian Coordinates). Returns ------- numpy array The overlap matrix. """ if sobo is True: spacing = (self.max_r - self.min_r) / (self.num_of_div - 1) r_freq = spyfft.fftfreq(self.num_of_div, spacing) S_mat = np.zeros((self.num_of_basis, self.num_of_basis), dtype=complex) for mu in range(self.num_of_basis): for nu in range(self.num_of_basis): overlap_mu_nu_temp = 0 for p in range(self.num_of_gauss): for q in range(self.num_of_gauss): if sobo is False: new_a, new_c, new_f = self.two_GF( self.a_overlap_mat[p][mu], self.a_overlap_mat[q][nu], self.atomic_position[mu], self.atomic_position[nu]) int_func_x1 = self.GF(new_a, self.r - new_c[0]) int_func_y1 = self.GF(new_a, self.r - new_c[1]) int_func_z1 = self.GF(new_a, self.r - new_c[2]) integrate_x = spyint.simpson(int_func_x1, self.r) integrate_y = spyint.simpson(int_func_y1, self.r) integrate_z = spyint.simpson(int_func_z1, self.r) overlap_mu_nu_temp += self.d_overlap_mat[p][ mu] * self.d_overlap_mat[q][nu] * ( 2 * new_a / m.pi)**(3 / 4) * new_f * ( integrate_x * integrate_y * integrate_z) elif sobo is True: int_func_x1 = self.GF( self.a_overlap_mat[p][mu], self.r - self.atomic_position[mu][0]) int_func_y1 = self.GF( self.a_overlap_mat[p][mu], self.r - self.atomic_position[mu][1]) int_func_z1 = self.GF( self.a_overlap_mat[p][mu], self.r - self.atomic_position[mu][2]) int_func_x2 = self.GF( self.a_overlap_mat[q][nu], self.r - self.atomic_position[nu][0]) int_func_y2 = self.GF( self.a_overlap_mat[q][nu], self.r - self.atomic_position[nu][1]) int_func_z2 = self.GF( self.a_overlap_mat[q][nu], self.r - self.atomic_position[nu][2]) integrate_x = spyint.simpson( np.multiply( int_func_x1, spyfft.ifft(spyfft.fft(int_func_x2))), self.r) integrate_y = spyint.simpson( np.multiply( int_func_y1, spyfft.ifft(spyfft.fft(int_func_y2))), self.r) integrate_z = spyint.simpson( np.multiply( int_func_z1, spyfft.ifft(spyfft.fft(int_func_z2))), self.r) integrate_x_d = spyint.simpson( np.multiply( int_func_x1, spyfft.ifft( spyfft.fft(int_func_x2) / (1 + (0.5) * ((2 * np.pi)**2) * (r_freq**2)))), self.r) integrate_y_d = spyint.simpson( np.multiply( int_func_y1, spyfft.ifft( spyfft.fft(int_func_y2) / (1 + (0.5) * ((2 * np.pi)**2) * (r_freq**2)))), self.r) integrate_z_d = spyint.simpson( np.multiply( int_func_z1, spyfft.ifft( spyfft.fft(int_func_z2) / (1 + (0.5) * ((2 * np.pi)**2) * (r_freq**2)))), self.r) overlap_mu_nu_temp += self.d_overlap_mat[p][ mu] * self.d_overlap_mat[q][nu] * ( 2 * self.a_overlap_mat[p][mu] / m.pi)**(3 / 4) * ( 2 * self.a_overlap_mat[q][nu] / m.pi)**(3 / 4) * ( (integrate_x_d * integrate_y * integrate_z) + (integrate_x * integrate_y_d * integrate_z) + (integrate_x * integrate_y * integrate_z_d)) # print(overlap_mu_nu_temp) # print("Overlap", overlap_mu_nu_temp) S_mat[mu][nu] += overlap_mu_nu_temp return np.real(S_mat)
def df_to_fixed_frames(self, frame_size, skip_size, transform_type='all'): """Creates a tuple of the frames containing the sequence of temporal series and the corresponding labels. Each frame is reduced to a vactor thanks to a PCA algorithm Parameters ---------- frame_size : int the size of each sliced window skip_size : int the size of the window that should skipped before creating a new one Returns ------- frames : array An array containing sub-arrays of each reduced frame of data labels : array An array containing labels corresponding to each sub-frame """ # n_components = min(frame_size, 6) # frames = [] acc_x_frames = [] acc_y_frames = [] acc_z_frames = [] gyro_x_frames = [] gyro_y_frames = [] gyro_z_frames = [] acc_x_frames_dct = [] acc_y_frames_dct = [] acc_z_frames_dct = [] gyro_x_frames_dct = [] gyro_y_frames_dct = [] gyro_z_frames_dct = [] acc_x_frames_fft = [] acc_y_frames_fft = [] acc_z_frames_fft = [] gyro_x_frames_fft = [] gyro_y_frames_fft = [] gyro_z_frames_fft = [] labels = [] for i in range(0, len(self.df) - frame_size, skip_size): acc_x = self.df['Acc_x'].values[i:i + frame_size] acc_y = self.df['Acc_y'].values[i:i + frame_size] acc_z = self.df['Acc_z'].values[i:i + frame_size] gyro_x = self.df['Gyro_x'].values[i:i + frame_size] gyro_y = self.df['Gyro_y'].values[i:i + frame_size] gyro_z = self.df['Gyro_z'].values[i:i + frame_size] label = stats.mode(self.df['appui_leve'][i:i + frame_size])[0][0] if transform_type == 'all' or transform_type is None: acc_x_frames.append(np.asarray(acc_x)) acc_y_frames.append(np.asarray(acc_y)) acc_z_frames.append(np.asarray(acc_z)) gyro_x_frames.append(np.asarray(gyro_x)) gyro_y_frames.append(np.asarray(gyro_y)) gyro_z_frames.append(np.asarray(gyro_z)) if transform_type == 'all' or transform_type == 'dct': acc_x_frames_dct.append(np.asarray(dct(acc_x))) acc_y_frames_dct.append(np.asarray(dct(acc_y))) acc_z_frames_dct.append(np.asarray(dct(acc_z))) gyro_x_frames_dct.append(np.asarray(dct(gyro_x))) gyro_y_frames_dct.append(np.asarray(dct(gyro_y))) gyro_z_frames_dct.append(np.asarray(dct(gyro_z))) if transform_type == 'all' or transform_type == 'fft': acc_x_frames_fft.append(np.asarray(fft(acc_x).real)) acc_y_frames_fft.append(np.asarray(fft(acc_y).real)) acc_z_frames_fft.append(np.asarray(fft(acc_z).real)) gyro_x_frames_fft.append(np.asarray(fft(gyro_x).real)) gyro_y_frames_fft.append(np.asarray(fft(gyro_y).real)) gyro_z_frames_fft.append(np.asarray(fft(gyro_z).real)) labels.append(label) labels = np.asarray(labels) expand_dims_func = lambda x: np.expand_dims(np.asarray(x), axis=-1) if transform_type is None: frames = (acc_x_frames, acc_y_frames, acc_z_frames, gyro_x_frames, gyro_y_frames, gyro_z_frames) frames = tuple(map(expand_dims_func, frames)) return frames, labels elif transform_type == 'dct': dct_frames = (acc_x_frames_dct, acc_y_frames_dct, acc_z_frames_dct, gyro_x_frames_dct, gyro_y_frames_dct, gyro_z_frames_dct) dct_frames = tuple(map(expand_dims_func, dct_frames)) return dct_frames, labels elif transform_type == 'fft': fft_frames = (acc_x_frames_fft, acc_y_frames_fft, acc_z_frames_fft, gyro_x_frames_fft, gyro_y_frames_fft, gyro_z_frames_fft) fft_frames = tuple(map(expand_dims_func, fft_frames)) return fft_frames, labels elif transform_type == 'all': frames = (acc_x_frames, acc_y_frames, acc_z_frames, gyro_x_frames, gyro_y_frames, gyro_z_frames) frames = tuple(map(expand_dims_func, frames)) dct_frames = (acc_x_frames_dct, acc_y_frames_dct, acc_z_frames_dct, gyro_x_frames_dct, gyro_y_frames_dct, gyro_z_frames_dct) dct_frames = tuple(map(expand_dims_func, dct_frames)) fft_frames = (acc_x_frames_fft, acc_y_frames_fft, acc_z_frames_fft, gyro_x_frames_fft, gyro_y_frames_fft, gyro_z_frames_fft) fft_frames = tuple(map(expand_dims_func, fft_frames)) all_frames = (frames, dct_frames, fft_frames) return all_frames, labels
def step(self, D): # Propagate input Beam object over distance, D; return Beam object. Fourier algorithm. Pin = fft(self.U) # FFT of amplitude distribution, U, gives spatial frequency distribution, Pin at initial position, z. Pout = Pin * np.exp(1j * self.kz * D) # Multiply Spatial frequency distribution by phase-factor corresponding to propagation through distance, D, to give new spatial frequency distribution, Pout. Uout = ifft(Pout) # IFFT of spatial frequency distribution gives amplitude distribution, Uout, at plane z = z + D self.U = Uout return self
#sound = AudioSegment.from_file("perc_prosjekt.mp3", format="mp3") #play(sound) a = pydub.AudioSegment.from_mp3("perc_prosjekt.mp3") frame_rate = a.frame_rate track = np.array(a.get_array_of_samples()) track = track.reshape((-1, 2)) track = track / 2**15 # Normalize mono = track[:,0] track = mono track = track/1000 # in units of s now # Fourier: freqs = fft(track) # Hz peaks = signal.find_peaks(x=freqs, height=4) #print("n peaks: ", len(peaks[0])) peaks_x = peaks[0] peaks_y = peaks[1]["peak_heights"] Traveling_point(track, peaks_x, peaks_y, frame_rate) fig, ax = plt.subplots() ax.plot(freqs) ax.scatter(peaks_x, peaks_y, color="black") plt.semilogx() fig.savefig("dev_fig.pdf")
def mcR_FFT(v, t=None, meth='pad0', mT=0): """ Computes, using fast Fourier Transform, the raw correlation functions (i.e. non-central unnormalized moments) of a multi-channel signal, i.e. R(tau) = < v1(t) v2(t+tau) >_t. Equivalent to (but faster than) mcR(t,v,meth=('multiTau',0,'wrap')). Parameters: t: Time vector. Not necessarily starting from 0, but with dt somewhat uniform. v: Multi-channel signal where each row is a channel. meth: pad0: pad signal with zeros to get linear (not circular) correlations trim: trim overhangs of signal wrap: wrap signal around to get linear correlations mT: multitau algorithm, start averaging after 2^mT points Returns: tau: Vector of time lags (same unit as t) R: Raw cross-covariance function. """ assert not (meth.lower() == 'wrap' and mT), 'combination wrap and multi-tau not implemented' M = v.shape[-1] if meth.lower() == 'wrap': L = M else: L = int(2 ** np.ceil(1 + np.log2(M))) v = np.pad(v, [(0, 0)] * (v.ndim - 1) + [(0, L - M)], 'constant') fv = fft.fft(v) dt = 1 if t is None else np.nanmean(np.diff(t)) tau, R = [], [] p = 2 ** mT q = p // 2 s = 1 if mT == 0 else np.clip(int(np.log2(L) - mT), 0, 15) for i in range(s): j = 2 ** i r = fft.ifft(np.tile(fv, fv.shape[0]).reshape((fv.shape[0],) + fv.shape).conj() * fv).real / fv.shape[-1] if s == 1: # no multiTau u = np.arange(L) elif i == 0: # first part of corfun u = np.arange(p) r = r[..., :p] else: # other parts of corfun u = np.arange(q, p) * j r = r[..., q:p] if i < s - 1: # remove half of the higher frequencies fv = np.concatenate((fv[..., :fv.shape[-1] // 4], fv[..., -fv.shape[-1] // 4:]), -1) tau.append(u.astype(float)) R.append(r / j ** 2) tau = np.concatenate(tau, -1) i = np.argsort(tau) i = i[tau[i] < M] tau = tau[i] R = np.concatenate(R, -1) R = R[..., i] * L if meth.lower() == 'trim': R /= (M - tau) else: R /= M if t is None: return R return R, tau*dt
def time_fft(self, size, num_transforms, method): if method == 'threading': self.map_thread(scipy_fft.fft) else: for x in self.xs: scipy_fft.fft(x, workers=-1)
import numpy as np import matplotlib.pyplot as plt import matplotlib.image as im from scipy import fft from scipy.io import wavfile import tqdm for i in tqdm.tqdm(range(0, 700)): fs, sample = wavfile.read("301-project-train-noisy/sample" + str(i) + ".wav") spectrum = fft.fftshift(fft.fft(sample)) abs_spec = np.abs(spectrum) # plt.stem(abs_spec[80000:130000], use_line_collection=True) # plt.show() fftlength = len(spectrum) # print(len(abs_spec)) # Notice, band from 90000 to 122000 is unusually increased. To clean, we must remove that bump zeros = np.zeros((122000 - 90000)) spectrum[90000:122000] = zeros spectrum[fftlength - 122000:fftlength - 90000] = zeros output = np.real(fft.ifft(fft.ifftshift(spectrum))).astype(np.int16).T wavfile.write("301-project-train-clean/clean" + str(i) + ".wav", fs, output) for i in tqdm.tqdm(range(700, 1000)):
def timeseries_to_spectrogram(timeseries: Timeseries, fft_size: int = 1024, n_samples: int = 1024, n_records: int = None, synchronization_offset: int = 0, overlap: float = 0.0, window: str = None): """ # TODO: Introduce overlap + windowing Args: n_records: synchronization_offset: timeseries: fft_size: n_samples: overlap: window: str Returns: """ if overlap >= 1: raise ValueError("Overlap percentage must be less than 100%") if overlap < 0: raise ValueError("Overlap percentage must be equal or greater than 0%") total_samples = n_samples + synchronization_offset overlap_samples = n_samples * (1 - overlap) if n_records is None: n_records = int( ((len(timeseries.data) - total_samples) // overlap_samples)) + 1 start_samples = [ int(i * total_samples * (1 - overlap)) for i in range(n_records) ] time_data = np.zeros((fft_size, n_records), dtype=float) # Reshape the timeseries data into bins of n_time_samples: input_data = np.reshape(np.array( list( zip(*(timeseries.data['amplitude'][i:i + total_samples] for i in start_samples)))), (total_samples, n_records), order='F') # input_data = np.reshape(timeseries.data['amplitude'][:(n_records * total_samples)], (total_samples, n_records), # order='F') time_data[:n_samples, :] = input_data[:n_samples, :] if window is None: window = np.ones(n_samples) else: window = windows.get_window(window, n_samples) # Apply window time_data *= np.transpose(np.tile(window, (time_data.shape[1], 1))) spectrogram_data = fft.fft(time_data / timeseries.sample_rate, fft_size, axis=0) t_res = timeseries.duration() / (int( ((len(timeseries.data) - total_samples) // overlap_samples)) + 1) f_res = timeseries.sample_rate / fft_size return Spectrogram(spectrogram_data, f_res, t_res)
]) #array delle frequenze della funzione in ingresso FT = np.array([ np.sum(y * np.exp(2j * np.pi * freq[i] * t)) for i in range(N) ]) #FT di una funzione y in input return freq, FT N = 1000 t = np.linspace(0, 1, N) y = f(t, 1, 0.1) T = t[-1] tau = t[1] - t[0] omega = [t[i] / (2 * T * tau) for i in range(N)] F = np.abs(fft(y))[:N // 2] * tau freq, my_F = np.abs(Fourier(y, T, t)) fig, ax = plt.subplots() ax.plot(t, y) ax.set_xlabel('t (s)') ax.set_ylabel('y(t)') fig1, ax1 = plt.subplots() ax1.plot(omega[:N // 2], F, color='orange') ax1.set_xlabel('$\\nu$') ax1.set_ylabel('$\mathcal{F})(\\nu)$') fig2, ax2 = plt.subplots() ax2.plot(freq[:N // 2], my_F[:N // 2], color='blue') ax2.set_xlabel('$\\nu$')
#NOTE: use this function whenever you want to work with the ECG data (not rdrecord) signals, fields = wfdb.rdsamp('118e24', channels=[0], sampfrom=108600, sampto=108600 + 360) #194400) display(signals) display(fields) #signals7, fields7 = wfdb.rdsamp('118e12', channels=[1], sampfrom=0, sampto= 360) #194400) #display(signals7) #display(fields7) time = np.linspace(0, 1, 360, endpoint=False) z = fft(signals) display(np.max(z)) #signals = np.abs(signals) sampling_freq = 360 sampling_duration = 1 number_of_samples = int(sampling_freq * sampling_duration) time = np.linspace(0, sampling_duration, number_of_samples, endpoint=False) N = 3 # Filter order Wn = .1 #1-0.735 # Cutoff frequency b, a = signal.butter(N, Wn, 'low') fsignals = signal.filtfilt(b, a, signals, axis=0) plt.plot(time, signals, 'b-', label='signal') plt.plot(time, fsignals - 0.05, 'g-', linewidth=2,
def spec_pgram(x, xfreq=1, spans=None, kernel=None, taper=0.1, pad=0, fast=True, demean=False, detrend=True, plot=True, **kwargs): """ Computes the spectral density estimate using a periodogram. Optionally, it also: - Uses a provided kernel window, or a sequence of spans for convoluted modified Daniell kernels. - Tapers the start and end of the series to avoid end-of-signal effects. - Pads the provided series before computation, adding pad*(length of series) zeros at the end. - Pads the provided series before computation to speed up FFT calculation. - Performs demeaning or detrending on the series. - Plots results. Implemented to ensure compatibility with R's spectral functions, as opposed to reusing scipy's periodogram. Adapted from R's stats::spec.pgram. """ def daniell_window_modified(m): """ Single-pass modified Daniell kernel window. Weight is normalized to add up to 1, and all values are the same, other than the first and the last, which are divided by 2. """ def w(k): return np.where( np.abs(k) < m, 1 / (2 * m), np.where(np.abs(k) == m, 1 / (4 * m), 0)) return w(np.arange(-m, m + 1)) def daniell_window_convolve(v): """ Convolved version of multiple modified Daniell kernel windows. Parameter v should be an iterable of m values. """ if len(v) == 0: return np.r_[1] if len(v) == 1: return daniell_window_modified(v[0]) return signal.convolve(daniell_window_modified(v[0]), daniell_window_convolve(v[1:])) # Ensure we can store non-integers in x, and that it is a numpy object x = np.r_[x].astype('float64') original_shape = x.shape # Ensure correct dimensions assert len(original_shape) <= 2, "'x' must have at most 2 dimensions" while len(x.shape) < 2: x = np.expand_dims(x, axis=1) N, nser = x.shape N0 = N # Ensure only one of spans, kernel is provided, and build the kernel window if needed assert (spans is None) or ( kernel is None), "must specify only one of 'spans' or 'kernel'" if spans is not None: kernel = daniell_window_convolve(np.floor_divide(np.r_[spans], 2)) # Detrend or demean the series if detrend: t = np.arange(N) - (N - 1) / 2 sumt2 = N * (N**2 - 1) / 12 x -= (np.repeat(np.expand_dims(np.mean(x, axis=0), 0), N, axis=0) + np.outer(np.sum(x.T * t, axis=1), t / sumt2).T) elif demean: x -= np.mean(x, axis=0) # Compute taper and taper adjustment variables x = spec_taper(x, taper) u2 = (1 - (5 / 8) * taper * 2) u4 = (1 - (93 / 128) * taper * 2) # Pad the series with copies of the same shape, but filled with zeroes if pad > 0: x = np.r_[x, np.zeros((pad * x.shape[0], x.shape[1]))] N = x.shape[0] # Further pad the series to accelerate FFT computation if fast: newN = fft.next_fast_len(N, True) x = np.r_[x, np.zeros((newN - N, x.shape[1]))] N = newN # Compute the Fourier frequencies (R's spec.pgram convention style) Nspec = int(np.floor(N / 2)) freq = (np.arange(Nspec) + 1) * xfreq / N # Translations to keep same row / column convention as stats::mvfft xfft = fft.fft(x.T).T # Compute the periodogram for each i, j pgram = np.empty((N, nser, nser), dtype='complex') for i in range(nser): for j in range(nser): pgram[:, i, j] = xfft[:, i] * np.conj(xfft[:, j]) / (N0 * xfreq) pgram[0, i, j] = 0.5 * (pgram[1, i, j] + pgram[-1, i, j]) if kernel is None: # Values pre-adjustment df = 2 bandwidth = np.sqrt(1 / 12) else: def conv_circular(signal, kernel): """ Performs 1D circular convolution, in the same style as R::kernapply, assuming the kernel window is centered at 0. """ pad = len(signal) - len(kernel) half_window = int((len(kernel) + 1) / 2) indexes = range(-half_window, len(signal) - half_window) orig_conv = np.real( fft.ifft( fft.fft(signal) * fft.fft(np.r_[np.zeros(pad), kernel]))) return orig_conv.take(indexes, mode='wrap') # Convolve pgram with kernel with circular conv for i in range(nser): for j in range(nser): pgram[:, i, j] = conv_circular(pgram[:, i, j], kernel) df = 2 / np.sum(kernel**2) m = (len(kernel) - 1) / 2 k = np.arange(-m, m + 1) bandwidth = np.sqrt(np.sum((1 / 12 + k**2) * kernel)) df = df / (u4 / u2**2) * (N0 / N) bandwidth = bandwidth * xfreq / N # Remove padded results pgram = pgram[1:(Nspec + 1), :, :] spec = np.empty((Nspec, nser)) for i in range(nser): spec[:, i] = np.real(pgram[:, i, i]) if nser == 1: coh = None phase = None else: coh = np.empty((Nspec, int(nser * (nser - 1) / 2))) phase = np.empty((Nspec, int(nser * (nser - 1) / 2))) for i in range(nser): for j in range(i + 1, nser): index = int(i + j * (j - 1) / 2) coh[:, index] = np.abs(pgram[:, i, j])**2 / (spec[:, i] * spec[:, j]) phase[:, index] = np.angle(pgram[:, i, j]) spec = spec / u2 spec = spec.squeeze() results = { 'freq': freq, 'spec': spec, 'coh': coh, 'phase': phase, 'kernel': kernel, 'df': df, 'bandwidth': bandwidth, 'n.used': N, 'orig.n': N0, 'taper': taper, 'pad': pad, 'detrend': detrend, 'demean': demean, 'method': 'Raw Periodogram' if kernel is None else 'Smoothed Periodogram' } if plot: plot_spec(results, coverage=0.95, **kwargs) return results
ax2.set_xlabel('Tiempo (s)', color='r') ax2.set_ylabel('Amplitud', color='r') ax2.set_title('Con ruido', color='green') plt.show() # II)------CÁLCULO DE LA TRANSFORMADA DE FOURIER------# #a) Creación del dominio de la frecuencia frecuencias = fftfreq(nPuntos) #b) Ignoramos la mitad de los valores, puesto que son los conjugados complejos de los otros indices_numeros_positivos = frecuencias > 0 #c) Cálculo de la transformada mediante la FFT señal_ruidosa_dom_frec = fft(señal_ruidosa) amplitudes_señal_ruidosa_dom_frec = 2.0 * np.abs( señal_ruidosa_dom_frec / nPuntos) #d) Graficación de la señal (dominio de la frecuencia) fig = plt.figure(figsize=(12, 5), frameon=False, facecolor='yellow') fig.canvas.set_window_title( 'Ventana de salida de la señal en el dominio de la frecuencia') fig.suptitle('Señal ruidosa en el dominio de la frecuencia', fontsize=15, color='red') plt.plot(frecuencias[indices_numeros_positivos], amplitudes_señal_ruidosa_dom_frec[indices_numeros_positivos], label='Valores de la transformada')
lnx=np.size(mtn,0)-1; z=len(SrDrc) MTR=np.zeros([nmdn,z*(dgr03+1)+2]) for j in range(nmdn): if j==nmdnMAX: vctn=list(range(j*dn,ysz2)) else: vctn=list(range(j*dn,j*dn+4*HnklMtSz)) print(str(j)+':'+str(min(vctn))+'-'+str(max(vctn))) ypa=yp[:,vctn] NFFT=dgr03*2-2 fs1=(np.array(range(dgr03))*fs/NFFT).T w1=2*np.pi*fs1 ms1=np.ones([mktr,int(NFFT/2)+1]); for i1 in range(mktr): vct=fft(ypa[i1,:],NFFT)/fft(ypa[-1,:],NFFT); a=int(NFFT/2)+1 ms1[i1,range(a)]=vct[range(a)]; kn=kn+1; wdgr=np.size(w1,0); if wdgr<dgr03: hata=hata+1; HATA.extend([j]) np.append(w1,-np.ones([dgr03-wdgr,1])) np.append(ms1,np.zeros([len(mtn),dgr03-wdgr])) MSL=np.reshape(ms1.T,[1,(lnx)*dgr03]) v=[]; v.extend(SrDrc) v.extend([min(vctn),max(vctn)]) v.extend(w1[0:dgr03].T) v.extend(MSL[0])
def whiten(tr, Tmin=1, Tmax=150, freq_width=.0004, brute=True, frac=.2, epsilon=1e-8, **kwargs): """ Spectral whitening using running absolute mean in frequency domain. https://github.com/NoiseCIEI/Seed2Cor/blob/master/src/Whiten.c https://github.com/bgoutorbe/seismic-noise-tomography/blob/8f26ff827bee8a411038e33d93b59bffbc88c0a7/pysismo/pscrosscorr.py#L306 https://www.mathworks.com/matlabcentral/fileexchange/65345-spectral-whitening https://github.com/ROBelgium/MSNoise/blob/27749e2914b30b1ab8278054645677444f10e309/msnoise/move2obspy.py#L135 :param freq_width: length of averaging window in frequency domain :param epsilon: minimum value to avoid zero division :param return_spc: if return spectra for plot """ npts = tr.stats.npts sr = tr.stats.sampling_rate dom = sr / npts winlen = int(round(freq_width / dom)) nfreq = next_fast_len(npts) spc = fft(tr.data, nfreq) spc_am = np.abs(spc) spc_ph = np.unwrap(np.angle(spc)) if brute: weight = spc_am spc_w = np.exp(1j * spc_ph) elif winlen < 2: weight = spc_am spc_w = np.exp(1j * spc_ph) logger.debug('Window too short') else: weight = bn.move_mean(spc_am, winlen, 1) ind = weight < epsilon weight[ind] = epsilon spc_w = spc / weight spc_w[ind] = 0 f2 = 1 / Tmax f3 = 1 / Tmin f1 = f2 * (1 - frac) f4 = f3 * (1 + frac) if f4 > sr / 2: logger.warning( 'Whiten band upper end out of range! Corrected to Nyquist.') f4 = sr / 2 if f3 >= f4: f3 = f4 * (1 - frac) if f3 < f2: f3 = f2 freqs = fftfreq(nfreq, d=tr.stats.delta) spc_w *= obspy.signal.invsim.cosine_taper( npts=nfreq, freqs=freqs, flimit=[f1, f2, f3, f4], ) # Hermitian symmetry (because the input is real) spc_w[-(nfreq // 2) + 1:] = spc_w[1:(nfreq // 2)].conjugate()[::-1] whitened = ifft(spc_w, nfreq)[:npts] if kwargs.get('plot', False): xlim = [0, .2] npts = tr.stats.npts delta = tr.stats.delta t = np.arange(0, npts * delta, delta) fig = plt.figure(figsize=(12, 8)) gs = mpl.gridspec.GridSpec(3, 1) ax1 = plt.subplot(gs[0, 0]) ax2 = plt.subplot(gs[1, 0]) ax3 = plt.subplot(gs[2, 0], sharex=ax2) tr.filter('bandpass', freqmin=f2, freqmax=f3, zerophase=True) ax1.plot(t, tr.normalize().data, c='k', label="Raw", ls='--', lw=1) ax1.plot(t, whitened / np.abs(whitened).max(), c='r', label="Whitened", lw=1) ax1.set_xlabel("Time (s)") ax1.set_xlim(0, tr.stats.sac.dist) ax1.set_ylim(-1, 1) ifreq = np.argsort(freqs) ax2.plot(freqs[ifreq], spc_am[ifreq], alpha=.5, lw=1, c='gray', ls='--', label="Raw") ax2.plot(freqs[ifreq], weight[ifreq], alpha=.5, lw=2, c='g', label="Weight") ax2.set_xlim(xlim[0], xlim[1]) ax3.plot(freqs[ifreq], np.abs(spc_w)[ifreq], lw=1, c='b', label="Whitened") for ax in [ax2, ax3]: ax.set_ylim(0) ax.set_xlabel("Frequency (Hz)") for per in [8, 16, 26]: ax.axvline(1 / per, ls='--', alpha=.5, c='k') for ax in [ax1, ax2, ax3]: ax.legend(loc='upper right') pair = f'{tr.stats.sac.kevnm.strip()}_{tr.stats.sac.kstnm.strip()}' fig.suptitle(pair, y=1.02) # fig.savefig(f'/work2/szhang/US/Plot/fig4exp/US/sw_{pair}.pdf') plt.show() tr.data = whitened tr.taper(max_percentage=0.05, type='hann', side='both') return tr
xc = meshsim.centers() finit = rhs.fdata_fromprim([frho(xc), fu(xc), fp(xc)]) # rho, u, p fsol = solver.solve(finit, cfl, np.linspace(0., endtime, nsol + 1)) solver.show_perf() # Figure / Plot varname = 'pressure' # mach, pressure, entropy ttime = [fsol[i].time for i in range(nsol + 1)] xx, xt = np.meshgrid(xc, ttime) solgrid = [fsol[i].phydata(varname) for i in range(nsol + 1)] vmin, vmax = np.min(solgrid), np.max(solgrid) # from scipy.fft import fft, ifft sp0 = h * fft(finit.phydata(varname)) sp1 = h * fft(fsol[-1].phydata(varname)) # # Figure / Plot of final results fig, ax = plt.subplots(2, 2, figsize=(12, 8)) ax[0, 0].set_ylabel(varname) ax[0, 0].set_ylim(vmin, vmax) ax[0, 0].grid(linestyle='--', color='0.5') finit.plot(varname, 'k-', axes=ax[0, 0]) line1, = fsol[-1].plot(varname, 'b-', axes=ax[0, 0]) ax[0, 1].set_ylabel('t') ax[0, 1].set_xlim(0., 1.) #ax[0,1].grid(linestyle='--', color='0.5') flood = ax[0, 1].contour(xx, xt, solgrid, np.linspace(vmin, vmax, 50)) line2, = ax[0, 1].plot([0., 10.], [ttime[-1], ttime[-1]], 'k--') #
def plot_FFT(df, key, channels): from scipy.fft import fft, fftfreq for channel in channels: our_channels = [ col for col in df.columns if channel + ' final normalized' in col ] sig1 = df[our_channels[0]] sig2 = df[our_channels[1]] time = df['fTimeGreen'] # Number of sample points N = len(sig1) # sample spacing T = time.iloc[-1] / (N * 300) y1 = fft(sig1.tolist()) y1 = 2.0 / N * np.abs(y1[0:N // 2]), y2 = fft(sig2.tolist()) y2 = 2.0 / N * np.abs(y2[0:N // 2]), xf = fftfreq(N, T)[:N // 2] y1binned = np.arange(0, np.floor(xf[-1])) y2binned = np.arange(0, np.floor(xf[-1])) xbinned = np.arange(0, np.floor(xf[-1]), 1) counter = 0 idx = -1 y1tot = 0 y2tot = 0 for i in xf: idx = idx + 1 if i < counter + 1: y1tot = y1tot + y1[0][idx] y2tot = y2tot + y2[0][idx] else: y1binned[counter] = y1tot y2binned[counter] = y2tot counter = counter + 1 y1tot = 0 y2tot = 0 fig = make_subplots(rows=1, cols=1) fig.add_trace(go.Scatter(x=xf, y=y1[0], mode="lines", name='T= ' + str(T), showlegend=True), row=1, col=1) fig.add_trace(go.Scatter(x=xf, y=y2[0], mode="lines", name='y2', showlegend=True), row=1, col=1) fig.add_trace(go.Scatter(x=xbinned, y=y1binned, mode="lines", name='y1binned', showlegend=True), row=1, col=1) fig.add_trace(go.Scatter(x=xbinned, y=y2binned, mode="lines", name='y2binned', showlegend=True), row=1, col=1) fig.show()
def show(t, name="FFT"): plt.title(name) plt.xlabel('N') plt.ylabel(name) plt.plot([i for i in range(len(t))], t, color='red') plt.show() def create_signal(n=8, N=4096, W=1200): """Function for create random signal""" x = [0 for i in range(N)] for i in range(N): for j in range(n): A = randrange(0, 100) q = randrange(0, 100) SINUSOID = A * sin((W / n * (j + 1) / n) * i + q) x[i] += SINUSOID return [round(x[i], 3) for i in range(len(x))] x_n = create_signal() t1 = time() a = FFT(x_n, len(x_n)) t2 = time() - t1 t3 = time() b = fft(x_n) t4 = time() - t3 print("t1={} t2={}, обчислення виконались у {} швидше".format( round(t2, 4), round(t4, 4), int(t2 // t4))) # show(x_n, name="X(t)") # show(a)
############################################################################## ############################################################################## #%% 2) Mostrar el Espectro de la Señal (Espectro Módulo). Escalar el Eje de # Frecuencia en Hz. # Grilla Frecuencial f0 = 0 df = Fs / N # Resolución Espectral ff = (N-1)*df f = np.linspace(f0, ff, N) # Calculo la TDF de la Señal Sintetizada Utilizando la FFT: S = fft (s) Abs_S = np.abs( S ) / N # Módulo #%% Ploteo el Módulo del Espectro de la Señal Sintetizada. fig2 = plt.figure ( ) plt.plot (f, Abs_S) plt.title ('Módulo del Espectro de la Señal Sintetizada') plt.grid ('true') plt.xlabel('$frecuency [Hz]$', fontsize = 13) plt.ylabel ('$|S(f)|$', fontsize = 15) ############################################################################## ##############################################################################
stride_size = 512 def slice_signal(in_signal): return(util.view_as_windows(in_signal, window_shape=(512,), step=stride_size)) #return(util.view_as_windows(in_signal, window_shape=(1024,), step=stride_size)) # Create a sliding window representation (split channel1 into N chunks of 1024 samples each) intervals_chan1 = slice_signal(channel1) intervals_chan2 = slice_signal(channel2) print(f"Sliced channel 1: {intervals_chan1.shape}") print(f"Sliced channel 2: {intervals_chan2.shape}") n_intervals = intervals_chan1.shape[0] n_intervals # Audio spectra X_chan1 = fft(intervals_chan1, axis=1) magn_chan1, phas_chan1 = real_imag2magn_phas(X_chan1.real, X_chan1.imag) X_chan2 = fft(intervals_chan2, axis=1) magn_chan2, phas_chan2 = real_imag2magn_phas(X_chan2.real, X_chan2.imag) max_value = max(X_chan1[1]) min_value = min(X_chan1[1]) #avg_value = mean(X_chan1[1]) print(max_value) print(min_value) #print(avg_value) # Load image img = imread('paisaje5.jpg') img = resize(img, (512, 512))
def musicalNoteDetection(): #GPIO stuff GPIO.setmode(GPIO.BCM) GPIO.setup(5, GPIO.OUT) #D4 Blue GPIO.setup(6, GPIO.OUT) #F Down GPIO.setup(13, GPIO.OUT) #A Right GPIO.setup(19, GPIO.OUT) #D5 Up GPIO.setup(26, GPIO.OUT) #B Left GPIO.output(5, GPIO.LOW) GPIO.output(6, GPIO.LOW) GPIO.output(13, GPIO.LOW) GPIO.output(19, GPIO.LOW) GPIO.output(26, GPIO.LOW) #audio stuff maybe pygame.mixer.init(32000) #turn all of pygame on. confirm = Sound( "Music/OOT_Song_Correct.wav" ) #change accordingly for your song confirmation sound file name/location #mqtt stuff client = mqtt.Client() client.connect("localhost", 1883, 300) client.subscribe("WifiEnigma/#") client.loop_start() #Volume Sensitivity, 0.05: Extremely Sensitive, may give false alarms # 0.1: Probably Ideal volume # 1: Poorly sensitive, will only go off for relatively loud SENSITIVITY = 1.0 #Bandwidth for detection (i.e., detect frequencies within this margin of error of the TONE) BANDWIDTH = 25 # Alarm frequencies (Hz) to detect (Use audacity to record a wave and then do Analyze->Plot Spectrum) C = 494 D4 = 542 E = 618 F = 660 G = 744 A = 882 B = 992 D5 = 1179 #frequency ranges for each note '''rangeD4 = range(D4-BANDWIDTH,D4+BANDWIDTH) rangeE = range(E-BANDWIDTH,E+BANDWIDTH) rangeF = range(F-BANDWIDTH,F+BANDWIDTH) rangeG = range(G-BANDWIDTH,G+BANDWIDTH) rangeA = range(A-BANDWIDTH,A+BANDWIDTH) rangeB = range(B-BANDWIDTH,B+BANDWIDTH) rangeD5 = range(D5-BANDWIDTH,D5+BANDWIDTH)''' #These numbers work for my ocarina in my house with a blue yeti, ymmv minC = C - 25 maxC = C + 25 minD4 = D4 - 25 maxD4 = D4 + 25 minE = E - 25 maxE = E + 25 minF = F - 25 maxF = F + 25 minG = G - BANDWIDTH maxG = G + BANDWIDTH minA = A - BANDWIDTH maxA = A + 55 minB = B - BANDWIDTH maxB = B + BANDWIDTH minD5 = D5 - BANDWIDTH maxD5 = D5 + BANDWIDTH # Song note sequences sun = deque(['A', 'F', 'D5', 'A', 'F', 'D5']) time = deque(['A', 'D4', 'F', 'A', 'D4', 'F']) storm = deque(['D4', 'F', 'D5', 'D4', 'F', 'D5']) forest = deque(['D4', 'D5', 'B', 'A', 'B', 'A']) saria = deque(['F', 'A', 'B', 'F', 'A', 'B']) fire = deque(['F', 'D4', 'F', 'D4', 'A', 'F']) #This is just 6 notes, play all 8 if you want ;) epona = deque(['D5', 'B', 'A', 'D5', 'B', 'A']) zelda = deque(['E', 'G', 'D4', 'E', 'G', 'D4']) heal = deque(['B', 'A', 'F', 'B', 'A', 'F']) test = deque( ['C', 'D4', 'E', 'F', 'G', 'F']) #Not a Zelda song, just nice to make sure everything's working #heard note sequence deque notes = deque(['G', 'G', 'G', 'G', 'G', 'G'], maxlen=6) # Show the most intense frequency detected (useful for configuration) frequencyoutput = True freqNow = 1.0 freqPast = 1.0 #Set up audio sampler - NUM_SAMPLES = 2048 SAMPLING_RATE = 48000 #make sure this matches the sampling rate of your mic! with noalsaerr(): pa = pyaudio.PyAudio() _stream = pa.open(format=pyaudio.paInt16, channels=1, rate=SAMPLING_RATE, input=True, frames_per_buffer=NUM_SAMPLES) #print("Alarm detector working. Press CTRL-C to quit.") while True: while _stream.get_read_available() < NUM_SAMPLES: sleep( 0.01 ) #Retourne le nombre d'image qui peuvent etre lue sans attendre audio_data = frombuffer(_stream.read(_stream.get_read_available()), dtype=short)[-NUM_SAMPLES:] # Each data point is a signed 16 bit number, so we can normalize by dividing 32*1024 normalized_data = audio_data / 32768.0 #print(type(NUM_SAMPLES)) #print("La taille du tableau audio est :", +audio_data.size) #print("Le tableau de audio est :\n", +audio_data) #print("Le tableau de normalized est :\n", +normalized_data) #print("La taille du tableau normalise est :", +normalized_data) intensity = abs(fft.fft(normalized_data))[:int(NUM_SAMPLES // 2)] frequencies = linspace(0.0, float(SAMPLING_RATE) // 2, num=NUM_SAMPLES // 2) if frequencyoutput: which = intensity[1:].argmax() + 1 # use quadratic interpolation around the max if which != len(intensity) - 1: y0, y1, y2 = log(intensity[which - 1:which + 2:]) x1 = (y2 - y0) * .5 / (2 * y1 - y2 - y0) # find the frequency and output it freqPast = freqNow freqNow = (which + x1) * SAMPLING_RATE / NUM_SAMPLES else: freqNow = which * SAMPLING_RATE / NUM_SAMPLES # print "\t\t\t\tfreq=",freqNow,"\t",freqPast if minC <= freqPast <= maxD5 and abs(freqNow - freqPast) <= 25: if minA <= freqPast <= maxA and minA <= freqNow <= maxA and notes[ -1] != 'A': notes.append( 'A') #La note A (La) est ajoutée au tableau de note GPIO.output(26, GPIO.LOW) #LED éteinte GPIO.output(19, GPIO.LOW) GPIO.output(13, GPIO.HIGH) #LED allumée GPIO.output(6, GPIO.LOW) GPIO.output(5, GPIO.LOW) print("You played A!") elif minF <= freqPast <= maxF and minF <= freqNow <= maxF and notes[ -1] != 'F': notes.append('F') GPIO.output(26, GPIO.LOW) GPIO.output(19, GPIO.LOW) GPIO.output(13, GPIO.LOW) GPIO.output(6, GPIO.HIGH) GPIO.output(5, GPIO.LOW) print("You played F!") elif freqPast <= maxD4 and minD4 <= freqNow <= maxD4 and notes[ -1] != 'D4': notes.append('D4') GPIO.output(26, GPIO.LOW) GPIO.output(19, GPIO.LOW) GPIO.output(13, GPIO.LOW) GPIO.output(6, GPIO.LOW) GPIO.output(5, GPIO.HIGH) print("You played D4!") elif minD5 <= freqPast <= maxD5 and minD5 <= freqNow <= maxD5 and notes[ -1] != 'D5': notes.append('D5') GPIO.output(26, GPIO.LOW) GPIO.output(19, GPIO.HIGH) GPIO.output(13, GPIO.LOW) GPIO.output(6, GPIO.LOW) GPIO.output(5, GPIO.LOW) print("You played D5!") elif minB <= freqPast <= maxB and minB <= freqNow <= maxB and notes[ -1] != 'B': notes.append('B') GPIO.output(26, GPIO.HIGH) GPIO.output(19, GPIO.LOW) GPIO.output(13, GPIO.LOW) GPIO.output(6, GPIO.LOW) GPIO.output(5, GPIO.LOW) print("You played B!") elif minE <= freqPast <= maxE and minE <= freqNow <= maxE and notes[ -1] != 'E': notes.append('E') GPIO.output(26, GPIO.HIGH) GPIO.output(19, GPIO.LOW) GPIO.output(13, GPIO.LOW) GPIO.output(6, GPIO.LOW) GPIO.output(5, GPIO.LOW) print("You played E!") elif minG <= freqPast <= maxG and minG <= freqNow <= maxG and notes[ -1] != 'G': notes.append('G') GPIO.output(26, GPIO.LOW) GPIO.output(19, GPIO.HIGH) GPIO.output(13, GPIO.LOW) GPIO.output(6, GPIO.LOW) GPIO.output(5, GPIO.LOW) print("You played G!") elif minC <= freqPast <= maxC and minC <= freqNow <= maxC and notes[ -1] != 'C': notes.append('C') GPIO.output(26, GPIO.LOW) GPIO.output(19, GPIO.HIGH) GPIO.output(13, GPIO.LOW) GPIO.output(6, GPIO.LOW) GPIO.output(5, GPIO.LOW) print("You played C!") else: print( "What the heck is that?" ) #prints when sound is in range but not identifiable as note #or when a note has already been registered and is "heard" again if notes == sun: print("Sun song") confirm.play() notes.append( 'G' ) #append with 'G' to 'reset' notes, this keeps the song from triggering constantly if notes == forest: print("Minuet of Forest!") client.publish("songID", "4") #4=Forest confirm.play() notes.append('G') if notes == test: print("Musique de test reconnue !") client.publish("WifiEnigma/song", "TestSong") #4=Forest confirm.play() notes.append('G')
def filter_signal(signal, fs, cutoff, ftype="bessel", order=2, analog=False): """ Apply an analog filter to a signal for simulating e.g. electrical bandwidth limitation Parameters ---------- signal : array_like input signal array fs : float sampling frequency of the input signal cutoff : float 3 dB cutoff frequency of the filter ftype : string, optional filter type can be either a bessel, butter, exp or gauss filter (default=bessel) order : int order of the filter Returns ------- signalout : array_like filtered output signal """ sig = np.atleast_2d(signal) if ftype == "gauss": f = np.linspace(-fs / 2, fs / 2, sig.shape[1], endpoint=False, dtype=sig.dtype) w = cutoff / ( 2 * np.sqrt(2 * np.log(2)) ) # might need to add a factor of 2 here do we want FWHM or HWHM? g = np.exp(-f**2 / (2 * w**2)) fsignal = scifft.fftshift( scifft.fft(scifft.fftshift(sig, axes=-1), axis=-1), axes=-1) * g if signal.ndim == 1: return scifft.fftshift(scifft.ifft( scifft.fftshift(fsignal))).flatten() else: return scifft.fftshift(scifft.ifft(scifft.fftshift(fsignal))) if ftype == "exp": f = np.linspace(-fs / 2, fs / 2, sig.shape[1], endpoint=False, dtype=sig.dtype) w = cutoff / ( np.sqrt(2 * np.log(2)**2) ) # might need to add a factor of 2 here do we want FWHM or HWHM? g = np.exp(-np.sqrt((f**2 / (2 * w**2)))) g /= g.max() fsignal = scifft.fftshift(scifft.fft(scifft.fftshift(signal))) * g if signal.ndim == 1: return scifft.fftshift(scifft.ifft( scifft.fftshift(fsignal))).flatten() else: return scifft.fftshift(scifft.ifft(scifft.fftshift(fsignal))) Wn = cutoff * 2 * np.pi if analog else cutoff frmt = "ba" if analog else "sos" fs_in = None if analog else fs if ftype == "bessel": system = scisig.bessel(order, Wn, 'low', norm='mag', analog=analog, output=frmt, fs=fs_in) elif ftype == "butter": system = scisig.butter(order, Wn, 'low', analog=analog, output=frmt, fs=fs_in) if analog: t = np.arange(0, sig.shape[1]) * 1 / fs sig2 = np.zeros_like(sig) for i in range(sig.shape[0]): to, yo, xo = scisig.lsim(system, sig[i], t) sig2[i] = yo.astype(sig.dtype) else: sig2 = scisig.sosfilt(system.astype(sig.dtype), sig, axis=-1) if signal.ndim == 1: return sig2.flatten() else: return sig2
plt.ylabel("Амплітуда") plt.minorticks_on() plt.grid(which='major', linewidth=1.2) plt.grid(which='minor', linewidth=.5) plt.show() x = [x_random, x_net_noise, x_mixed, x_filtered] title = [["Прямокутний імпульс тривалістю 0.1с", "Амплітудний спектр"], ['Випадковий шумовий сигнал', 'Амплітудний спектр'], ['Зашумлений сигнал', 'Амплітудний спектр'], ['Відфільтрований сигнал', 'Амплітудний спектр']] x_label = ["Час, с", "Частота, Гц"] figure, axes = plt.subplots(len(x), 2, constrained_layout=True) figure.set_size_inches(12, 6) for i, ax in enumerate(axes): y = 2 * np.abs(fft(x[i]) / len(x[i])) ax[0].plot(t, x[i]) ax[1].stem(f, y) ax[1].set_xlim(0, sample_rate / 2) if i == 3: ax[0].set_ylim(-.01, .01) for j in range(2): ax[j].set_xlabel(x_label[j]) ax[j].set_title(title[i][j]) ax[j].set_ylabel("Амплітуда") ax[j].minorticks_on() ax[j].grid(which='major', linewidth=1.2) ax[j].grid(which='minor', linewidth=.5) plt.show()
def kinetic(self, sobo=False): """Get the Kinetic (Using Cartesian Coordinates, NO gaussian product rule, fft). Parameters ---------- sobo : Bool If True, use sobolev preconditioning. If False, no sobolev preconditioning. Returns ------- numpy array The kinetic matrix. """ spacing = (self.max_r - self.min_r) / (self.num_of_div - 1) r_freq = spyfft.fftfreq(self.num_of_div, spacing) K_mat = np.zeros((self.num_of_basis, self.num_of_basis), dtype=complex) for mu in range(self.num_of_basis): for nu in range(self.num_of_basis): kinetic_mu_nu_temp = 0 for p in range(self.num_of_gauss): for q in range(self.num_of_gauss): int_func_x1 = self.GF( self.a_overlap_mat[p][mu], self.r - self.atomic_position[mu][0]) int_func_y1 = self.GF( self.a_overlap_mat[p][mu], self.r - self.atomic_position[mu][1]) int_func_z1 = self.GF( self.a_overlap_mat[p][mu], self.r - self.atomic_position[mu][2]) int_func_x2 = self.GF( self.a_overlap_mat[q][nu], self.r - self.atomic_position[nu][0]) int_func_y2 = self.GF( self.a_overlap_mat[q][nu], self.r - self.atomic_position[nu][1]) int_func_z2 = self.GF( self.a_overlap_mat[q][nu], self.r - self.atomic_position[nu][2]) integrate_x = spyint.simpson( np.multiply(int_func_x1, spyfft.ifft(spyfft.fft(int_func_x2))), self.r) integrate_y = spyint.simpson( np.multiply(int_func_y1, spyfft.ifft(spyfft.fft(int_func_y2))), self.r) integrate_z = spyint.simpson( np.multiply(int_func_z1, spyfft.ifft(spyfft.fft(int_func_z2))), self.r) if sobo is False: integrate_x_d = spyint.simpson( np.multiply( int_func_x1, spyfft.ifft((0.5) * ((2 * np.pi)**2) * (r_freq**2) * spyfft.fft(int_func_x2))), self.r) integrate_y_d = spyint.simpson( np.multiply( int_func_y1, spyfft.ifft((0.5) * ((2 * np.pi)**2) * (r_freq**2) * spyfft.fft(int_func_y2))), self.r) integrate_z_d = spyint.simpson( np.multiply( int_func_z1, spyfft.ifft((0.5) * ((2 * np.pi)**2) * (r_freq**2) * spyfft.fft(int_func_z2))), self.r) elif sobo is True: integrate_x_d = spyint.simpson( np.multiply( int_func_x1, spyfft.ifft( (0.5) * ((2 * np.pi)**2) * (r_freq**2) * spyfft.fft(int_func_x2) / (1 + (0.5) * ((2 * np.pi)**2) * (r_freq**2)))), self.r) integrate_y_d = spyint.simpson( np.multiply( int_func_y1, spyfft.ifft( (0.5) * ((2 * np.pi)**2) * (r_freq**2) * spyfft.fft(int_func_y2) / (1 + (0.5) * ((2 * np.pi)**2) * (r_freq**2)))), self.r) integrate_z_d = spyint.simpson( np.multiply( int_func_z1, spyfft.ifft( (0.5) * ((2 * np.pi)**2) * (r_freq**2) * spyfft.fft(int_func_z2) / (1 + (0.5) * ((2 * np.pi)**2) * (r_freq**2)))), self.r) kinetic_mu_nu_temp += self.d_overlap_mat[p][ mu] * self.d_overlap_mat[q][nu] * ( 2 * self.a_overlap_mat[p][mu] / m.pi )**(3 / 4) * ( 2 * self.a_overlap_mat[q][nu] / m.pi )**(3 / 4) * ( (integrate_x_d * integrate_y * integrate_z) + (integrate_x * integrate_y_d * integrate_z) + (integrate_x * integrate_y * integrate_z_d)) # print(kinetic_mu_nu_temp) # print("Kinetic", kinetic_mu_nu_temp) K_mat[mu][nu] += kinetic_mu_nu_temp return np.real(K_mat)
def _loop_over_Q(self, proc, invars, Qpoints): """ this target is passed to each mp Process. it loops over the Q points assigned to each process and puts the results into the Queue. a background process collects all of this and assembles to total S(Q,w), S(Q), etc. arrays. could be easily modified to work in serial. """ # get the inds of which Q to do Q_inds = Qpoints.Q_on_procs[proc] # get how many there are num_Q = len(Q_inds) # return dummy (None) sqw array if not requested if invars.compute_sqw: sqw_pp = np.zeros((self.num_freq, num_Q)) else: sqw_pp = None # return dummy (None) bragg array if not requested if invars.compute_bragg: bragg_pp = np.zeros(num_Q) else: bragg_pp = None # return dummy (None) timeavg array if not requested if invars.compute_timeavg: timeavg_pp = np.zeros(num_Q) else: timeavg_pp = None # loop over the Q points for qq in range(num_Q): # print status if on proc 0 if proc == 0: message = f' now on Q-point {qq+1} out of {num_Q}' print_stdout(message) # the Qpoint to do Q_ind = Q_inds[qq] Q = Qpoints.total_Qpoints[Q_ind, :].reshape((1, 3)) # 1/Angstrom # TS: 10.13.2021: this line of code doesnt seemed to be used anywhere self.Q_norm = np.sqrt(Q[0, 0]**2 + Q[0, 1]**2 + Q[0, 2]**2) # |Q| # if xray, need to compute f(|Q|), which are placed in self.xlengths if invars.exp_type == 'xray': self.xlengths_tools.compute_xray_form_fact(self, invars) # space FT by vectorized Q.r dot products and sum over atoms. (tile prepends new axes) exp_iQr = np.tile(Q, reps=[self.block_steps, invars.num_atoms, 1 ]) * self.pos # Q.r exp_iQr = np.exp( 1j * exp_iQr.sum(axis=2)) * self.xlengths # sum over x, y, z exp_iQr = exp_iQr.sum(axis=1) # sum over atoms # compute bragg intensity = |<rho(Q,t)>|**2 if invars.compute_bragg: bragg_pp[qq] = np.abs( (exp_iQr).mean())**2 / self.common_rescale # compute timeavg intensity = <|rho(Q,t)|**2> if invars.compute_timeavg: timeavg_pp[qq] = (np.abs(exp_iQr)** 2).mean() / self.common_rescale # compute dynamical intensity = |rho(Q,w)|**2 if invars.compute_sqw: sqw_pp[:, qq] = np.abs( fft(exp_iQr))**2 / self.sqw_norm / self.common_rescale # put this stuff into the 'Queue' so that some other process can put it into the main arrays self.mp_queue.put([sqw_pp, bragg_pp, timeavg_pp, proc])
ζ = np.linspace(0, 25, N) # Distancia adimensional z/L X, Z = np.meshgrid(χ, ζ) Ia = abs(1 + m * np.exp(-1j * np.pi * Λ * Z) * np.cos(2 * np.pi * X))**2 / 4 # Intensidad analítica en el plano XZ # In[3]: plt.figure(figsize=(10, 8)) plt.pcolormesh(Z, X, Ia, shading='auto') plt.xlabel(r'$\dfrac{z}{L}$', fontsize=16) plt.ylabel(r'$\dfrac{x}{L}$', fontsize=16) # In[4]: t = (1 + m * np.cos(2 * np.pi * χ)) / 2 # Transmitancia fftt = fft(t) fx = fftfreq(N, Δχ) Hf = [] for z in ζ: Hf.append(np.exp(-1j * np.pi * Λ * z * fx**2)) # Función de transferencia en z dado In = [] for i in range(len(ζ)): In.append(abs(ifft(fftt * Hf[i]))**2) # Intensidad numérica en el plano XZ # In[5]: plt.figure(figsize=(10, 8)) plt.pcolormesh(Z, X, In, shading='auto') plt.xlabel(r'$\dfrac{z}{L}$', fontsize=16) plt.ylabel(r'$\dfrac{x}{L}$', fontsize=16)
def selectorPlot(self): roi = self.selector[0].getRegion() if 1 < np.abs(roi[1] - roi[0]) < 30 or \ (1 < np.abs(roi[1] - roi[0]) and \ (self.plot_type.currentText() == 'Azimuth Window' or \ self.plot_type.currentText() == 'Jurkevic Azimuth') or \ self.plot_type.currentText() == 'Azimuth Colourmap'): ### TEMP stime = UTCDateTime(self.bam.setup.fireball_datetime) + roi[0] etime = UTCDateTime(self.bam.setup.fireball_datetime) + roi[1] win_len = float(self.win_len_e.text()) win_frac = float(self.win_frac_e.text()) try: pol_res = polarization_analysis(self.condensed_stream, win_len, win_frac, \ float(self.low_edits.text()), float(self.high_edits.text()), stime, etime, adaptive=True) except ValueError: pol_res = {} pol_res['azimuth'] = np.nan pol_res['timestamp'] = np.nan except IndexError: pol_res = {} pol_res['azimuth'] = np.nan pol_res['timestamp'] = np.nan print( "Too many indicies for array - Not sure on this error yet") self.particle_motion_canvas.clear() self.waveform_canvas.clear() self.waveform_fft_canvas.clear() st_data = [None] * 3 ti_data = [None] * 3 raw_data = [None] * 3 noise_data = [None] * 3 for i in range(len(self.condensed_stream)): st = self.condensed_stream[i].copy() stn = self.stn delta = st.stats.delta start_datetime = st.stats.starttime.datetime end_datetime = st.stats.endtime.datetime stn.offset = ( start_datetime - self.bam.setup.fireball_datetime).total_seconds() self.current_waveform_delta = delta self.current_waveform_time = np.arange(0, st.stats.npts / st.stats.sampling_rate, \ delta) time_data = np.copy(self.current_waveform_time) st.detrend() resp = stn.response st2 = st.copy() st2 = st2.remove_response(inventory=resp, output="DISP") # st2.remove_sensitivity(resp) waveform_data = st2.data waveform_data = waveform_data[:len(time_data)] time_data = time_data[:len(waveform_data)] + stn.offset self.current_waveform_processed = waveform_data number_of_pts_per_s = st.stats.sampling_rate len_of_region = roi[1] - roi[0] num_of_pts_in_roi = len_of_region * number_of_pts_per_s num_of_pts_in_offset = np.abs(number_of_pts_per_s * stn.offset) num_of_pts_to_roi = roi[0] * number_of_pts_per_s pt_0 = int(num_of_pts_in_offset + num_of_pts_to_roi) pt_1 = int(pt_0 + num_of_pts_in_roi) raw_data[i] = waveform_data[pt_0:pt_1] noise_data[i] = waveform_data[0:(pt_1 - pt_0)] ##### # Bandpass ##### low = float(self.low_edits.text()) high = float(self.high_edits.text()) if low > 0 and high > 0: # Init the butterworth bandpass filter butter_b, butter_a = butterworthBandpassFilter(low, high, \ 1.0/self.current_waveform_delta, order=2) # Filter the data waveform_data = scipy.signal.filtfilt( butter_b, butter_a, np.copy(waveform_data)) # waveform_data = st.data # butter_b, butter_a = butterworthBandpassFilter(float(self.low_edits.text()), float(self.high_edits.text()), \ # 1.0/self.current_waveform_delta, order=6) # # Filter the data # waveform_data = scipy.signal.filtfilt(butter_b, butter_a, np.copy(waveform_data)) st_data[i] = waveform_data[pt_0:pt_1] ti_data[i] = time_data[pt_0:pt_1] e_r, n_r, z_r = raw_data[0], raw_data[1], raw_data[2] e_n, n_n, z_n = noise_data[0], noise_data[1], noise_data[2] e, n, z = st_data[0], st_data[1], st_data[2] et, nt, zt = ti_data[0], ti_data[1], ti_data[2] e = np.array(e) n = np.array(n) def fit_func(beta, x): return beta[0] * x data = scipy.odr.Data(e, n) model = scipy.odr.Model(fit_func) odr = scipy.odr.ODR(data, model, beta0=[1.0]) out = odr.run() az_slope = out.beta[0] az_error = out.sd_beta[0] azimuth = np.arctan2(1.0, az_slope) az_error = np.degrees(1.0 / ((1.0**2 + az_slope**2) * azimuth) * az_error) z = np.array(z) r = np.sqrt(n**2 + e**2) * np.cos(azimuth - np.arctan2(n, e)) data = scipy.odr.Data(r, z) model = scipy.odr.Model(fit_func) odr = scipy.odr.ODR(data, model, beta0=[1.0]) out = odr.run() in_slope = out.beta[0] in_error = out.sd_beta[0] x_h, y_h = np.abs(scipy.signal.hilbert(st_data[0])), np.abs( scipy.signal.hilbert(st_data[1])) data = scipy.odr.Data(x_h, y_h) model = scipy.odr.Model(fit_func) odr = scipy.odr.ODR(data, model, beta0=[1.0]) out = odr.run() h_az_slope = out.beta[0] h_az_error = out.sd_beta[0] h_azimuth = np.arctan2(1.0, h_az_slope) h_az_error = np.degrees( 1.0 / ((1.0**2 + h_az_slope**2) * h_azimuth) * h_az_error) incidence = np.arctan2(1.0, in_slope) in_error = np.degrees(1.0 / ((1.0**2 + in_slope**2) * incidence) * in_error) azimuth = np.degrees(azimuth) incidence = np.degrees(incidence) # Fit to lines using orthoganal distance regression to a linear function if self.group_no == 0: pen = QColor(0, 255, 0) brush = QColor(0, 255, 0, 125) else: pen = QColor(0, 0, 255) brush = QColor(0, 0, 255, 125) if self.plot_type.currentText() == 'Azimuth': p_mot_plot = pg.PlotDataItem() p_mot_plot.setData(x=e, y=n) self.particle_motion_canvas.addItem( pg.InfiniteLine(pos=(0, 0), angle=90 - azimuth, pen=pen)) self.particle_motion_canvas.setLabel( 'bottom', "Channel: {:}".format( self.condensed_stream[0].stats.channel)) self.particle_motion_canvas.setLabel( 'left', "Channel: {:}".format( self.condensed_stream[1].stats.channel)) self.particle_motion_canvas.addItem(p_mot_plot) self.particle_motion_canvas.addItem(pg.TextItem(text='Azimuth = {:.2f}° ± {:.2f}°'.format(azimuth, az_error), color=(255, 0, 0), \ anchor=(0, 0))) self.particle_motion_canvas.setXRange(np.min(e), np.max(e), padding=0) self.particle_motion_canvas.setYRange(np.min(n), np.max(n), padding=0) elif self.plot_type.currentText() == 'Incidence': p_mot_plot = pg.PlotDataItem() p_mot_plot.setData(x=r, y=z) self.particle_motion_canvas.addItem( pg.InfiniteLine(pos=(0, 0), angle=90 - incidence, pen=pen)) self.particle_motion_canvas.setLabel( 'bottom', "Horizontal in Direction of Azimuth") self.particle_motion_canvas.setLabel( 'left', "Channel: {:}".format( self.condensed_stream[2].stats.channel)) self.particle_motion_canvas.addItem(p_mot_plot) self.particle_motion_canvas.addItem(pg.TextItem(text='Incidence = {:.2f}° ± {:.2f}°'.format(incidence, in_error), color=(255, 0, 0), \ anchor=(0, 0))) self.particle_motion_canvas.setXRange(np.min(r), np.max(r), padding=0) self.particle_motion_canvas.setYRange(np.min(z), np.max(z), padding=0) elif self.plot_type.currentText() == 'Jurkevic Azimuth': # fix this bndps = [[0.001, 10], [0.1, 20], [1, 30]] for bb, b in enumerate(bndps): az_list, t_list = jurkevicWindows(z_r, n_r, e_r, st.stats, window_size=win_len, window_overlap=win_frac, bandpass=b) p_mot_plot = pg.ScatterPlotItem() p_mot_plot.setData(x=t_list, y=az_list, pen=pg.intColor(bb), \ brush=pg.intColor(bb), name="Bandpass: {:} - {:} Hz".format(b[0], b[1])) self.particle_motion_canvas.addItem(p_mot_plot) # print("{:} -> Bandpass: {:} - {:} Hz".format(pg.intColor(bb), b[0], b[1])) self.particle_motion_canvas.setLabel('bottom', "Time") self.particle_motion_canvas.setLabel('left', "Azimuth") self.particle_motion_canvas.setXRange(0, np.max(t_list), padding=0) self.particle_motion_canvas.setYRange(0, 180, padding=0) self.particle_motion_canvas.setLimits(xMin=0, xMax=np.max(t_list), yMin=0, yMax=180) elif self.plot_type.currentText() == 'Azimuth Colourmap': bandpass_low = float(self.low_edits.text()) bandpass_high = float(self.high_edits.text()) bins = 15 bin_overlap = 0.5 # this equation is wrong size_of_bin = ((bandpass_high - bandpass_low) - (bins - 1) * bin_overlap) / bins lows = np.linspace(bandpass_low, bandpass_high - size_of_bin, bins) highs = np.linspace(bandpass_low + size_of_bin, bandpass_high, bins) bndps = [] for i in range(len(lows)): bndps.append([lows[i], highs[i]]) total_list = [] for bb, b in enumerate(bndps): az_list, t_list = jurkevicWindows(z_r, n_r, e_r, st.stats, window_size=win_len, window_overlap=1.0, bandpass=b) total_list.append(az_list) img = pg.ImageItem() self.particle_motion_canvas.addItem(img) az_img = np.array(total_list) img.setImage(np.transpose(az_img)) img.scale(t_list[-1]/np.size(az_img, axis=1),\ lows[-1]/np.size(az_img, axis=0)) img.translate(0, bandpass_low) self.hist = pg.HistogramLUTItem() # Link the histogram to the image self.hist.setImageItem(img) if self.added: self.waveform_hist_view.clear() self.waveform_hist_view.addItem(self.hist) self.added = True # Fit the min and max levels of the histogram to the data available self.hist.setLevels(np.min(az_img), np.max(az_img)) # This gradient is roughly comparable to the gradient used by Matplotlib # You can adjust it and then save it using hist.gradient.saveState() self.hist.gradient.restoreState({ 'mode': 'rgb', 'ticks': [(0.5, (0, 182, 188, 255)), (1.0, (246, 111, 0, 255)), (0.0, (75, 0, 113, 255))] }) self.particle_motion_canvas.setLimits(xMin=0, xMax=t_list[-1] + bandpass_low, yMin=bandpass_low, yMax=bandpass_high) self.hist.setHistogramRange(0, 180) # self.particle_motion_canvas.setLookupTable(self.hist) # elif self.plot_type.currentText() == 'Abercrombie 1995': # STEP_DEG = 1 #deg # ba_list = np.arange(0, 360, STEP_DEG) # raw_stream = self.condensed_stream[i].copy() # for ba in ba_list: # raw_stream.rotate('NE->RT', back_azimuth=ba) else: az_window = pol_res['azimuth'] # times are in unix time, casting UTCDatetime to float makes it also unix t_window = pol_res['timestamp'] - float(stime) az_win_error = pol_res['azimuth_error'] p_mot_plot = pg.ScatterPlotItem() p_mot_plot.setData(x=t_window, y=az_window) p_mot_plot_err = pg.ErrorBarItem() p_mot_plot_err.setData(x=t_window, y=az_window, height=az_win_error) azimuth = np.mean(az_window) az_error = np.std(az_window) self.particle_motion_canvas.setLabel('bottom', "Time") self.particle_motion_canvas.setLabel('left', "Azimuth") self.particle_motion_canvas.addItem( pg.InfiniteLine(pos=(0, azimuth), angle=0, pen=pen)) self.particle_motion_canvas.addItem(pg.TextItem(text='Azimuth = {:.2f}° ± {:.2f}°'.format(azimuth, az_error), color=(255, 0, 0), \ anchor=(0, 0))) self.particle_motion_canvas.addItem(p_mot_plot_err) self.particle_motion_canvas.addItem(p_mot_plot) self.particle_motion_canvas.setXRange(0, np.max(t_window), padding=0) self.particle_motion_canvas.setYRange(0, 180, padding=0) # self.particle_motion_canvas.getViewBox().setLimits(xMin=0, xMax=15, # yMin=range_[1][0], yMax=range_[1][1]) self.azimuth = azimuth self.az_error = az_error roi_waveform = pg.PlotDataItem() pts = np.linspace(pt_0/st.stats.sampling_rate + stn.offset - roi[0], \ pt_1/st.stats.sampling_rate + stn.offset - roi[0], num=len(z)) roi_waveform.setData(x=pts, y=bandpassFunc(z, 2, 8, st.stats.delta)) self.waveform_canvas.addItem(roi_waveform) sps = st.stats.sampling_rate dt = 1 / st.stats.sampling_rate length = len(z_r) freq = np.linspace(1 / len_of_region, (sps / 2), length) * sps / length FAS = abs(fft(z_r)) FAS_n = abs(fft(z_n)) fas_data = pg.PlotDataItem() fas_data.setData(x=freq, y=FAS, pen=(255, 0, 0)) fas_noise_data = pg.PlotDataItem() fas_noise_data.setData(x=freq, y=FAS_n, pen=(255, 255, 255)) fas_diff_data = pg.PlotDataItem() fas_diff_data.setData(x=freq, y=np.abs(FAS / FAS_n), pen=(0, 125, 255)) print("Red - Data", "White - Noise", "Blue - Data/Noise") self.waveform_fft_canvas.addItem(fas_data) self.waveform_fft_canvas.addItem(fas_noise_data) self.waveform_fft_canvas.addItem(fas_diff_data)
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)
def digitize(x): if bitdepth is 0: return x a = (2**bitdepth-1) return float64(int32(a*x/max(x)))/a def dB(x): return 10*log10(x) def add_detail(x): if x =='0': return 'non-digitalized' return x+' bit' X = linspace(-7, 7, nsamples) #plot(X,f(X)) bds = [0, 8, 12, 16] for bitdepth in bds: plot(dB(abs(fft.fftshift(fft.fft(digitize(f(X))))))) legend(map(lambda x:add_detail(str(x)),bds),loc='upper left') xlabel('frequency domain (a.u.)') ylabel('signal (dB)') #ns = [512, 1024, 2048] #bitdepth = 8 #for nsamples in ns: # X = linspace(-7, 7, nsamples) # K = X*nsamples/512.0 # plot(K,dB(abs(fft.fftshift(fft.fft(digitize(f(X))))))) #legend(map(str,ns))