def simple_cf_dft_analysis(): global lrss_lengths_dft lrss_lengths_dft = dft.dft(lrss_lengths) global lrss_first_index_dft lrss_first_index_dft = dft.dft(lrss_first_index) global max_value_dft max_value_dft = dft.dft(max_values) global zero_1_simple_cf_dft zero_1_simple_cf_dft = dft.dft(zero_1_simple_cf) global zero_1_successive_diffs_dft zero_1_successive_diffs_dft = dft.dft(zero_1_successive_diffs)
def sectionDftNonInteger(): wave = sectionDftWave(sectionDftWavePoint, 8, 8500) result = dft(wave) x = 0 for z in result: za = z # Get the correct sign for polar form # magnitude, phase if z.imag != 0: za = complex(z.real, z.imag * -1) else: za = z # Change sign for displaying resolved rectagular form # X(m) = a - jb op = "-" if z.imag < 0.0: op = "+" z = complex(z.real, z.imag * -1) print("x({})\t{:.3f} {} j{:.3f}\t\t{}, {}".format(x,z.real, op, z.imag, mag(za), phase(za))) x = x + 1 mags = list(map(lambda z: mag(z), result)) fig, ax = plt.subplots() ax.bar(range(0,len(mags)), mags, align="center", color="green", ecolor="black", width=1/8) ax.set_xticks(range(0,len(mags))) plt.show()
def INT_TEST(): print('INT TEST:\n\n') #signal x x = [] #making signal a sine wave amount = 8 n = 0 inkrement = 1 i = 0 for i in range(amount): x.append(n) n = n + inkrement N = len(x) #Diskrete-Fourier-Transformation X = around(dft(x), decimals=6) print('Diskrete-Fourier-Transformation:') print(f'X = {X}\n') #amplitude and phase A = [None] * N p = [None] * N i = 0 for i in range(len(X)): temp1 = abs(X[i]) A[i] = temp1 temp2 = angle(X[i]) p[i] = temp2 #print(p[i]) print(f'Amplitude: A = {A}') print(f'Phase: p = {p}\n\n') #Fast-Fourier-Transformation X2 = around(fft(x), decimals=6) print('Fast-Fourier-Transformation:') print(f'X2 = {X2}\n') #amplitude and phase A2 = [None] * N p2 = [None] * N i = 0 for i in range(len(X2)): temp1 = abs(X2[i]) A2[i] = temp1 temp2 = angle(X[i]) p2[i] = temp2 print(f'Amplitude: A2 = {A2}') print(f'Phase: p2 = {p2}\n\n\n') plt.plot(x, X, max(x))
def sectionZeroPadding(): N = 32 wave = sectionDftWave(waveSine3Hz, N, 8000) result = dft(wave) mags = list(map(lambda z: mag(z), result)) plt.figure().suptitle("L=16 N=16") plt.bar(range(0,len(mags)), mags, align="center", color="green", ecolor="black", width=1/8) wave = sectionDftWave(waveSine3Hz, N, 8000) zeroPad(wave, N * 1) result = dft(wave) mags = list(map(lambda z: mag(z), result)) plt.figure().suptitle("L=16 N=32") plt.bar(range(0,len(mags)), mags, align="center", color="green", ecolor="black", width=1/8) wave = sectionDftWave(waveSine3Hz, N, 8000) zeroPad(wave, N * 2) result = dft(wave) mags = list(map(lambda z: mag(z), result)) plt.figure().suptitle("L=16 N=64") plt.bar(range(0,len(mags)), mags, align="center", color="green", ecolor="black", width=1/8) wave = sectionDftWave(waveSine3Hz, N, 8000) zeroPad(wave, N * 4) result = dft(wave) mags = list(map(lambda z: mag(z), result)) plt.figure().suptitle("L=16 N=128") plt.bar(range(0,len(mags)), mags, align="center", color="green", ecolor="black", width=1/8) wave = sectionDftWave(waveSine3Hz, N, 8000) zeroPad(wave, N * 8) result = dft(wave) mags = list(map(lambda z: mag(z), result)) plt.figure().suptitle("L=16 N=256") plt.bar(range(0,len(mags)), mags, align="center", color="green", ecolor="black", width=1/8) plt.show()
def main(): graphics = Graphics() # NUM_CYCLES = 5 # data = build_data(NUM_CYCLES) file = 'train.json' point_data = load_json(file) signal_data = dft(point_data) graphics.epicycles = build_epicycles(graphics.screen, signal_data) graphics.init_callback()
def AC_TEST_with_zero_padding(): print('AC TEST with zero padding:\n\n') #signal x x = [] #making signal a sine wave amount = 8 n = 0 inkrement = 2 * pi / amount i = 0 for i in range(amount): x.append(sin(n) * 5) n = n + inkrement for i in range(amount * 4): x.append(0) N = len(x) #original signal print(f'signal: x = {x}\n\n') #Diskrete-Fourier-Transformation X = around(dft(x), decimals=6) print('Diskrete-Fourier-Transformation:') print(f'X = {X}\n') #amplitude and phase A = [None] * N p = [None] * N i = 0 for i in range(len(X)): temp1 = abs(X[i]) A[i] = temp1 temp2 = angle(X[i]) p[i] = temp2 #dividing by 1/N is not right anymore because of zero padding X = X * N / 8 print(f'Amplitude: A = {A}') print(f'Phase: p = {p}\n\n') plt.plot(x, X, max(x))
def dft1d_test(n): print(f"Testing DFT for n = {n}") x = np.random.randint(100,size=(n)) start = time.time() res1 = dft(x) end = time.time() - start print(f"My DFT Time: {end}, ",end=' ') start = time.time() res2 = np.fft.fft(x) end = time.time() - start print(f"Numpy time: {end}") close = np.allclose(res1, res2) if not close: print("Wrong answer") else: print("OK")
def testsignal(): N = 4096 signal = np.zeros(N) x = np.arange(N) signal += GAUSS(x, 601, 5.7, 2765) signal += GAUSS(x, 665, 6.0, 528) plt.clf() plt.plot(x, signal, '.') plt.xlabel("Kanal") plt.ylabel("simulierte Höhe") plt.savefig("out/testsignal." + SAVETYPE) f, fy = dft(signal) plt.clf() plt.plot(f, np.abs(fy), '.') plt.xlim(0, 0.15) plt.axvline(0.1) plt.xlabel("Frequenz") plt.ylabel("Betrag des Fouriertransformierten") plt.savefig("out/testsignal_dft." + SAVETYPE)
def compare(n): print(f"Comparing DFT and FFT for n = {n}") x = np.random.randint(100,size=(n)) start = time.time() res1 = dft(x) end = time.time() - start print(f"My DFT Time: {end}, ",end=' ') start = time.time() res2 = cooley_tukey_1d(x) end = time.time() - start print(f"My FFT Time: {end}, ",end=' ') start = time.time() res_np = np.fft.fft(x) end = time.time() - start print(f"Numpy time: {end}") close = np.allclose(res1, res_np) and np.allclose(res2, res_np) if not close: print("Wrong answer") else: print("OK")
def sin_gen(): for i in range(XX_CNT): # sig1[i] = 10*math.sin(2 * math.pi * f1 * i * ts) sig2[i] = math.sin(2 * math.pi * f2 * i * ts) XX[i] = sig1[i] + sig2[i] def rectangular_to_polar(): for k in range(DFT_CNT): MAG[k] = math.sqrt(math.pow(REX[k], 2) + math.pow(IMX[k], 2)) PHASE[k] = math.atan2(IMX[k], REX[k]) if __name__ == '__main__': sin_gen() dft.dft(XX, XX_CNT, REX, IMX) rectangular_to_polar() pyplot.subplot(231) pyplot.plot(XX) pyplot.subplot(232) pyplot.plot(REX) print(REX) pyplot.subplot(233) pyplot.plot(IMX) pyplot.subplot(234) pyplot.plot(MAG) pyplot.subplot(235) pyplot.plot(PHASE) pyplot.show()
color='blue', label='imaginary') plt.ylabel(r'$G^R(\tau)$') plt.xlabel(r'$J\,\tau$') plt.legend() plt.tight_layout(padding) plt.savefig(pltfolder + 'green_%i.eps' % i, format='eps', dpi=1000) plt.clf() ### plt.title(r'Spectral function of level $%i$' % i) if not os.path.isfile('../data/spectral_%i.txt' % i) or True: green_ret = greendat[:, ind] + 1j * greendat[:, ind + 1] if i == 0: sample_spacing = (greendat[-1, 0] - greendat[0, 0]) / (len(green_ret) - 1) green_ret_freq = dft.rearrange(dft.dft(green_ret, 1.0 / sample_spacing)) spec_tmp = np.column_stack( (green_ret_freq[:, 0].real, -2 * green_ret_freq[:, 1].imag)) print(np.shape(spec_tmp)) np.savetxt('../data/spectral_%i.txt' % i, spec_tmp, "%16e", delimiter=' ') else: spec_tmp = np.loadtxt('../data/spectral_%i.txt' % i) if i == 0: spec_total = spec_tmp[:] else: spec_total[:, 1] += spec_tmp[:, 1] spec.append(spec_tmp) plt.plot(spec_tmp[:, 0], spec_tmp[:, 1], color='red', lw=0.3)
from dft import dft from numpy import loadtxt from pylab import plot, show data = loadtxt('pitch.txt',float) mydft=dft() a=mydft.dft(data[:,3]) b=list(map(abs,a)) plot(b) show()
#! /usr/bin/python # # Test the fft and dft modules import fft import dft import math SIZE = 64 TWO_PI = 2.0*math.pi SCALE = TWO_PI/SIZE X = x = [0] * SIZE for i in range(0,SIZE): x[i] = complex( math.cos(4.0*i*SCALE), math.cos(6.0*i*SCALE) ) print "%d:%5.2f+%5.2fj" % ( i,x[i].real, x[i].imag ) X = fft.fft(x) print "FFT" for i in range(0,SIZE): print"%d:%5.2f+%5.2fj" % ( i,X[i].real,X[i].imag ) print "DFT" X = dft.dft(x) for i in range(0,SIZE): print "%d:%5.2f+%5.2fj" % ( i,X[i].real,X[i].imag )
def DC_TEST(): print('DC TEST:\n\n') #signal x x = [] #making a dc signal with 5V here amount = 8 n = 0 inkrement = 2 * pi / amount i = 0 for i in range(amount): x.append(5) n = n + inkrement N = len(x) #original signal print(f'signal: x = {x}\n\n') #if my ouput is the same it highly possible that is correct NUMPYFFT = around(npfft.fft(x), decimals=6) print(f'NumpyFFT = {NUMPYFFT}\n') print(f'Amplitude = {around(abs(NUMPYFFT), decimals=6)}') print(f'Phase = {around(npangle(NUMPYFFT), decimals=6)}\n\n') #Diskrete-Fourier-Transformation X = around(dft(x), decimals=6) print('Diskrete-Fourier-Transformation:') print(f'X = {X}\n') #amplitude and phase A = [None] * N p = [None] * N i = 0 for i in range(len(X)): temp1 = abs(X[i]) A[i] = temp1 temp2 = angle(X[i]) p[i] = temp2 print(f'Amplitude: A = {A}') print(f'Phase: p = {p}\n\n') #Fast-Fourier-Transformation X2 = around(fft(x), decimals=6) print('Fast-Fourier-Transformation:') print(f'X2 = {X2}\n') #amplitude and phase A2 = [None] * N p2 = [None] * N i = 0 for i in range(len(X2)): temp1 = abs(X2[i]) A2[i] = temp1 temp2 = angle(X[i]) p2[i] = temp2 print(f'Amplitude: A2 = {A2}') print(f'Phase: p2 = {p2}\n\n\n') plt.plot(x, X, max(x))
if __name__ == "__main__": Fs = 256 # points Ts = 1 / 256 # step t = np.arange(0, 1, Ts) F = 6 # Hz y = 8 * sp.sin(2 * sp.pi * F * t) n = len(y) T = n / Fs k = np.arange(n) frq = k / T frq = frq[range(n // 2)] fft = abs(dft(y)) fft = fft[range(n // 2)] ifft = idft(fft) n = len(ifft) fig, ax = plt.subplots(3, 1, figsize=(16, 9)) ax[0].plot(t, y) ax[1].stem(frq, fft, 'r') Fs = n Ts = 1 / Fs t = np.arange(0, 1, Ts) ax[2].plot(t, ifft) plt.show()
def compress(X, r): X = dft.dft(X) return o3.submatrix(X, math.ceil(len(X)*r), math.ceil(len(X[0])*r))
#!/usr/bin/env python import numpy as np import matplotlib.pyplot as pl from timeit import timeit from dft import dft import pylab pl.clf() # make sure dft(x) and np.fft.fft(x) output the same thing. # when I run this section, they do. test = pylab.randn(5) myfunc = dft(test) npfunc = np.fft.fft(test) print 'dft gives:' for item in myfunc: print item print 'np.fft.fft gives:' for item in npfunc: print item # compare times for dft and ff N = np.arange(10, 101) #sizes of the array to be transformed t1 = np.zeros(N.size)
from dft import dft t = np.arange(1e-5, 257e-5, 1e-5) # f_signal = f_nu filedict = np.load("../data/1_1_2/f_10000Hz.npz") data = filedict["arr_0"] title(r"$\nu_{sig}=\nu_{samp}=10 kHz$") plot(t, data) xlim(0, 0.0005) ylim(-1, 1) figure() # f_signal >> f_sample subplot(211) filedict = np.load("../data/1_1_2/fast_signal.npz") data = filedict["arr_0"] title(r"$\nu_{sig}=10MHz,\nu_{samp}=7kHz$") plot(t, data) # TODO plot an acutal 10MHz wave on top of this subplot(212) f_sample = 7e3 freq, data_fourier = dft(data, f_sample=f_sample, power=True, f_max=10e3, f_res=1.) title(r"$\nu_{sig}=10MHz,\nu_{samp}=7kHz$") plot(freq, data_fourier) # TODO plot actual foureir transform of 10MHZ sine wave on top of this
import numpy as np import matplotlib.pyplot as mp from dft import dft data= np.loadtxt("sunspots.txt", float) time = data[:,0] number_of_sunspots = data[:,1] mp.plot(time,number_of_sunspots, label="Number of Sunspots") mp.legend() mp.show() fourier = dft(number_of_sunspots) fourier = abs(fourier*fourier) mp.plot(list(map(abs,fourier))) mp.show()
data = filedict["arr_0"] ax = subplotaxes[x-1][0] ax.set_ylabel(r"$\nu_{sig}=%s kHz$" % x, rotation="horizontal", fontsize=14) ax.plot(t*1e3, data, "-o", linewidth=2) # plot actual waveform lightly # first line them up fitfunc = lambda t, A, phi: A * np.cos(2*pi*x*1e3*t + phi) (A, phi), _ = curve_fit(fitfunc, t, data) ax.plot(t2*1e3, A*np.cos(2*pi*x*1e3*t2 + phi), "b-", alpha=0.2, linewidth=4) ax.set_xlim(0, 2.0) ax.set_ylim(-1.4, 1.4) ax.set_yticklabels([], visible=False) f_sample = 10e3 freq, data_fourier = dft(data, f_sample=f_sample, power=True) ax = subplotaxes[x-1][1] # ax.set_title(r"$\nu_{sig}=%s kHz$" % x) ax.plot(freq*1e-3, data_fourier, linewidth=2) ax.set_yticklabels([], visible=False) ax.set_xlim(-6, 6) subplotaxes[-1][0].set_xlabel("time (ms)", fontsize=14) subplotaxes[-1][1].set_xlabel("freq (kHz)", fontsize=14) # Fine-tune figure; make subplots close to each other and hide x ticks for # all but bottom plot. f.subplots_adjust(hspace=0) # plt.setp([a.get_xticklabels() for a in f.axes[:-1]], visible=False) # generate example of mixing
def call_dft ( signal ) : dft.dft ( signal )
def dft_attack(seq_s, fun_f, fun_g): n = fun_f.degree() field = GF(2 ** n, name = 'gamma', modulus = fun_f) gamma = field.gen() seq_b_iv = [] for i in range(n): seq_b_iv.append(trace(gamma ** i)) seq_b_generator = lfsr(seq_b_iv, fun_f) seq_b = [] for i in range(2 ** n - 1): seq_b.append(seq_b_generator.next()) # print 'seq_b', seq_b seq_a = [] seq_b_doubled = seq_b * 2 # for ease of programming for i in range(2 ** n - 1): seq_a.append(GF(2)(fun_g(seq_b_doubled[i : (i + n)]))) fun_p = bma(seq_a) if len(seq_s) < fun_p.degree(): os.stderr.write("algorithm failed\n") os.exit(-1) # 2 coset_leaders = coset(2 ** n - 1) for k in coset_leaders: # coset() is changed? if 1 == gcd(k, 2 ** n - 1) and k is not 1: break # k_inverse = field(k).pth_power(-1) # not right? for i in range(2 ** n - 1): if (i * k) % (2 ** n - 1) == 1: k_inverse = i break #print 'k_inverse', k_inverse # 3 # print 'seq_a', seq_a # print type(seq_a[0]) (A_k, S_k) = dft(seq_s, seq_a) # print 'A_k', A_k # online phase # 1 # print 'seq_s', seq_s # two dft computations are combined now # print 'S_k', S_k # 2 # print 'k', k # print 'k_inverse', k_inverse # k_inverse = 13 gamma_tau = (S_k[k] * (A_k[k] ** (-1))) ** (k_inverse) # print gamma_tau # 3 result_u = [] for i in range(n): result_u.append(trace(gamma_tau * (gamma_tau.parent().gen() ** i))) return result_u
import matplotlib import matplotlib.pyplot as plt import rsg from dft import dft HARMONICS = 8 FREQUENCY = 1200 N = 1024 sigs = rsg.generate(HARMONICS, FREQUENCY, N) fig, (ax1, ax2) = plt.subplots(2, 1) ax1.plot(sigs) ax1.set_xlim(0, int(N/4)) ax1.set(xlabel='time', ylabel='signal', title='Random generated signals') ax2.plot(dft(sigs)) ax2.set_xlim(0, int(N/4)) ax2.set(xlabel='time', ylabel='frequency', title='Frequency spectrum using DFT') fig.savefig("example.png") plt.show()
# Ay 190 # WS6 import numpy as np import matplotlib.pyplot as pl from dft import dft from timeit import timeit import plot_defaults # PART A: Test of DFT Implementation (implemented in dft.py) x = np.random.randn(10) fft_x = np.fft.fft(x) print("Relative error of dft compared to np.fft for random input vector:") print(np.sqrt(np.sum(np.abs((dft(x) - fft_x))**2)) / np.sqrt(np.sum(np.abs(fft_x)**2))) # PARTS B+C: Characterization of Runtimes # Parameters ntrials = 10 Ns = range(10, 101) dft_runtimes = [] fft_runtimes = [] for N in Ns: dft_runtimes.append(timeit("dft(x)", number=ntrials, setup="from dft import dft; import numpy as np; x=np.random.randn({})".format(N)) / ntrials) fft_runtimes.append(timeit("np.fft.fft(x)", number=ntrials, setup="import numpy as np; x=np.random.randn({})".format(N)) / ntrials) # set up the figure and control white space
############# #обратное фурье от сдвига N = 500 left_border = -2 * np.pi right_border = 2 * np.pi shift = np.pi x = np.linspace(left_border, right_border, N) y = np.sin(2 * np.pi * x + np.pi) fft_lib_res = np.fft.fft(y) fft_lib_res_real = extract_real(fft_lib_res) fft_lib_res_im = extract_im(fft_lib_res) lib_res_module = calc_module(fft_lib_res) #my_calc my_res = my_dft.dft(y) xf = fftfreq(N, get_spacing_period(left_border, right_border, N)) reverse_dft = np.fft.ifft(fft_lib_res) reverse_dft_ = np.fft.ifft(lib_res_module) reverse_dft_module = calc_module(reverse_dft) fig = plt.figure() title = 'shifted sin ' subplot = fig.add_subplot(1, 2, 1) subplot.set_title(title + "Original curve") subplot.xaxis.set_ticks_position('bottom') subplot.yaxis.set_ticks_position('left') subplot.plot(x, y, 'b', label='Original curve') subplot.plot(x,
import time import rsg from dft import dft from fft import fft, real HARMONICS = 8 FREQUENCY = 1200 N = 1024 sigs = rsg.generate(HARMONICS, FREQUENCY, N) start = time.time() dft(sigs) print("discrete Fourier transform time: {}".format(time.time() - start)) start = time.time() fft(sigs) print("fast Fourier transform time: {}".format(time.time() - start))
def calc_and_plot(x, y, numb_of_signal_pts, spacing_period, title): fig = plt.figure() #library function calc fft_lib_res = np.fft.fft(y) fft_lib_res_real = extract_real(fft_lib_res) fft_lib_res_im = extract_im(fft_lib_res) # phases = calc_phase(fft_lib_res) #my_calc my_res = my_dft.dft(y) my_res_real = extract_real(my_res) my_res_im = extract_im(my_res) #difference between my and library diff_re = get_diff(fft_lib_res_real, my_res_real) diff_im = get_diff(fft_lib_res_im, my_res_im) xf = fftfreq(numb_of_signal_pts, spacing_period) fig = plt.figure() ''' subplot = fig.add_subplot(1, 4, 1) subplot.set_title(title + " Fourier Image(Re)") subplot.xaxis.set_ticks_position('bottom') subplot.yaxis.set_ticks_position('left')''' '''#getting the sampling frequencies subplot.plot(fftshift(xf), abs(fftshift(my_res_real))/numb_of_signal_pts, 'b', label = 'My dft, Re') subplot.plot(fftshift(xf), abs(fftshift(fft_lib_res_real))/numb_of_signal_pts, 'r--', label = 'Lib dft, Re') subplot.plot(fftshift(xf), abs(fftshift(diff_re))/numb_of_signal_pts, 'g', label = 'difference') #subplot.plot(x, y, 'yellow', label = 'Original') subplot.legend()''' '''subplot = fig.add_subplot(1, 4, 2) subplot.set_title(title + " Fourier Image(Im)") subplot.xaxis.set_ticks_position('bottom') subplot.yaxis.set_ticks_position('left') subplot.plot(fftshift(xf), abs(fftshift(my_res_im))/numb_of_signal_pts, 'b', label = 'My dft, Im') subplot.plot(fftshift(xf), abs(fftshift(fft_lib_res_im))/numb_of_signal_pts, 'r--', label = 'Lib dft, Im') subplot.plot(fftshift(xf), abs(fftshift(diff_im))/numb_of_signal_pts, 'g', label = 'difference') subplot.legend()''' subplot = fig.add_subplot(1, 2, 1) subplot.set_title(title + "Original") subplot.xaxis.set_ticks_position('bottom') subplot.yaxis.set_ticks_position('left') subplot.plot(x, y, 'b', label='Original curve') subplot.legend() my_res_module = calc_module(my_res) lib_res_module = calc_module(fft_lib_res) diff_module = get_diff(my_res_module, lib_res_module) subplot = fig.add_subplot(1, 2, 2) subplot.set_title(title + "Fourier image module") subplot.xaxis.set_ticks_position('bottom') subplot.yaxis.set_ticks_position('left') subplot.set_xlim(0, max(fftshift(xf))) subplot.plot(fftshift(xf), abs(fftshift(my_res_module)) / numb_of_signal_pts, 'b', label='My dft, |z|') subplot.plot(fftshift(xf), abs(fftshift(lib_res_module)) / numb_of_signal_pts, 'r--', label='Lib dft, |z|') subplot.plot(fftshift(xf), abs(fftshift(diff_module)) / numb_of_signal_pts, 'g', label='difference') subplot.plot(fftshift(xf), phases, 'black', label='phase') subplot.legend() fig.show()
# plt.figure(2) # dft.plot_dft_power(dft_var, (2, 4, i + 1), titles[i]) # # plt.figure(3) # plt.subplot(2, 4, i+1) # plt.plot(variable, '-b', label="Original") # plt.plot(dft.idft(dft_var, 51), ':r', label="IDFT") # plt.legend(loc='upper right') # # plt.show() # for n in range(0, 50): # coeffs = [] # # for variable in data: # coeffs.append(dft.idft_get(dft.dft(variable), n, 51)) # # print(f"{n}: " + str(coeffs)) coeffs = [] n = 50 for variable in data: coeffs.append(round(dft.idft_get(dft.dft(variable), n - 1, 51))) print( cf.hk_decode_to_decimal( cf.hk_quadlin_gen_decode(coeffs[0], coeffs[1], coeffs[2:], 15), 10)) print(coeffs) # print(cf.hk_decode_to_decimal(cf.hk_quadlin_gen_decode(19, 5, [-7, -5, -13, 13, -11], 15), 10))
print "downsampling time-domain data : dt=%fe-6 -> dt=%fe-6"%(dt*1e6, _dt*1e6) if opts.time: to = time.time() vec, dt = dft.resample(vec, dt, _dt, method=resample_method) if opts.time: print "\t", time.time()-to ### check that we have all the data we expect if len(vec)*dt != seglen: raise ValueError, "len(vec)*dt = %f != %f = seglen"%(len(vec)*dt, seglen) ### compute windowing function win = dft.window(vec, kind="tukey", alpha=2*padding/seglen) ### store noise dft_vec, dft_freqs = dft.dft(vec*win, dt=dt) if np.any(dft_freqs != freqs): raise ValueError, "frequencies from utils.dft do not agree with freqs defined by hand" noise[:,ifo_ind] = dft_vec else: if opts.verbose: print "no noise generation specified. zero-ing noise" noise = np.zeros((n_freqs, n_ifo), complex) ### dump noise to file if opts.diagnostic: ### save noise to file noise_filename = "%s/noise%s_%d.pkl"%(opts.output_dir, opts.tag, int(opts.gps)) if opts.verbose: print "writing noise to %s"%noise_filename
import numpy as np import matplotlib.pyplot as mp from dft import dft pi = 3.14159 N = 1000 x = np.linspace(1, N, 501) square = np.zeros(N, complex) for i in range(1, N // 2): square[i] = 1.0 mp.plot(list(map(abs, dft(square)))) mp.show() sawtooth = np.empty(N, complex) for i in range(N): sawtooth[i] = i mp.plot(list(map(abs, dft(sawtooth)))) mp.show() mod_sine = np.empty(N, complex) for n in range(N): mod_sine[n] = np.sin(pi * n / N) * np.sin(20 * pi * n / N) mp.plot(list(map(abs, dft(mod_sine)))) mp.show()
t = np.arange(0, T_dur, Ts) # time vector #t = np.linspace(0,T_dur,Fs) ff_1 = 5 ff_2 = 53 ff_3 = 34 # frequency of the signal y = np.sin(2 * np.pi * ff_1 * t) + np.sin(2 * np.pi * ff_2 * t) + np.sin( 2 * np.pi * ff_3 * t) n = len(y) # length of the signal k = np.arange(n) T = n / Fs #frq_1 = k/T # two sides frequency range frq_1 = k * Fs / n frq = frq_1[range(int(n / 2))] # one side frequency range Y_1 = dft.dft(y) # fft computing and normalization Y_1 = np.array(Y_1) Y = Y_1 fig, ax = plt.subplots(2, 1) ax[0].plot(t, y) ax[0].set_xlabel('Time') ax[0].set_ylabel('Amplitude') ax[1].plot(frq, abs(Y), 'r') # plotting the spectrum ax[1].set_xlabel('Freq (Hz)') ax[1].set_ylabel('|Y(freq)|')
def AC_TEST(): print('AC TEST:\n\n') #signal x x = [] #making signal a sine wave amount = 8 n = 0 inkrement = 2 * pi / amount i = 0 for i in range(amount): x.append(sin(n) * 5) n = n + inkrement N = len(x) #original signal print(f'signal: x = {x}\n\n') #if my ouput is the same it highly possible that is correct #try out yourself with the file ProofItWorks.m print('Octave(Matlab)-Output:') print( 'fft = 0.00000 + 0.00000i -0.00000 - 20.00000i 0.00000 - 0.00000i 0.00000 - 0.00000i 0.00000 + 0.00000i 0.00000 + 0.00000i 0.00000 + 0.00000i -0.00000 + 20.00000i\n' ) print( 'fft(Amplitude) = 1.6823e-16 2.0000e+01 1.4662e-15 1.7764e-15 1.0564e-15 1.7764e-15 1.4662e-15 2.0000e+01' ) print( 'fft(Phase) = 0.00000 -1.57080 -1.13998 -1.56195 0.00000 1.56195 1.13998 1.57080\nthe phase is actually false\n\n' ) #you can also try numpy fft.fft() NUMPYFFT = around(npfft.fft(x), decimals=6) print(f'NumpyFFT = {NUMPYFFT}\n') print(f'Amplitude = {around(abs(NUMPYFFT), decimals=6)}') print(f'Phase = {around(npangle(NUMPYFFT), decimals=6)}\n\n') #Diskrete-Fourier-Transformation X = around(dft(x), decimals=6) print('Diskrete-Fourier-Transformation:') print(f'X = {X}\n') #amplitude and phase A = [None] * N p = [None] * N i = 0 for i in range(len(X)): temp1 = abs(X[i]) A[i] = temp1 temp2 = angle(X[i]) p[i] = temp2 #print(p[i]) print(f'Amplitude: A = {A}') print(f'Phase: p = {p}\n\n') #Fast-Fourier-Transformation X2 = around(fft(x), decimals=6) print('Fast-Fourier-Transformation:') print(f'X2 = {X2}\n') #amplitude and phase A2 = [None] * N p2 = [None] * N i = 0 for i in range(len(X2)): temp1 = abs(X2[i]) A2[i] = temp1 temp2 = angle(X[i]) p2[i] = temp2 print(f'Amplitude: A2 = {A2}') print(f'Phase: p2 = {p2}\n\n\n') plt.plot(x, X, max(x))
import sys import numpy as np from matplotlib import pyplot as plt import dft N = 32 M = 32 X,Y = np.mgrid[-N/2:N/2+1,-M/2:M/2+1] V = np.cos(2*np.pi*X/N) + np.sin(2*np.pi*Y/M) Q1 = dft.dft(V) P1 = dft.idft(Q1) ax = plt.subplot(2, 2, 1) ax.imshow(V, interpolation='nearest') ax = plt.subplot(2, 2, 2) ax.imshow(np.real(P1), interpolation='nearest') ax = plt.subplot(2, 2, 3) ax.imshow(np.real(Q1), interpolation='nearest') ax = plt.subplot(2, 2, 4) ax.imshow(np.imag(Q1), interpolation='nearest') plt.show() Q2 = np.fft.fft(V) P2 = np.fft.ifft(Q2) plt.plot(X, V, '-b', X, np.real(Q2/np.sqrt(N)), '-g', X, np.real(P2), '-r')