def THDN(signal, sample_rate, filename): signal = signal - mean(signal) # this is so that the DC offset is not the peak in the case of PDM windowed = signal * blackmanharris(len(signal)) # Find the peak of the frequency spectrum (fundamental frequency), and filter # the signal by throwing away values between the nearest local minima f = rfft(windowed) #limit the bandwidth if len(f) > 24000: f[24000:len(f)] = 0 bandwidth_limited = irfft(f) total_rms = rms_flat(bandwidth_limited) #for i in range(6000): #print abs(f[i]) i = argmax(abs(f)) #This will be exact if the frequency under test falls into the middle of an fft bin print 'Frequency: %f Hz' % (sample_rate * (i / len(windowed))) lowermin, uppermin = find_range(abs(f), i) #notch out the signal f[lowermin: uppermin] = 0 noise = irfft(f) THDN = rms_flat(noise) / total_rms print "THD+N: %.12f%% or %.12f dB" % (THDN * 100, 20 * log10(THDN))
def FFT(self): for o in self.object_list: x_list = [] y_list = [] # print o.chaincode print "----" print o.object_name + "_1 " + str(o.point_list[0][0]) + " " + str(o.point_list[0][1]) + " 1 1" for d in o.chaincode: print d, print "-1" print "----" x = y = 0 for d in o.chaincode: x += DIRECTION_MATRIX[d][0] y -= DIRECTION_MATRIX[d][1] x_list.append(x) y_list.append(y) n_point = len(x_list) x_fft_result = fft.rfft(x_list) y_fft_result = fft.rfft(y_list) for i in range(20): x = x_fft_result[i] y = y_fft_result[i] print "%e %e %e %e" % ( x.real, x.imag, y.real, y.imag ) x_list_2 = fft.irfft(x_fft_result[0:10], n_point) y_list_2 = fft.irfft(y_fft_result[0:10], n_point) print "x" print x_list print x_list_2 print "y" print y_list print y_list_2
def filtered_cross_corr(signal1,signal2,bins,smoothing=10,timestep=1): """Get the cross-correlation between the signals, first filtering the fourier transforms (smoothed top-hat), chopping the fourier signals into "bins" bins""" signal1 -= signal1.mean() signal2 -= signal2.mean() x1 = rfft(signal1) x2 = rfft(signal2) assert len(x1)==len(x2) startfreq = arange(1,len(x1),len(x1)/(bins+1)) position = arange(len(x1)) freq = fftfreq(len(x1),timestep) freqout = zeros(bins)*1. out = zeros((bins,len(signal1)))*1.0 att = ones(len(x1))*1. for i in range(bins): att[:startfreq[i]] = 0 att[startfreq[i]:startfreq[i+1]] = 1 att[startfreq[i+1]:] = 0 freqout[i] = mean(freq*att[:len(freq)]) att = smooth(att,smoothing) att[0] = 0 x1dash = x1*att sig1dash = irfft(x1dash,len(signal1)) x2dash = x2*att sig2dash = irfft(x2dash,len(signal2)) out[i] = correlate(sig1dash,sig2dash,'same') lag = arange(-len(x2),len(x2),1.)*timestep return lag,freqout,out
def filter_xyz(data): xdata=[a[0] for a in data] ydata=[a[1] for a in data] zdata=[a[2] for a in data] samples=len(ydata) xdata=array(xdata) ydata=array(ydata) zdata=array(zdata) try: #---------------------------------- xfft=(fft.rfft(xdata)) yfft=(fft.rfft(ydata)) zfft=(fft.rfft(zdata)) #-------------filtering part -------------- cutoff=samples/3*2 xfft=ffilter(xfft,cutoff) yfft=ffilter(yfft,cutoff) zfft=ffilter(zfft,cutoff) nxdata=fft.irfft(xfft) nydata=fft.irfft(yfft) nzdata=fft.irfft(zfft) except: raise ValueError('null value') size=len(nxdata) data=[[nxdata[i],nydata[i],nzdata[i]] for i in range(size)] return data
def to_time(self, data_type): parity = self.pulses_length % 2 delta_t = 0.5 / ((self.pulses_length - parity) * self.delta_f) data1_time = irfft(self._data[self._data1]) data2_time = irfft(self._data[self._data2]) time_pulses_length = data1_time.shape[1] pulses_time = data_type(time_pulses_length, self.pulses_nb, delta_t) pulses_time._data['Valim'] = self.valim pulses_time._data[self._data1] = data1_time pulses_time._data[self._data2] = data2_time return pulses_time
def single_step_propagation(self): """ Perform single step propagation. The final Wigner functions are not normalized. """ ################ p x -> theta x ################ self.wigner_ge = fftpack.fft(self.wigner_ge, axis=0, overwrite_x=True) self.wigner_g = fftpack.fft(self.wigner_g, axis=0, overwrite_x=True) self.wigner_e = fftpack.fft(self.wigner_e, axis=0, overwrite_x=True) # Construct T matricies TgL, TgeL, TeL = self.get_T_left(self.t) TgR, TgeR, TeR = self.get_T_right(self.t) # Save previous version of the Wigner function Wg, Wge, We = self.wigner_g, self.wigner_ge, self.wigner_e # First update the complex valued off diagonal wigner function self.wigner_ge = (TgL*Wg + TgeL*Wge.conj())*TgeR + (TgL*Wge + TgeL*We)*TeR # Slice arrays to employ the symmetry (savings in speed) TgL, TgeL, TeL = self.theta_slice(TgL, TgeL, TeL) TgR, TgeR, TeR = self.theta_slice(TgR, TgeR, TeR) Wg, Wge, We = self.theta_slice(Wg, Wge, We) # Calculate the remaning real valued Wigner functions self.wigner_g = (TgL*Wg + TgeL*Wge.conj())*TgR + (TgL*Wge + TgeL*We)*TgeR self.wigner_e = (TgeL*Wg + TeL*Wge.conj())*TgeR + (TgeL*Wge + TeL*We)*TeR ################ Apply the phase factor ################ self.wigner_ge *= self.expV self.wigner_g *= self.expV[:(1 + self.P_gridDIM//2), :] self.wigner_e *= self.expV[:(1 + self.P_gridDIM//2), :] ################ theta x -> p x ################ self.wigner_ge = fftpack.ifft(self.wigner_ge, axis=0, overwrite_x=True) self.wigner_g = fft.irfft(self.wigner_g, axis=0) self.wigner_e = fft.irfft(self.wigner_e, axis=0) ################ p x -> p lambda ################ self.wigner_ge = fftpack.fft(self.wigner_ge, axis=1, overwrite_x=True) self.wigner_g = fft.rfft(self.wigner_g, axis=1) self.wigner_e = fft.rfft(self.wigner_e, axis=1) ################ Apply the phase factor ################ self.wigner_ge *= self.expK self.wigner_g *= self.expK[:, :(1 + self.X_gridDIM//2)] self.wigner_e *= self.expK[:, :(1 + self.X_gridDIM//2)] ################ p lambda -> p x ################ self.wigner_ge = fftpack.ifft(self.wigner_ge, axis=1, overwrite_x=True) self.wigner_g = fft.irfft(self.wigner_g, axis=1) self.wigner_e = fft.irfft(self.wigner_e, axis=1)
def output(self): """ """ # One dimension if len(self._source.shape) == 1: source = self._actual_source # Use FFT convolution if self._fft: if not self._toric: P = rfft(source,self._fft_shape[0])*self._fft_weights R = irfft(P, self._fft_shape[0]).real R = R[self._fft_indices] else: P = rfft(source)*self._fft_weights R = irfft(P,source.shape[0]).real # if self._toric: # R = ifft(fft(source)*self._fft_weights).real # else: # n = source.shape[0] # self._src_holder[n//2:n//2+n] = source # R = ifft(fft(self._src_holder)*self._fft_weights) # R = R.real[n//2:n//2+n] # Use regular convolution else: R = convolve1d(source, self._weights[::-1], self._toric) if self._src_rows is not None: R = R[self._src_rows] return R.reshape(self._target.shape) # Two dimensions else: source = self._actual_source # Use FFT convolution if self._fft: if not self._toric: P = rfft2(source,self._fft_shape)*self._fft_weights R = irfft2(P, self._fft_shape).real R = R[self._fft_indices] else: P = rfft2(source)*self._fft_weights R = irfft2(P,source.shape).real # Use SVD convolution else: R = convolve2d(source, self._weights, self._USV, self._toric) if self._src_rows is not None and self._src_cols is not None: R = R[self._src_rows, self._src_cols] return R.reshape(self._target.shape)
def autocorr(self, x): """ multi-dimensional autocorrelation with FFT """ X = rfft(x, n=(x.shape[1]*2-1), axis=1) xr = irfft(X * X.conjugate(), axis=1).real xr = fftshift(xr, axes=1) xr = xr.sum(axis=1) return xr
def record2vecs(File): # Read the rr data (Note that it is sampled irregularly and # consists of the r-times in centiseconds) and return a high # frequency spectrogram. import cinc2000 from numpy.fft import rfft, irfft data = [] for line in File: data.append(float(line)/100) File.close() # Now data[i] is an r-time in seconds. hrd = cinc2000.R_times2Dev(data) # hrd are heart rate deviations sampled at 2 Hz pad = np.zeros(((Glength+len(hrd)),),np.float64) pad[Gl_2:len(hrd)+Gl_2] = hrd # Now pad is hrd with Gl_2 zeros before and after N_out = len(hrd)//RDt result = np.zeros((N_out,Fw/2),np.float64) mags = [] for k in range(N_out): i = int(RDt*k) WD = Gw*pad[i:i+Glength] # Multiply data by window fuction FT = rfft(WD,n=Fw) SP = np.conjugate(FT)*FT # Periodogram temp = rfft(SP,n=Fw//2) SP = irfft(temp[0:int(0.1*Fw/2)],n=Fw/2) # Low pass filter in freq domain. Pass below 0.1 Nyquist temp = SP.real[:Fw/2] mag = math.sqrt(np.dot(temp,temp)) result[k,:] = temp/mag mags.append(math.log(mag)) # result[k,:] is a unit vector and a smoothed periodogram return [result,mags]
def deriv(var, periodic=False): """Take derivative of 1D array""" n = var.size if periodic: # Use FFTs to take derivatives f = rfft(var) f[0] = 0.0 # Zero constant term if n % 2 == 0: # Even n for i in arange(1,n/2): f[i] *= 2.0j * pi * float(i)/float(n) f[-1] = 0.0 # Nothing from Nyquist frequency else: # Odd n for i in arange(1,(n-1)/2 + 1): f[i] *= 2.0j * pi * float(i)/float(n) return irfft(f) else: # Non-periodic function result = zeros(n) # Create empty array if n > 2: for i in arange(1, n-1): # 2nd-order central difference in the middle of the domain result[i] = 0.5*(var[i+1] - var[i-1]) # Use left,right-biased stencils on edges (2nd order) result[0] = -1.5*var[0] + 2.*var[1] - 0.5*var[2] result[n-1] = 1.5*var[n-1] - 2.*var[n-2] + 0.5*var[n-3] elif n == 2: # Just 1st-order difference for both points result[0] = result[1] = var[1] - var[0] elif n == 1: result[0] = 0.0 return result
def shift(self,p=None,pdot=None,dm=None): if dm is None: dm = self.current_dm if p is None: p = self.current_p if pdot is None: pdot = self.current_pdot f = rfft(self.profs,axis=-1) # the sample at phase p is moved to phase p-dmdelays dmdelays = (psr_utils.delay_from_DM(dm,self.pfd.subfreqs) - psr_utils.delay_from_DM(self.current_dm,self.pfd.subfreqs))/self.original_fold_p start_times = self.pfd.start_secs pdelays = (start_times/self.original_fold_p) * (p-self.current_p)/self.original_fold_p pdotdelays = ((pdot-self.current_pdot)*start_times**2/2.)/self.original_fold_p f *= np.exp((2.j*np.pi)* dmdelays[np.newaxis,:,np.newaxis]* np.arange(f.shape[-1])[np.newaxis,np.newaxis,:]) f *= np.exp((2.j*np.pi)* (pdelays+pdotdelays)[:,np.newaxis,np.newaxis]* np.arange(f.shape[-1])[np.newaxis,np.newaxis,:]) self.profs = irfft(f) self.current_p = p self.current_dm = dm self.current_pdt = pdot
def bandpass_gaussian(data, dt, period, alpha): """ Bandpassing real data (in array *data*) with a Gaussian filter centered at *period* whose width is controlled by *alpha*: exp[-alpha * ((f-f0)/f0)**2], with f the frequency and f0 = 1 / *period*. *dt* is the sampling interval of the data. @type data: L{numpy.ndarray} @type dt: float @type period: float @type alpha: float @rtype: L{numpy.ndarray} """ # Fourier transform fft_data = rfft(data) # aray of frequencies freq = rfftfreq(len(data), d=dt) # bandpassing data f0 = 1.0 / period fft_data *= np.exp(-alpha * ((freq - f0) / f0) ** 2) # back to time domain return irfft(fft_data, n=len(data))
def lpc_python(x, order): def levinson(R, order): """ input: autocorrelation and order, output: LPC coefficients """ a = np.zeros(order + 2) a[0] = -1 k = np.zeros(order + 1) # step 1: initialize prediction error "e" to R[0] e = R[0] # step 2: iterate over [1:order] for i in range(1, order + 1): # step 2-1: calculate PARCOR coefficients k[i] = (R[i] - np.sum(a[1:i] * R[i - 1 : 0 : -1])) / e # step 2-2: update LPCs a[i] = np.copy(k[i]) a_old = np.copy(a) for j in range(1, i): a[j] -= k[i] * a_old[i - j] # step 2-3: update prediction error "e" e = e * (1.0 - k[i] ** 2) return -1 * a[0 : order + 1], e, -1 * k[1:] # N: compute next power of 2 n = x.shape[0] N = int(np.power(2, np.ceil(np.log2(2 * n - 1)))) # calculate autocorrelation using FFT X = rfft(x, N) r = irfft(abs(X) ** 2)[: order + 1] return levinson(r, order)
def fft_multiply_repeated(h_fft, x, n_fft, cuda_dict): """Do FFT multiplication by a filter function (possibly using CUDA). Parameters ---------- h_fft : 1-d array or gpuarray The filtering array to apply. x : 1-d array The array to filter. n_fft : int The number of points in the FFT. cuda_dict : dict Dictionary constructed using setup_cuda_multiply_repeated(). Returns ------- x : 1-d array Filtered version of x. """ if not cuda_dict['use_cuda']: # do the fourier-domain operations x = irfft(h_fft * rfft(x, n=n_fft), n_fft) else: cudafft = _get_cudafft() # do the fourier-domain operations, results in second param cuda_dict['x'].set(x.astype(np.float64)) cudafft.fft(cuda_dict['x'], cuda_dict['x_fft'], cuda_dict['fft_plan']) _multiply_inplace_c128(h_fft, cuda_dict['x_fft']) # If we wanted to do it locally instead of using our own kernel: # cuda_seg_fft.set(cuda_seg_fft.get() * h_fft) cudafft.ifft(cuda_dict['x_fft'], cuda_dict['x'], cuda_dict['ifft_plan'], False) x = np.array(cuda_dict['x'].get(), dtype=x.dtype, subok=True, copy=False) return x
def track_memory(self): ''' Calculates the induced voltage energy kick to particles taking into account multi-turn induced voltage plus inductive impedance contribution. ''' # Contribution from multi-turn induced voltage. self.array_memory *= np.exp(self.omegaj_array_memory * self.rev_time_array[self.counter_turn]) induced_voltage = irfft(self.array_memory + rfft(self.slices.n_macroparticles, self.n_points_fft) * self.sum_impedances_memory, self.n_points_fft) self.induced_voltage = self.coefficient * induced_voltage[:self.slices.n_slices] induced_voltage[self.len_array_memory:]=0 self.array_memory = rfft(induced_voltage, self.n_points_fft) # Contribution from inductive impedance if self.inductive_impedance_on: self.induced_voltage_list[self.index_inductive_impedance].induced_voltage_generation(self.beam, 'slice_frame') self.induced_voltage += self.induced_voltage_list[self.index_inductive_impedance].induced_voltage # Induced voltage energy kick to particles through linear interpolation libfib.linear_interp_kick(self.beam.dt.ctypes.data_as(ctypes.c_void_p), self.beam.dE.ctypes.data_as(ctypes.c_void_p), self.induced_voltage.ctypes.data_as(ctypes.c_void_p), self.slices.bin_centers.ctypes.data_as(ctypes.c_void_p), ctypes.c_uint(self.slices.n_slices), ctypes.c_uint(self.beam.n_macroparticles), ctypes.c_double(0.)) # Counter update self.counter_turn += 1
def fft_lowpass(nelevation, low_bound, high_bound): """ Performs a low pass filter on the nelevation series. low_bound and high_bound specifes the boundary of the filter. """ import numpy.fft as F if len(nelevation) % 2: result = F.rfft(nelevation, len(nelevation)) else: result = F.rfft(nelevation) freq = F.fftfreq(len(nelevation))[:len(nelevation)/2] factor = np.ones_like(result) factor[freq > low_bound] = 0.0 sl = np.logical_and(high_bound < freq, freq < low_bound) a = factor[sl] # Create float array of required length and reverse a = np.arange(len(a) + 2).astype(float)[::-1] # Ramp from 1 to 0 exclusive a = (a/a[0])[1:-1] # Insert ramp into factor factor[sl] = a print factor[sl] result = result * factor print result print 'resultnog=', len(result) relevation = F.irfft(result, len(nelevation)) print 'result=', len(relevation) return relevation
def STIFT(stft_windows, nfft, nskip): "Sum contributions from each window. No normalization." r = np.zeros(nskip * (len(stft_windows) - 1) + nfft) h = hamming(nfft) for w, w_0 in zip(stft_windows, xrange(0, r.size, nskip)): r[w_0 : w_0+nfft] += irfft(w, nfft) * h return r
def macro_mismatch(self,p1,p2): """ Performs double convolution with two different periods to calculate macroscopic average of a charge density along the z-axis. """ from numpy.fft import rfft,irfft # Convert periods to direct units, if given in cartesian if p1 > 1.0: p1 = p1/self.unitcell.cell_vec[2,2] if p2 > 1.0: p2 = p2/self.unitcell.cell_vec[2,2] # Create xy-plane averaged density micro_z = self.integrate_z_density() # Create convolutions z_pos = np.linspace(0,1,len(micro_z)) # Find index of lowest lower bound for p1 low = 1.-p1/2. i1 = len(z_pos)-1 while True: if z_pos[i1] <= low: i1 += 1 break i1 -= 1 #Find index of lowest upper bound for p1 high = p1/2. j1 = 0 while True: if z_pos[j1] >= high: j1 -= 1 break j1 += 1 # Find index of lowest lower bound for p2 low = 1.-p2/2. i2 = len(z_pos)-1 while True: if z_pos[i2] <= low: i2 += 1 break i2 -= 1 #Find index of lowest upper bound for p2 high = p2/2. j2 = 0 while True: if z_pos[j2] >= high: j2 -= 1 break j2 += 1 conv1 = np.zeros(len(micro_z)) conv1[0:j1+1] = np.ones(j1+1) conv1[i1:] = np.ones(len(conv1[i1:])) conv2 = np.zeros(len(micro_z)) conv2[0:j2+1] = np.ones(j2+1) conv2[i2:] = np.ones(len(conv2[i2:])) # Perform convolutions in Fourier Space f_micro_z = rfft(micro_z) f_conv1 = rfft(conv1) f_conv2 = rfft(conv2) f_macro = f_conv2*f_conv1*f_micro_z macro_z = irfft(f_macro)/float(np.sum(conv1))/float(np.sum(conv2)) return macro_z
def smear_profile(prof,fac): nb = len(prof) bmax = int(1.0/fac/2.0) if bmax>nb/2: bmax=nb/2 fprof = rfft(prof) fprof[bmax:] = 0.0 return irfft(fprof)
def find_fast_fft_sizes(max_size = 4192, array_size = 1024*1024): from numpy.fft import rfft, irfft from time import clock from numpy import ones, single a = ones((array_size,), single) tl = [] for s in range(2, max_size+1): n = array_size/s b = a[:s*n].reshape((n, s)) c0 = clock() f = rfft(b) g = irfft(f) c1 = clock() t = (c1-c0)/n # Average time for one fft if t < 0: # Python clock() wraps after 4295 seconds on 32-bit systems. Ugh. t += (256.0**4/1e6)/n tl.append((t,s)) print s, '%.4g' % (1e6*t) tl.reverse() tmin,s = tl[0] fs = [s] for t,s in tl: if t < tmin: fs.append(s) tmin = t fs.reverse() return fs
def filterFromXFer(ds, dpathXFer='/', newpath='/filter', nyquist=5000): d = ds.getSubData(dpathXFer) fs, start = d.fs(), d.start() gain = d.data[:,0] phase = d.data[:,1] if not nyquist: nyquist = start + gain.shape[0]/fs if start: npad = int(round(start*fs)) gain = concatenate([zeros(npad), gain]) phase = concatenate([zeros(npad), phase]) else: gain[0]=0 phase[0]=0 c = gain*exp(1j*phase) ts = irfft(c, nyquist*2) n = int(ts.shape[0]/2.0) ts = concatenate([ts[n:], ts[:n]]) #phase correction by one sample point here. Why is that? #it seems that irfft doesn't use an odd number of Fourier points, and so the center of the #spectrum gets shifted by one? Overtly specifying an odd number of transform points doesn't solve #the problem though. using nyquist*2+1 ts=ts[1:] head = {"SampleType":"timeseries", "SamplesPerSecond":nyquist*2} ds.createSubData(newpath, data=ts, head=head, delete=True) analyzeFilterWN(ds, dpathFilt=newpath, useWindowedFFT=True)
def gaussian_convolution(data, ijk_sdev, cyclic = False, cutoff = 5, task = None): from numpy import array, single as floatc, multiply, swapaxes c = array(data, floatc) from numpy.fft import rfft, irfft for axis in range(3): # Transform one axis at a time. size = c.shape[axis] sdev = ijk_sdev[2-axis] # Axes i,j,k are 2,1,0. hw = min(size/2, int(cutoff*sdev+1)) if cutoff else size/2 nzeros = 0 if cyclic else hw # Zero-fill for non-cyclic convolution. if nzeros > 0: # FFT performance is much better (up to 10x faster in numpy 1.2.1) # than other sizes. nzeros = efficient_fft_size(size + nzeros) - size g = gaussian(sdev, size + nzeros) g[hw:-hw] = 0 fg = rfft(g) # Fourier transform of 1-d gaussian. cs = swapaxes(c, axis, 2) # Make axis 2 the FT axis. s0 = cs.shape[0] for p in range(s0): # Transform one plane at a time. cp = cs[p,...] try: ft = rfft(cp, n=len(g)) # Complex128 result, size n/2+1 except ValueError, e: raise MemoryError, e # Array dimensions too large. multiply(ft, fg, ft) cp[:,:] = irfft(ft)[:,:size] # Float64 result if task: pct = 100.0 * (axis + float(p)/s0) / 3.0 task.updateStatus('%.0f%%' % pct)
def periodic_interp(self,data, zoomfact, window='hanning', alpha=6.0): """ Return a periodic, windowed, sinc-interpolation of the data which is oversampled by a factor of 'zoomfact'. """ zoomfact = int(zoomfact) if (zoomfact < 1): #print "zoomfact must be >= 1." return 0.0 elif zoomfact==1: return data newN = len(data)*zoomfact # Space out the data comb = Num.zeros((zoomfact, len(data)), dtype='d') comb[0] += data comb = Num.reshape(Num.transpose(comb), (newN,)) # Compute the offsets xs = Num.zeros(newN, dtype='d') xs[:newN/2+1] = Num.arange(newN/2+1, dtype='d')/zoomfact xs[-newN/2:] = xs[::-1][newN/2-1:-1] # Calculate the sinc times window for the kernel if window.lower()=="kaiser": win = _window_function[window](xs, len(data)/2, alpha) else: win = _window_function[window](xs, len(data)/2) kernel = win * self.sinc(xs) if (0): print "would have plotted." return FFT.irfft(FFT.rfft(kernel) * FFT.rfft(comb))
def generalized_cross_correlation(d0, d1): # substract the means # (in order to get a normalized cross-correlation at the end) d0 -= d0.mean() d1 -= d1.mean() # Hann window to mitigate non-periodicity effects window = numpy.hanning(len(d0)) # compute the cross-correlation D0 = rfft(d0 * window) D1 = rfft(d1 * window) D0r = D0.conjugate() G = D0r * D1 # G = (G==0.)*1e-30 + (G<>0.)*G # W = 1. # frequency unweighted # W = 1./numpy.abs(G) # "PHAT" absG = numpy.abs(G) m = max(absG) W = 1. / (1e-10 * m + absG) # D1r = D1.conjugate(); G0 = D0r*D0; G1 = D1r*D1; W = numpy.abs(G)/(G0*G1) # HB weighted Xcorr = irfft(W * G) # Xcorr_unweighted = irfft(G) # numpy.save("d0.npy", d0) # numpy.save("d1.npy", d1) # numpy.save("Xcorr.npy", Xcorr) return Xcorr
def getview (self, view, pbar): # {{{ import numpy saxis = self.saxis # Get bounds of slice on smoothing axis ind = view.integer_indices[saxis] st, sp = numpy.min(ind), numpy.max(ind) # input is the whole range insl = slice(0, self.shape[saxis],1) # output is the required slice outsl = [ ind if i == saxis else slice(None) for i in range(self.naxes)] # Get source data aview = view.modify_slice(saxis, insl) src = aview.get(self.var, pbar=pbar) maxharm= self.maxharm smsl = [ slice(maxharm,None) if i == saxis else slice(None) for i in range(self.naxes)] # calculate harmonics and output required data from numpy import fft if 'complex' in self.dtype.name: ct=fft.fft(src,self.shape[saxis],saxis) smsl=[ slice(maxharm,-maxharm+1) if i == saxis else slice(None) for i in range(self.naxes)] ct[smsl]=0 st = fft.ifft(ct, self.shape[saxis], saxis) else: ct=fft.rfft(src,self.shape[saxis],saxis) ct[smsl]=0 st = fft.irfft(ct, self.shape[saxis], saxis) return st[outsl].astype(self.dtype)
def induced_voltage_generation(self, Beam, length = 'slice_frame'): ''' *Method to calculate the induced voltage from the inverse FFT of the impedance times the spectrum (fourier convolution).* ''' if self.recalculation_impedance: self.sum_impedances(self.frequency_array) self.slices.beam_spectrum_generation(self.n_fft_sampling) if self.save_individual_voltages: for i in range(self.len_impedance_source_list): self.matrix_save_individual_voltages[:,i] = - Beam.charge * e * Beam.ratio * irfft(self.matrix_save_individual_impedances[:,i] * self.slices.beam_spectrum)[0:self.slices.n_slices] * self.slices.beam_spectrum_freq[1] * 2*(len(self.slices.beam_spectrum)-1) self.induced_voltage = np.sum(self.matrix_save_individual_voltages,axis=0) else: induced_voltage = - Beam.charge * e * Beam.ratio * irfft(self.total_impedance * self.slices.beam_spectrum) * self.slices.beam_spectrum_freq[1] * 2*(len(self.slices.beam_spectrum)-1) self.induced_voltage = induced_voltage[0:self.slices.n_slices] if isinstance(length, int): max_length = len(induced_voltage) if length > max_length: induced_voltage = np.lib.pad(induced_voltage, (0, length-max_length), 'constant', constant_values=(0,0)) return induced_voltage[0:length]
def phaseshuffle(input_signal): """phaseshuffle(input_signal) phaseshuffle shuffles the phases of the component frequencies of a real signal among each other, but preserving the phase of the DC component and any Nyquist element. Input is a matrix of channels x timesteps.""" ## Fourier Transform to Get Component Frequencies' Phases and Magnitudes length_of_signal = input_signal.shape[1] from numpy.fft import rfft, irfft from numpy import angle, zeros, concatenate, exp from numpy.random import permutation print("Calculating component frequencies and their phases") y = rfft(input_signal, axis=1) magnitudes = abs(y) phases = angle(y) ## Shuffle Phases, Preserving DC component and Nyquist element (if present) number_of_channels, N = y.shape randomized_phases = zeros(y.shape) print("Randomizing") for j in range(number_of_channels): if N & 1: #If there are an odd number of elements #Retain the DC component and shuffle the remaining components. order = concatenate(([0], permutation(N-1)+1), axis=1) else: #Retain the DC and Nyquist element component and shuffle the remaining components. This makes the new signal real, instead of complex. order = concatenate(([0], permutation(N-2)+1, [-1]), axis=1) randomized_phases[j] = phases[j, order] ## Construct New Signal print("Constructing new signal") y1 = magnitudes*exp(1j*randomized_phases) output_signal = irfft(y1,n=length_of_signal, axis=1) #While the above code will produce a real signal when given a real signal, numerical issues sometimes make the output from ifft "complex", with a +/- 0i component. Since the imaginary component is accidental and meaningless, we remove it. return output_signal
def ifft(self): """Compute the one-dimensional discrete inverse Fourier transform of this `FrequencySeries`. Returns ------- out : :class:`~gwpy.timeseries.TimeSeries` the normalised, real-valued `TimeSeries`. See Also -------- :mod:`scipy.fftpack` for the definition of the DFT and conventions used. Notes ----- This method applies the necessary normalisation such that the condition holds: >>> timeseries = TimeSeries([1.0, 0.0, -1.0, 0.0], sample_rate=1.0) >>> timeseries.fft().ifft() == timeseries """ from ..timeseries import TimeSeries nout = (self.size - 1) * 2 # Undo normalization from TimeSeries.fft # The DC component does not have the factor of two applied # so we account for it here dift = npfft.irfft(self.value * nout) / 2 new = TimeSeries(dift, epoch=self.epoch, channel=self.channel, unit=self.unit, dx=1/self.dx/nout) return new
def cross_correlate(histogram, template, n_harmonics=None, upsample=16): """Find the shift required to align histogram with template """ n = max(len(histogram),len(template)) h_ft = rfft(histogram) t_ft = rfft(template) if len(h_ft)<len(t_ft): h_ft = concatenate((h_ft,zeros(len(t_ft)-len(h_ft)))) elif len(t_ft)<len(h_ft): t_ft = concatenate((t_ft,zeros(len(h_ft)-len(t_ft)))) if n_harmonics is not None: h_ft[n_harmonics+1:]*=0. t_ft[n_harmonics+1:]*=0. h_ft[0] = 0 t_ft[0] = 0 cross_correlations = irfft(conjugate(h_ft)*t_ft,n*upsample) shift = argmax(cross_correlations)/float(len(cross_correlations)) assert 0<=shift<1 #FIXME: warn if double-peaked return shift
def _genNoise(delta, npts, NM, velocity): """ Helper function for calculating random noise from noise model NM. """ delta = float(delta) Fnyq = 0.5/delta f = interp1d(NM['T'], NM['dB'], kind='linear', bounds_error=False, fill_value=-200) NPTS = 2**np.ceil(np.ceil(np.log2(npts)+1)) # make it longer than necessary so we can cut out middle bit freqs = np.linspace(1./NPTS/delta,Fnyq,NPTS-1) Pxx = f(1/freqs) spectrum = np.zeros(NPTS) spectrum[1:NPTS] = np.sqrt(10**(Pxx/10) * NPTS / delta * 2) # phase is randomly generated phase = (rand(NPTS) - 0.5) * np.pi * 2 NewX = spectrum * (np.cos(phase) + 1j * np.sin(phase)) acceleration = irfft(NewX) start = int((NPTS-npts)/2) end = start + npts if velocity: velocity = cumtrapz(acceleration, dx=delta) velocity = velocity[start:end] velocity = velocity - np.mean(velocity) return velocity else: acceleration = acceleration[start:end] acceleration = acceleration - np.mean(acceleration) return acceleration
def bp_chunk(ts, new_srate, f_low, f_high): srate=int(ts.sample_rate.value) bp=sig.firwin(4*srate,[f_low, f_high],nyq=srate/2.,window='hann',pass_zero=False) bp.resize(len(ts)) tmp=(2.*new_srate/float(srate))*abs(rfft(bp))*rfft(ts) padidx=4*int(new_srate) # Sample rate after irfft is twice desired return TimeSeries(irfft(tmp[:1+int(ts.duration.value*new_srate)])[padidx:-padidx:2], sample_rate=new_srate,epoch=ts.epoch.gps+2)
def convert_template(template, nbins): """Convert template to match prof (in length) Either down- or up-sample template so that it is the same length as prof. Use the Fourier domain; either drop or pad with zero the extra Fourier coefficients. """ return irfft(rfft(template),nbins)*(float(nbins)/len(template))
def test_front_back_4(self): s = np.random.randn(100) try: res = bm.irfft(bm.rfft(s, n=150), n=200) except AttributeError as e: self.skipTest('Not compiled with FFTW') np.testing.assert_almost_equal( res, fft.irfft(fft.rfft(s, n=150), n=200), 8)
def multS(s, v, L, TP=False): N = s.shape[0] vp = prepare_v(v, N, L, TP=TP) p = irfft(rfft(vp) * rfft(s)) if not TP: return p[:L] return p[L - 1:]
def idct(a): N = len(a) c = empty(N + 1, complex) phi = exp(1j * pi * arange(N) / (2 * N)) c[:N] = phi * a c[N] = 0.0 return irfft(c)[:N]
def idst(a): n = len(a) c = np.empty(n + 1, complex) c[0] = c[n] = 0.0 c[1:n] = -1j * a[1:] y = irfft(c)[:n] y[0] = 0.0 return y
def __generateSequence(self,T,seed=[]): # Set noise reproducibility seed if not isempty(seed): random.seed(seed); # Initialize sizes and data storage n = len(self._pd[:,0]); N = int(T/self._dt+1); wout = zeros((n,N)); minsamps = int(1e6); # Generate random sequences (with white frequency) if self._d == 1: w = random.normal(0,1,n*max([N,minsamps])); elif self._d == 2: w = random.uniform(-0.5,0.5,n*max([N,minsamps])); w = reshape(w,(n,max([N,minsamps]))); # Include frequency characcteristics into sequences for i in range(0,n): if self._f == 1: # ... with 1 frequency wout[i,:] = w[i,0:N]; # sequence is already correct; elif self._f >= 2 and self._f <= 6: t_temp = linspace(0,max([N,minsamps])*self._dt, max([N,minsamps])); f = fft.rfftfreq(t_temp.shape[-1],self._dt)*2; A = fft.rfft(w[i,:]); for j in range(0,len(f)): if f[j] != 0: A[j] = A[j]*(f[j]**(self._pf/20)); w[i,:] = fft.irfft(A); # f,A = self.__myFFT(w[i,:],t_temp,1); # w[i,:] = fft.irfft(A); # Shorten sequence wout[i,:] = w[i,0:N]; # Include auto-correlation characteristics into sequences if self._a == 1: # No autocorrellation pass; elif self._a == 2: # Causal integration for i in range(1,N): wout[:,i] = wout[:,i-1] + self._dt*wout[:,i] elif self._a == 3: # Gaussian auto-correlation wout = self.__correlateGaussian(wout); elif self._a == 4: # block auto-correlation wout = self.__correlateBlock(wout); # Rescale for i in range(0,n): wout[i,:] = wout[i,:]-mean(wout[i,:]); if self._d == 1: wout[i,:] = wout[i,:]/std(wout[i,:]); elif self._d == 2: wout[i,:] = wout[i,:]/(max(wout[i,:])-min(wout[i,:])); wout[i,:] = self._pd[i,1]*wout[i,:] + self._pd[i,0]; self._w = wout; return 0;
def interpolatePeriodicData(f,factor): nlat = len(f)*factor nk = nlat//2 + 1 fk = rfft(f) nkPad = nk - len(fk) fk = np.concatenate( [fk,np.zeros(nkPad)] ) fRefined = irfft(fk) # Add normalization in here return fRefined
def violet(N, power): orig_N = N # Because doing rfft->ifft produces different length outputs depending if its odd or even length inputs N+=1 x = np.random.randn(N).astype(np.float32) X = rfft(x) / N S = np.arange(X.size) # Filter y = irfft(X*S).real[0:orig_N] return normalise(y, power)
def test_irfft_10(self): s = np.random.randn(100) o = fft.rfft(s) try: res = bm.irfft(o, n=101) except AttributeError as e: self.skipTest('Not compiled with FFTW') np.testing.assert_almost_equal(res, fft.irfft(o, n=101), 8)
def pink(N, power): orig_N = N # Because doing rfft->ifft produces different length outputs depending if its odd or even length inputs N+=1 x = np.random.randn(N).astype(np.float32) X = rfft(x) / N S = np.sqrt(np.arange(X.size)+1.) # +1 to avoid divide by zero y = irfft(X/S).real[:orig_N] return normalise(y, power)
def idst(a): # Type-I inverse DST of a N = len(a) c = zeros(N+1,dtype=complex_) c[0] = c[N] = 0.0 c[1:N] = -1j*a[1:] y = irfft(c)[:N] y[0] = 0.0 return y
def idst(a): N = len(a) c = np.empty(N+1) c[0] = c[N] = 0.0 c[1:N] = -1j*a[1:] y = irfft(c)[:N] y[0] = 0.0 return y
def GConvolveFFT(Decay, Time, Center, FWHM): length = len(Decay) from scipy.stats import norm Width = FWHM / 2.0 * (2.0 * log(2.0))**0.5 CenteredIRF = norm.pdf(r_[Time, Time + Time[-1]], Center + Time[-1], Width) CenteredIRF = CenteredIRF / sum(CenteredIRF) # from matplotlib.pylab import plot # plot(CenteredIRF) return irfft(rfft(CenteredIRF) * rfft(r_[zeros(length), Decay]))[:length]
def update_nmda_sum(): for i in range(2): fft_s_NMDA = rfft(excit_pop[i * N_excitatory:(i + 1) * N_excitatory].s_NMDA) fft_s_NMDA_total = np.multiply(fft_presyn_weight_kernel, fft_s_NMDA) s_NMDA_tot = irfft(fft_s_NMDA_total) excit_pop[i * N_excitatory:(i + 1) * N_excitatory].s_NMDA_total_ = s_NMDA_tot
def ConvolveFFT(IRF, Decay): length = len(Decay) CenteredIRF = r_[zeros(length), IRF] # print argmax(CenteredIRF) # print CenteredIRF CenteredIRF = roll(CenteredIRF, length - argmax(CenteredIRF)) # from matplotlib.pylab import plot # plot(CenteredIRF) return irfft(rfft(CenteredIRF) * rfft(r_[zeros(length), Decay]))[:length]
def pink(N, data, state=None): state = np.random.RandomState() if state is None else state uneven = N%2 X = state.randn(N//2+1+uneven) + 1j * state.randn(N//2+1+uneven) S = np.sqrt(np.arange(len(X))+1.) # +1 to avoid divide by zero y = (irfft(X/S)).real if uneven: y = y[:-1] return normalize(y, data)
def falpha(length=8192, alpha=1.0, fl=None, fu=None, mean=0.0, var=1.0): """Generate (1/f)^alpha noise by inverting the power spectrum. Generates (1/f)^alpha noise by inverting the power spectrum. Follows the algorithm described by Voss (1988) to generate fractional Brownian motion. Parameters ---------- length : int, optional (default = 8192) Length of the time series to be generated. alpha : float, optional (default = 1.0) Exponent in (1/f)^alpha. Pink noise will be generated by default. fl : float, optional (default = None) Lower cutoff frequency. fu : float, optional (default = None) Upper cutoff frequency. mean : float, optional (default = 0.0) Mean of the generated noise. var : float, optional (default = 1.0) Variance of the generated noise. Returns ------- x : array Array containing the time series. Notes ----- As discrete Fourier transforms assume that the input data is periodic, the resultant series x_{i} (= x_{i + N}) is also periodic. To avoid this periodicity, it is recommended to always generate a longer series (two or three times longer) and trim it to the desired length. """ freqs = fft.rfftfreq(length) power = freqs[1:] ** -alpha power = np.insert(power, 0, 0) # P(0) = 0 if fl: power[freqs < fl] = 0 if fu: power[freqs > fu] = 0 # Randomize complex phases. phase = 2 * np.pi * np.random.random(len(freqs)) y = np.sqrt(power) * np.exp(1j * phase) # The last component (corresponding to the Nyquist frequency) of an # RFFT with even number of points is always real. (We don't have to # make the mean real as P(0) = 0.) if length % 2 == 0: y[-1] = np.abs(y[-1] * np.sqrt(2)) x = fft.irfft(y, n=length) # Rescale to proper variance and mean. x = np.sqrt(var) * x / np.std(x) return mean + x - np.mean(x)
def test_fourier_uniform_real01(self, shape, dtype, dec): a = numpy.zeros(shape, dtype) a[0, 0] = 1.0 a = fft.rfft(a, shape[0], 0) a = fft.fft(a, shape[1], 1) a = ndimage.fourier_uniform(a, [5.0, 2.5], shape[0], 0) a = fft.ifft(a, shape[1], 1) a = fft.irfft(a, shape[0], 0) assert_almost_equal(ndimage.sum(a), 1.0, decimal=dec)
def idst(a): N = len(a) c = empty(N + 1, complex) c[0] = c[N] = 0.0 c[1:N] = -1j * a[1:] y = irfft(c)[:N] y[0] = 0.0 return y
def transfer(self, signal, verbose=False): from numpy.fft import irfft if not self.gotBode: from scipy.interpolate import interp1d fmax = self._fMax if self._stepSize == 4e6: step = 10 if self._stepSize == 2e6: step = 20 else: step = 10 tmlBode = np.power(10,self._attenuation/20.)[::step] phase = self.dataDict['Phase'][::step] #tmlBode = tmlBode[:tmlBode.shape[0]/4:2] oldx = np.linspace(0,tmlBode.shape[0], num = tmlBode.shape[0], endpoint=True) fbode = interp1d(oldx, tmlBode, kind='cubic') fphase = interp1d(oldx, phase, kind='slinear') if signal.spectrum['Frequency'][len(signal.spectrum['Frequency'])-1] < fmax: sp = signal.spectrum['Frequency'] else: sp = signal.spectrum['Frequency'][0:len(np.where(signal.spectrum['Frequency']<fmax)[0])] newx = np.linspace(0,tmlBode.shape[0], num = len(sp), endpoint = True) interpBode = fbode(newx) interpPhase = fphase(newx) #import matplotlib.pyplot as plt #plt.plot(oldx, phase) #plt.plot(newx, interpPhase) #plt.show() self._bode = interpBode#/interpBode[0] self.gotBode = True else: interpBode = self._bode wf = {} complexBode = 1j*np.sin(2*np.pi*interpPhase)+np.cos(2*np.pi*interpPhase) complexBode *= interpBode for cnt in range(len(signal.waveform)-1): if verbose: printProgress(cnt, len(signal.waveform)-1, prefix = 'Transmitting wavefrom:', suffix = 'Complete', decimals=3, barLength = 50) wf['Sample %s'%cnt] = {} if 'Single' in signal.waveform['Sample %s'%cnt].keys(): fftwf = signal.spectrum['Data'][cnt] wf['Sample %s'%cnt]['Single'] = irfft(fftwf*np.append(complexBode,np.array([0.]*(fftwf.shape[0]-interpBode.shape[0]))), norm=None) wf['Sample %s'%cnt]['Single'] *= np.sqrt(2*len(fftwf)) if signal._window == 'Hamming': wf['Sample %s'%cnt]['Single'] /= signal._hamm elif signal._window == 'Tukey': wf['Sample %s'%cnt]['Single'] /= signal._tuk wf['Time'] = signal.waveform['Time'] return wf
def _calcTimeSeries(self, ): """ Compute the u,v,w, timeseries based on the spectral, coherence and Reynold's stress models. This method performs the work of taking a specified spectrum and coherence function and transforming it into a spatial timeseries. It performs the steps outlined in Veers84's [1]_ equations 7 and 8. Returns ------- turb : the turbulent velocity timeseries array (3 x nz x ny x nt) for this PyTurbSim run. Notes ----- 1) Veers84's equation 7 [1]_ is actually a 'Cholesky Factorization'. Therefore, rather than writing this functionality explicitly we call 'cholesky' routines to do this work. 2) This function uses one of two methods for computing the Cholesky factorization. If the Fortran library tslib is available it is used (it is much more efficient), otherwise the numpy implementation of Cholesky is used. .. [1] Veers, Paul (1984) 'Modeling Stochastic Wind Loads on Vertical Axis Wind Turbines', Sandia Report 1909, 17 pages. """ grid = self.grid tmp = np.zeros((grid.n_comp, grid.n_z, grid.n_y, grid.n_f + 1), dtype=ts_complex) if dbg: self.timer.start() # First calculate the 'base' set of random phases: phases = self.phase(self) # Now correlate the phases at each point to set the Reynold's stress: phases = self.stress.calc_phases(phases) # Now correlate the phases between points to set the spatial coherence: phases = self.cohere.calc_phases(phases) # Now multiply the phases by the spectrum... tmp[..., 1:] = np.sqrt(self.spec.array) * grid.reshape(phases) # and compute the inverse fft to produce the timeseries: ts = irfft(tmp) if dbg: self.timer.stop() # Select only the time period requested: # Grab a random number of where to cut the timeseries. i0_out = self.randgen.randint(grid.n_t - grid.n_t_out + 1) ts = ts[..., i0_out:i0_out + grid.n_t_out] / (grid.dt / grid.n_f)**0.5 ts -= ts.mean(-1)[..., None] # Make sure the turbulence has zero mean. return ts
def uv2image(self, uv): ''' Convert from uv space to pixel space by inverse FFT. ''' assert (len(uv) == self.Nfft // 2 + 1) bigimage = irfft(uv) # Concatenate the last chunk of bigimage to first chunk of bigimage image = np.hstack((bigimage[-self.Npix_fft // 2:], bigimage[:self.Npix_fft // 2 + 1])) return image
def irfft_adjusted_lower_limit(x, low_lim, indices): """ Compute the ifft of real matrix x with adjusted summation limits: y(j) = sum[k=-n-2, ... , -low_lim-1, low_lim, low_lim+1, ... n-2, n-1] x[k] * exp(sqrt(-1)*j*k* 2*pi/n), j =-n-2, ..., -low_limit-1, low_limit, low_limit+1, ... n-2, n-1 :param x: Single-sided real array to Fourier transform. :param low_lim: lower limit index of the array x. :param indices: list of indices of interest :return: Fourier transformed two-sided array x with adjusted lower limit. Retruns values. """ nf = 2 * (x.shape[1] - 1) a = (irfft(x, n=nf)[:, indices]) * nf b = (irfft(x[:, :low_lim], n=nf)[:, indices]) * nf return a - b
def idct(a): """ Inverse Direct Cosine Transform of 1D array. """ N = len(a) c = np.empty(N + 1, complex) phi = np.exp(1j * np.pi * np.arange(N) / (2 * N)) c[:N] = phi * a c[N] = 0.0 return irfft(c)[:N]
def generatePinkNoise(t, fs): N = int(t * fs) state_pink = np.random.RandomState() uneven = N % 2 X = state_pink.randn(N // 2 + 1 + uneven) + 1j * state_pink.randn(N // 2 + 1 + uneven) S = np.sqrt(np.arange(len(X)) + 1.) # +1 to avoid divide by zero y_pink = (irfft(X / S)).real y_pink_norm = normalize(y_pink) return y_pink_norm
def test_fourier_shift_real01(self, shape, dtype, dec): expected = numpy.arange(shape[0] * shape[1], dtype=dtype) expected.shape = shape a = fft.rfft(expected, shape[0], 0) a = fft.fft(a, shape[1], 1) a = ndimage.fourier_shift(a, [1, 1], shape[0], 0) a = fft.ifft(a, shape[1], 1) a = fft.irfft(a, shape[0], 0) assert_array_almost_equal(a[1:, 1:], expected[:-1, :-1], decimal=dec) assert_array_almost_equal(a.imag, numpy.zeros(shape), decimal=dec)
def compute_corr(f, g, conj=True): f_star = rfft(f) g_star = rfft(g) if conj: g_star_conj = np.conj(g_star) else: g_star_conj = g_star corr_star = f_star * g_star_conj corr = irfft(corr_star) return np.real(corr)
def sinc_lowpass(s, fs, cutoff): n = len(s) if n % 2 == 1: n = n - 1 f = rfft(s, n) # f size: (n/2)+1 nc = int((cutoff / fs) * n) if nc >= (n // 2) + 1: raise ValueError("Cutoff frequency is too high.") f[nc:] = 0.0 return irfft(f)
def istft_single_channel(stft_signal, size=1024, shift=256, window=signal.blackman, fading=True, window_length=None, use_amplitude_for_biorthogonal_window=False, disable_sythesis_window=False): """ Calculated the inverse short time Fourier transform to exactly reconstruct the time signal. Notes: Be careful if you make modifications in the frequency domain (e.g. beamforming) because the synthesis window is calculated according to the unmodified! analysis window. Args: stft_signal: Single channel complex STFT signal with dimensions frames times size/2+1. size: Scalar FFT-size. shift: Scalar FFT-shift. Typically shift is a fraction of size. window: Window function handle. fading: Removes the additional padding, if done during STFT. window_length: Sometimes one desires to use a shorter window than the fft size. In that case, the window is padded with zeros. The default is to use the fft-size as a window size. Returns: Single channel complex STFT signal Single channel time signal. """ assert stft_signal.shape[1] == size // 2 + 1, str(stft_signal.shape) if window_length is None: window = window(size) else: window = window(window_length) window = np.pad(window, (0, size - window_length), mode='constant') window = _biorthogonal_window_fastest( window, shift, use_amplitude_for_biorthogonal_window) if disable_sythesis_window: window = np.ones_like(window) time_signal = scipy.zeros(stft_signal.shape[0] * shift + size - shift) for j, i in enumerate(range(0, len(time_signal) - size + shift, shift)): time_signal[i:i + size] += window * np.real(irfft(stft_signal[j])) # Compensate fade-in and fade-out if fading: time_signal = time_signal[size - shift:len(time_signal) - (size - shift)] return time_signal