def fft_unpack(org1, org2): o1, o2, a1, a2 = unpack(org1, org2) avg_len = (len(o1) + len(o2))/2.0 std_len = abs(len(o1) - avg_len) child_len = -1 while (child_len < 1): child_len = int(abs(gauss( avg_len, std_len ))) # Find the next power of 2 greater than the longest length if len(o1) > len(o2): pow = nextpow2(len(o1)) else: pow = nextpow2(len(o2)) # Deep copy tmp1 = [ele for ele in o1] tmp2 = [ele for ele in o2] # Zero-pad tmp1.extend([0 for i in range(pow - len(tmp1))]) tmp2.extend([0 for i in range(pow - len(tmp2))]) o1, o2 = tmp1, tmp2 o1 = fft(o1) o2 = fft(o2) return avg_len, std_len, child_len, pow, o1, o2, a1, a2
def align_symmetryEEE(V,symop,max_radwn= 10,verbose=0, cuda_dev=0): #if not cudaworker.cuda_init_done: import pycuda.gpuarray as gpuarray cudaworker.cuda_init(cuda_dev) N = V.shape[0] if max_radwn is None:max_radwn = N/2 - 1 premult3 = sigproc.generate_premultiplier(N, 3) print('length', len(premult3)) print(premult3.shape) fVnopre = fourier.fft(V).astype(n.complex64) fV = fourier.fft(V/premult3).astype(n.complex64) with cudaworker.GPUContext(): stream = cudaworker.cudrv.Stream() gfV = (gpuarray.to_gpu(n.copy(fV.real).astype(n.float32)), gpuarray.to_gpu(n.copy(fV.imag).astype(n.float32))) gfVnopre = (gpuarray.to_gpu(n.copy(fVnopre.real).astype(n.float32)), gpuarray.to_gpu(n.copy(fVnopre.imag).astype(n.float32))) delta_R_thresh = 5e-2*geometry.angle_at_radwn(max_radwn) r_factor = 1.0/8.0 init_r_grid = 32 radwn = 50 rs, dr = geometry.gen_rs(init_r_grid, symop) best_R = None import time tic = time.time() for it in range(5000): print('iter ...', it) radwn_ang = geometry.angle_at_radwn(radwn) if True: print 'Aligning at radwn = {0}, N_R = {1}'.format(radwn,rs.shape[0]) print ' dr = {0}'.format(dr), errs = compute_symmetry_errs(rs,symop,gfV,gfVnopre,radwn,stream=None) """ if dr>=0.13: errs_best = errs.min() errs_best_r = errs.argmin() prevbest_R = best_R best_R = geometry.expmap(rs[errs_best_r]) if prevbest_R is not None: delta_R = min([n.arccos(n.clip(0.5*(n.trace(prevbest_R.T.dot(symR.dot(best_R))) - 1),-1,1)) \ for symR in symop.get_rotations()]) else: delta_R = n.inf if verbose > 0: print ', delta_R = {0}'.format(delta_R) best_thresh = (2.25 - float(radwn)/max_radwn)*errs_best subd_R = (delta_R >= delta_R_thresh or dr >= radwn_ang) and dr > 0.25*radwn_ang if it<=3: if subd_R: r_thresh = min(n.percentile(errs, 100*r_factor),best_thresh) rs = rs[errs <= r_thresh] rs, dr = geometry.subdivde(rs, dr) gc.collect() if radwn == max_radwn and ((not subd_R) or \ (delta_R < delta_R_thresh)): break if dr < radwn_ang: radwn = n.minimum(radwn + 5, 10)#max_radwn) """ print(time.time()-tic)/5000. return best_R, n.zeros(3)
def __init__(self, samples, sample_rate=44100.0, c_size=1024): # NEW TEST VARIABLES input_chunk_size = c_size # Number of samples to take from "samples" per fft input_chunk_count = len(samples) // input_chunk_size input_padding = 8192 # Number of zeros to pad each chunk with (multiple of 2) padded_chunk_size = input_chunk_size + input_padding # Number of frequency bins in the fft output # Calculate the frequency information frequency_bins = int(5000*padded_chunk_size/sample_rate) # frequency_bins = padded_chunk_size // 2 # The number of frequency bins (trim off the top half) frequency_bin_size = sample_rate / padded_chunk_size # The difference in max and min Hz per frequency bin frequencies = fourier.freqs(padded_chunk_size, sample_rate)[:frequency_bins] # output matrix self.amplitudes = np.zeros((input_chunk_count, len(frequencies))) # 2D array containing amp in terms of frequency at a time window = np.hamming(input_chunk_size) with ProgressBar("Performing STFT") as bar: for i in range(0, input_chunk_count*input_chunk_size, input_chunk_size): amps = fourier.fft(np.pad(window*samples[i:i+input_chunk_size], (input_padding/2, input_padding/2), 'constant')) amps = (np.array(amps) / padded_chunk_size).tolist() amps = [abs(x.real) for x in amps] # use real part only amps = amps[:frequency_bins] self.amplitudes[i/input_chunk_size] = amps bar.set(i*1./(input_chunk_count*input_chunk_size)) # Set old variables self.chunk_size = input_chunk_size self.chunk_count = input_chunk_count self.frequency_precision = frequency_bin_size self.frequencies = frequencies self.frequency_cutoff_index = frequency_bins-1 self.frequency_cutoff = frequencies[frequency_bins-1]
def test4(): N = 1024 f = 510 signal = [math.sin(2*f*math.pi*x/N) for x in xrange(N)] cspect = fourier.fft(signal) magspect = [abs(comp) for comp in cspect] stemplot(magspect)
def kernel(F, G, t=None): assert len(F) == len(G), "Input arrays must have equal length" if len(t) == 0: t = np.arange(len(F)) # Calculate the fourier transforms of F and G FF, f = fft(F, t) FG, _ = fft(G, t) # Calculate the inverse fourier transform of the quotient k, tt = ifft(FG / FF, f) k = np.real(k) # Sort results by time value sort = np.argsort(tt) k = k[sort] tt = tt[sort] return k, tt
def calcTimeAndOutput(numSignalLengths, fourierAlgo): outputs, outputsTime = [], [] for i in range(numSignalLengths): time_start = time.time() if (fourierAlgo == 'FFT'): outputs.append(fourier.fft(inputs[i])) elif (fourierAlgo == 'FT'): outputs.append(fourier.ft(inputs[i])) time_end = time.time() outputsTime.append(time_end - time_start) return outputs, outputsTime
def signal_recomp(data): Va_modulo, Va_fase = fft(data['Va'], data['time'], 60, 128) Vb_modulo, Vb_fase = fft(data['Vb'], data['time'], 60, 128) Vc_modulo, Vc_fase = fft(data['Vc'], data['time'], 60, 128) Ia_modulo, Ia_fase = fft(data['Ia'], data['time'], 60, 128) Ib_modulo, Ib_fase = fft(data['Ib'], data['time'], 60, 128) Ic_modulo, Ic_fase = fft(data['Ic'], data['time'], 60, 128) Va1H = np.zeros((len(Ia_modulo), 1)) Vb1H = np.zeros((len(Ia_modulo), 1)) Vc1H = np.zeros((len(Ia_modulo), 1)) Ia1H = np.zeros((len(Ia_modulo), 1)) Ib1H = np.zeros((len(Ia_modulo), 1)) Ic1H = np.zeros((len(Ia_modulo), 1)) for i in range(0, len(Ia_modulo), 1): Va1H[i] = Va_modulo[i] * np.sin(2 * np.pi * 60 * data['time'][i] + Va_fase[i]*(np.pi/180)) Vb1H[i] = Vb_modulo[i] * np.sin(2 * np.pi * 60 * data['time'][i] + Vb_fase[i]*(np.pi/180)) Vc1H[i] = Vc_modulo[i] * np.sin(2 * np.pi * 60 * data['time'][i] + Vc_fase[i]*(np.pi/180)) Ia1H[i] = Ia_modulo[i] * np.sin(2 * np.pi * 60 * data['time'][i] + Ia_fase[i]*(np.pi/180)) Ib1H[i] = Ib_modulo[i] * np.sin(2 * np.pi * 60 * data['time'][i] + Ib_fase[i]*(np.pi/180)) Ic1H[i] = Ic_modulo[i] * np.sin(2 * np.pi * 60 * data['time'][i] + Ic_fase[i]*(np.pi/180)) data_1h = {'Va': Va1H, 'Vb': Vb1H, 'Vc': Vc1H, 'Ia': Ia1H, 'Ib': Ib1H, 'Ic': Ic1H, 'time': data['time'][128:, 0]} return data_1h
def test6(): N = 1024 f = 10 signal = [math.sin(2*f*math.pi*x/N) for x in xrange(N)] Fsignal = fourier.fft(signal) H = genfhilbert(N) HFsignal = [Fsignal[i]*H[i] for i in xrange(len(Fsignal))] hsignalc = fourier.ifft(HFsignal) hsignal = [samp.real for samp in hsignalc] mag = [math.sqrt(signal[x]*signal[x] + hsignal[x]*hsignal[x]) for x in xrange(len(hsignal))] fig, ax = pyplot.subplots(1) ax.plot(hsignal,'-r') ax.plot(signal,'-b') ax.plot(mag,'-k') pyplot.show()
def test10(): N = 1024 f = 25 dd = N/2 nn = N/10 signal = [math.exp(-((dd-x)/nn)**2/2)*math.sin(2*f*math.pi*x/N) for x in xrange(N)] ### Fsignal = fourier.fft(signal) H = genf2hilbert(N) HFsignal = [Fsignal[i]*H[i] for i in xrange(len(Fsignal))] hsignalc = fourier.ifft(HFsignal) hsignal = [samp.imag for samp in hsignalc] rsignal = [samp.real for samp in hsignalc] mag = [abs(hsignalc[x]) for x in xrange(len(hsignalc))] ### fig, ax = pyplot.subplots(1) ax.plot(signal,'-b') ax.plot(hsignal,'-r') ax.plot(mag,'-k') pyplot.show()
def decode_chord(samples): """Given a list of samples, interpret the samples as one chord and return a tuple (ctrl, bytes) where ctrl is the control note byte in the chord and bytes is a list of bytes of the remaining data notes. """ map = bands.get_frequency_map() spec = fourier.fft(samples) # Compute amplitudes for each sample in window. amps = [] for i in range(len(spec)): amps.append(sqrt(pow(spec[i].real, 2) + pow(spec[i].imag, 2))) # Determine whether the amplitudes indicate 0 or 1. j = 0 chord = [] inRange = False foundBit = False # For all indices under the Nyquist Limit. for i in range(len(amps) // 2): # While the frequency is within some range around # a frequency in the frequency map. while abs(map[j] - i * wavetools.SAMPLE_RATE / \ fourier.WINDOW_SIZE) <= FREQ_RANGE: inRange = True # If one of the amplitudes within this frequency range # is above a threshold, then the bit should be a 1. if amps[i] > AMP_THRESHOLD: foundBit = True break i += 1 if inRange: chord.append(1 if foundBit else 0) inRange = False foundBit = False j += 1 if j == len(map): break # From our list of bits in the chord, construct bytes by slicing the # bit list in byte-sized sublists and convert them to bytes. notes = [] for n in range(chords.CHORD_SIZE): note_start = (n * 8) note_end = note_start + 8 note_bits = chord[note_start:note_end] notes.append(bits.to_byte(note_bits)) # The first note is the control note, so we return it separately # from the other notes. return (notes[0], notes[1:])
""" Python implementation of Drawing With Fourier Epicycles, based on Coding Train Tutorial by Daniel Shiffman: https://thecodingtrain.com/CodingChallenges/130.3-fourier-transform-drawing.html Uses drawing coordinate extraction algorithm from Randy Olson: http://www.randalolson.com/2018/04/11/traveling-salesman-portrait-in-python/ MIT License """ import epicycles import fourier # This is just a simple box drawn in paint. You can adjust num_indicies and indices_step_size to trade speed for # accuracy. There is also a read_json_as_complex that will read in coordinates in JSON format directly. You can modify # Daniel's Coding Train JavaScript coordinates to be JSON and that will run well. z = epicycles.Epicycles.read_image_as_complex("box.png", num_indicies=1700, indices_step_size=5) fourier_data = fourier.fft(z) # Sort so that largest epicycles are at the center, and the smaller ones are at the location of the drawing points fourier_data.sort(key=lambda x: x.amplitude, reverse=True) epicycles = epicycles.Epicycles(fourier_data, plot_size=[1024, 1024]) epicycles.run()