예제 #1
0
파일: timecrystal.py 프로젝트: natl/bg
 def step4(self):
   '''
   Perform a 4th order timestep
   '''
   
   def order2(c):
     Vc = np.exp( -1j * c * self.dt / 2. * 
                   ( self.V - self.gravity() + 
                     self.g * abs( self.psi ) ** 2
                   )
                 )
     Tc = self.expksquare ** c
     return Vc, Tc
   
   p = 1/(4.-4.**(1/3.))
   q = 1 - 4 * p
   
   Vp,Tp = order2( p )
   Vq,Tq = order2( q )
   
   return Vp * ff.fftshift( ff.ifft2( Tp * ff.fft2( ff.fftshift( Vp ** 2 * 
               ff.fftshift( ff.ifft2( Tp * ff.fft2( ff.fftshift( Vp * Vq *
               ff.fftshift( ff.ifft2( Tq * ff.fft2( ff.fftshift( Vq * Vp * 
               ff.fftshift( ff.ifft2( Tp * ff.fft2( ff.fftshift( Vp ** 2 *  
               ff.fftshift( ff.ifft2( Tp * ff.fft2( ff.fftshift( Vp * self.psi 
               ) ) ) )
               ) ) ) )
               ) ) ) )
               ) ) ) )
               ) ) ) )
예제 #2
0
def fftPropagate(field, grid, propDistance):
    '''Propagates a sampled 1D field along the optical axis.
    
    fftPropagate propagates a sampled 1D field a distance L by computing the
    field's angular spectrum, multiplying each spectral component by the
    propagation kernel exp(j * 2 * pi * fx * L / wavelength), and then
    recomibining the propagated spectral components. The angular spectrum is
    computed using a FFT.
    
    Parameters
    ----------
    field        : 1D array of complex
        The sampled field to propagate.
    grid         : Grid
        The grid on which the sampled field lies.
    propDistance : float
        The distance to propagate the field in the same physical units as the
        grid.
    
    '''
    scalingFactor = (grid.physicalSize / (grid.gridSize - 1))
    F             = scalingFactor * fftshift(fft(ifftshift(field)))
    
    # Compute the z-component of the wavevector
    # Adding 0j ensures that numpy.sqrt returns complex numbers
    kz = 2 * np.pi * np.sqrt(1 - (grid.pfX * grid.wavelength)**2 + 0j) / grid.wavelength
    
    # Propagate the field's spectral components
    Fprop = F * np.exp(1j * kz * propDistance)
    
    # Recombine the spectral components
    fieldProp = fftshift(ifft(ifftshift(Fprop))) / scalingFactor
    
    return fieldProp
예제 #3
0
    def test_depth_kwarg(self):
        nz = 100
        zN2 = 0.5*nz**-1 + np.arange(nz, dtype=np.float64)/nz
        zU = 0.5*nz**-1 + np.arange(nz+1, dtype=np.float64)/nz
        N2 = np.full(nz, 1.)
        f0 = 1.
        #beta = 1e-6
        beta = 0.
        Nx = 1
        Ny = 1
        dx = .1
        dy = .1
        k = fft.fftshift( fft.fftfreq(Nx, dx) )
        l = fft.fftshift( fft.fftfreq(Ny, dy) )
        ubar = np.zeros(nz+1)
        vbar = np.zeros(nz+1)
        etax = np.zeros(2)
        etay = np.zeros(2)

        with self.assertRaises(ValueError):
            z, growth_rate, vertical_modes = modes.instability_analysis_from_N2_profile(
                zN2, N2, f0, beta, k, l, zU, ubar, vbar, etax, etay, depth=zN2[-5]
            )

        # no error expected
        z, growth_rate, vertical_mode = modes.instability_analysis_from_N2_profile(
                zN2, N2, f0, beta, k, l, zU, ubar, vbar, etax, etay, depth=1.1
        )
예제 #4
0
def compute_fft(x, n=None, axis=True, power=True, fftshift=True, fs=1.0):
    """
    Compute and return the FFT of the input data
    :param x:
    :param n:
    :param power:
    :param fftshift:
    :return:
    """
    x = x.strip('[]')
    x = [float(i) for i in x.split(',') if i is not '']

    fft_out = fftpack.fft(x,n)

    if axis is True:
        axis_values = np.linspace(0, 2*fs, len(fft_out))
    else:
        axis_values = []

    if power is True:
        fft_out = np.abs(fft_out)

    if fftshift is True:
        fft_out = fftpack.fftshift(fft_out)
        axis_values = fftpack.fftshift(axis_values)

    outdict = {'data_in': x,
               'data_out': fft_out,
               'axis':axis_values,
                'power':power,
                'fft_shift':fft_shift}
예제 #5
0
 def sim_pic(self,data,alpha):
     '''Do the forward transform to simulate a picture. Currently with 4Pi cruft.'''
     self.alpha = alpha
     self.e1 = fftshift(exp(1j*self.alpha))
     self.e2 = fftshift(exp(2j*self.alpha))
     
     return self.Afunc(data)
예제 #6
0
파일: wt.py 프로젝트: jpcoles/jcode
def test5():
    global L0, N

    L = deepcopy(L0)
    rho = zeros(N, 'double')
    rho[0]  = 1.
    rho[N/2] = 1.

    print rho

    print fft(rho)
    rho = fftshift(fft(rho))
    print "fft(rho) =", rho

    L = fft(L).T
    L = fft(L).T

    L = fftshift(L)

    #print L

    x = linalg.solve(L, rho)
    print "x =", x
    #x[abs(x)<0.001] = 0

    x = ifftshift(ifft(x)).real * N
    print "ifft(x) =", x
    F = []
    for i in xrange(len(x)-1):
        F.append(x[i+1] - x[i])

    print "F =", F
    print "--------------------------------"
예제 #7
0
파일: miscDMD.py 프로젝트: mmcqed/DMD
def rescale_target_superpixel_resolution(E_target):
    '''Rescale the target field to the superpixel resolution (currently only 4x4 superpixels implemented)'''
    
    superpixelSize = 4
    
    ny,nx = scipy.shape(E_target)
    
    maskCenterX = scipy.ceil((nx+1)/2)
    maskCenterY = scipy.ceil((ny+1)/2)
    
    nSuperpixelX = int(nx/superpixelSize)
    nSuperpixelY = int(ny/superpixelSize)
    
    FourierMaskSuperpixelResolution = fourier_mask(ny,nx,superpixelSize)
    
    
    E_target_ft = fft.fftshift(fft.fft2(fft.ifftshift(E_target)))
    
    #Apply mask
    E_target_ft = FourierMaskSuperpixelResolution*E_target_ft
    
    #Remove zeros outside of mask
    E_superpixelResolution_ft = E_target_ft[(maskCenterY - scipy.ceil((nSuperpixelY-1)/2)-1):(maskCenterY + scipy.floor((nSuperpixelY-1)/2)),(maskCenterX - scipy.ceil((nSuperpixelX-1)/2)-1):(maskCenterX + scipy.floor((nSuperpixelX-1)/2))]
    
    # Add phase gradient to compensate for anomalous 1.5 pixel shift in real
    # plane
    
    phaseFactor = [[(scipy.exp(2*1j*pi*((k+1)/nSuperpixelY+(j+1)/nSuperpixelX)*3/8)) for j in range(nSuperpixelX)] for k in range(nSuperpixelY)] # QUESTION
    E_superpixelResolution_ft = E_superpixelResolution_ft*phaseFactor
    
    # Fourier transform back to DMD plane
    E_superpixelResolution = fft.fftshift(fft.ifft2(fft.ifftshift(E_superpixelResolution_ft)))

    return E_superpixelResolution
예제 #8
0
def standard_dsi_algorithm(S,bvals,bvecs):
    #volume size
    sz=16
    #shifting
    origin=8
    #hanning width
    filter_width=32.
    #number of signal sampling points
    n=515

    #odf radius
    #radius=np.arange(2.1,30,.1)
    radius=np.arange(2.1,6,.2)
    #radius=np.arange(.1,6,.1)   
    
    bv=bvals
    bmin=np.sort(bv)[1]
    bv=np.sqrt(bv/bmin)
    qtable=np.vstack((bv,bv,bv)).T*bvecs
    qtable=np.floor(qtable+.5)
   
    #calculate radius for the hanning filter
    r = np.sqrt(qtable[:,0]**2+qtable[:,1]**2+qtable[:,2]**2)
        
    #setting hanning filter width and hanning
    hanning=.5*np.cos(2*np.pi*r/filter_width)
    
    #center and index in q space volume
    q=qtable+origin
    q=q.astype('i8')
    
    #apply the hanning filter
    values=S*hanning
    
    #create the signal volume    
    Sq=np.zeros((sz,sz,sz))
    for i in range(n):        
        Sq[q[i][0],q[i][1],q[i][2]]+=values[i]
    
    #apply fourier transform
    Pr=fftshift(np.abs(np.real(fftn(fftshift(Sq),(sz,sz,sz)))))

    #vertices, edges, faces  = create_unit_sphere(5)    
    #vertices, faces = sphere_vf_from('symmetric362')           
    vertices, faces = sphere_vf_from('symmetric724')           
    odf = np.zeros(len(vertices))
        
    for m in range(len(vertices)):
        
        xi=origin+radius*vertices[m,0]
        yi=origin+radius*vertices[m,1]
        zi=origin+radius*vertices[m,2]
        
        PrI=map_coordinates(Pr,np.vstack((xi,yi,zi)),order=1)
        for i in range(len(radius)):
            odf[m]=odf[m]+PrI[i]*radius[i]**2
   
    peaks,inds=peak_finding(odf.astype('f8'),faces.astype('uint16'))

    return Pr,odf,peaks
def rolloff(grid_shape, nhood_shape=[6,6], ncrop=None, osfactor=2, threshold=0.01, axes=[-1, -2], combi=False, slice_prof_coef=1):
    if combi:
        nz = spatial_dims[-1]
        spatial_dims = grid_shape[:-1]
        ndims = len(spatial_dims)
        ro_data = ones(nz, dtype='complex64')
        ro_K = zeros((nz, ndims), dtype='float32')
        ro_K[:,2] = linspace(-nz/2, nz/2, nz, endpoint=False)
    else:
        spatial_dims = grid_shape
        ndims = len(spatial_dims)
        ro_data = array([1.0], dtype='complex64')
        ro_K = array([[0]*ndims], dtype='float32')
    G = sparse_matrix_operator(ro_K, grid_shape=spatial_dims, nhood_shape=nhood_shape, osfactor=osfactor, combi=combi, slice_prof_coef=slice_prof_coef)
    ro = G.T * ro_data
    n = sqrt(G.shape[1])
    ro = reshape(ro, (n,n))
    #if osfactor > 1 and ncrop == None:
    #    ncrop = int((spatial_dims[0]/osfactor) * (osfactor - 1) / 2)
    ro = fftshift(abs(ifftn(fftshift(ro, axes=axes), axes=axes)), axes=axes)  # transform to image
    if ncrop > 0:
        ro = ro[ncrop:-ncrop, ncrop:-ncrop]
    #print 'rolloff shape:', ro.shape
    ro = ro / ro.max()  # normalize
    ro[ro < threshold] = 1.0
    #ro_max = ro.max()
    #ro[ro < threshold*ro_max] = 1.0
    ro = 1.0 / ro
    #ro = ro**2
    #print 'TOOK OUT SQUARED RO'
    #ro = ro / ro.max()
    return ro
예제 #10
0
    def plot_transfer_function(self, ds):
        ax1 = pl.subplot(211)
        ax2 = pl.subplot(212)

        Hw = self.transfer_function(ds.omega)
        ax1.plot(fftp.fftshift(ds.f), np.abs(fftp.fftshift(Hw)) ** 2, "k--")
        ax2.plot(fftp.fftshift(ds.f), np.angle(fftp.fftshift(Hw)), "k--")
예제 #11
0
def genwavenumber(nlon):
    if (nlon%2 == 0):
        wavenumber = fftpack.fftshift(fftpack.fftfreq(nlon)*nlon)[1:]
    else:
        wavenumber = fftpack.fftshift(fftpack.fftfreq(nlon)*nlon)

    return wavenumber
예제 #12
0
파일: utilities.py 프로젝트: cvarin/PyOFTK
def pulseSpectrum(t, SVEAAmp, lambdaZero = 0.0, units = 'nm'):
	'''
	Compute the spectrum of o SVEA pulse center at lambdaZero
		* t: time vector
		* SVEAAmp: SVEA enveloppe of the pulse
		* lambdaZero: center of the pulse [m]
		* units: Units of the output ['nm','um','m']
	'''

	C = 2.99792458e-4
	nt = len(t)
	dt = t[1] - t[0]
	T =  t.max()-t.min()
	w = wspace(T,nt)
	vs = fftpack.fftshift(w/(2*pi))

	# Assign uniScale 
	unitScale = {
	  'nm': lambda: 1.0e9,
	  'um': lambda: 1.0e6,
	  'm': lambda: 1.0
	}[units]()

	if lambdaZero != 0.0:
		wavelength = ( 1.0/( (vs/C)+1.0/(lambdaZero) ) )*unitScale
		return [wavelength, fftpack.fftshift(pow(abs(dt*fftpack.fft(SVEAAmp)/sqrt(2.0*pi)),2))]
	else:
		return [vs, fftpack.fftshift(pow(abs(dt*fftpack.fft(SVEAAmp)/sqrt(2.0*pi)),2))]
예제 #13
0
    def __init__(self, x, y, s, detrend=True, window=False, **kwargs):
        # r-space
        self.x  = np.asanyarray(x)
        self.y  = np.asanyarray(y)
        self.s  = np.asanyarray(s)

        assert len(self.x.shape) == 2
        assert self.x.shape == self.y.shape == self.s.shape
        assert self.x.size == self.y.size == self.s.size

        # r-space spacing
        self.dx = self._delta(self.x, np.index_exp[0,0], np.index_exp[1,0])
        self.dy = self._delta(self.y, np.index_exp[0,0], np.index_exp[0,1])

        # r-space samples
        self.n0 = self.x.shape[0]
        self.n1 = self.x.shape[1]

        # r-space lengths
        self.lx = self.n0 * self.dx
        self.ly = self.n1 * self.dy

        # k-space
        u = fftpack.fftshift(fftpack.fftfreq(self.n0))
        v = fftpack.fftshift(fftpack.fftfreq(self.n1))
        self.u, self.v = np.meshgrid(u, v, indexing='ij')

        # k-space spacing
        self.du = self._delta(self.u, np.index_exp[0,0], np.index_exp[1,0])
        self.dv = self._delta(self.v, np.index_exp[0,0], np.index_exp[0,1])

        # k-space lengths
        self.lu = self.n0 * self.du
        self.lv = self.n1 * self.dv

        # nyquist
        try:
            self.nyquist_u = 0.5/self.dx
        except ZeroDivisionError:
            self.nyquist_u = 0.0

        try:
            self.nyquist_v = 0.5/self.dy
        except ZeroDivisionError:
            self.nyquist_v = 0.0

        self.k = np.sqrt(self.u**2 + self.v**2)

        # detrend the signal
        if detrend:
            self.s = signal.detrend(self.s)

        # apply window to signal
        if window:
            self._window()
            self.s = self.s * self.window

        # compute the FFT
        self.fft = fftpack.fftshift(fftpack.fft2(self.s))
        self.power = self.fft.real**2 + self.fft.imag**2
예제 #14
0
def sineSubtraction(x, N, H, sfreq, smag, sphase, fs):
	"""
	Subtract sinusoids from a sound
	x: input sound, N: fft-size, H: hop-size
	sfreq, smag, sphase: sinusoidal frequencies, magnitudes and phases
	returns xr: residual sound
	"""

	hN = N/2                                           # half of fft size
	x = np.append(np.zeros(hN),x)                      # add zeros at beginning to center first window at sample 0
	x = np.append(x,np.zeros(hN))                      # add zeros at the end to analyze last sample
	bh = blackmanharris(N)                             # blackman harris window
	w = bh/ sum(bh)                                    # normalize window
	sw = np.zeros(N)                                   # initialize synthesis window
	sw[hN-H:hN+H] = triang(2*H) / w[hN-H:hN+H]         # synthesis window
	L = sfreq.shape[0]                                 # number of frames, this works if no sines
	xr = np.zeros(x.size)                              # initialize output array
	pin = 0
	for l in range(L):
		xw = x[pin:pin+N]*w                              # window the input sound
		X = fft(fftshift(xw))                            # compute FFT
		Yh = UF_C.genSpecSines(N*sfreq[l,:]/fs, smag[l,:], sphase[l,:], N)   # generate spec sines
		Xr = X-Yh                                        # subtract sines from original spectrum
		xrw = np.real(fftshift(ifft(Xr)))                # inverse FFT
		xr[pin:pin+N] += xrw*sw                          # overlap-add
		pin += H                                         # advance sound pointer
	xr = np.delete(xr, range(hN))                      # delete half of first window which was added in stftAnal
	xr = np.delete(xr, range(xr.size-hN, xr.size))     # delete half of last window which was added in stftAnal
	return xr
예제 #15
0
파일: signal.py 프로젝트: dibgerge/utkit
    def fft(self, nfft=None, ssb=False):
        """
        Computes the Fast Fourier transform of the signal using :func:`scipy.fftpack.fft` function.
        The Fourier transform of a time series function is defined as:

        .. math::
           \mathcal{F}(y) ~=~ \int_{-\infty}^{\infty} y(t) e^{-2 \pi j f t}\,dt

        Parameters
        ----------
        nfft : int, optional
            Specify the number of points for the FFT. The default is the length of
            the time series signal.

        ssb : boolean, optional
            If true, returns only the single side band (components corresponding to positive
            frequency).

        Returns
        -------
        : Signal
            The FFT of the signal.
        """
        if nfft is None:
            nfft = self.size
        uf = Signal(fftshift(fft(self.values, n=nfft)), index=fftshift(fftfreq(nfft, self.ts)))
        return uf[uf.index >= 0] if ssb else uf
예제 #16
0
def plot_q_qhat(q, t):
    # Plot Potential Vorticity
    plt.clf()
    plt.subplot(2,1,1)
    plt.pcolormesh(xx/1e3,yy/1e3,q)
    plt.colorbar()
    plt.axes([-Lx/2e3, Lx/2e3, -Ly/2e3, Ly/2e3])
    name = "PV at t = %5.2f" % (t/(3600.0*24.0))
    plt.title(name)

    # compute power spectrum and shift ffts
    qe = np.vstack((q0,-np.flipud(q)))
    qhat = np.absolute(fftn(qe))
    kx = fftshift((parms.ikx/parms.ikx[0,1]).real)
    ky = fftshift((parms.iky/parms.iky[1,0]).real)
    qhat = fftshift(qhat)

    Sx, Sy = int(parms.Nx/2), parms.Ny
    Sk = 1.5

    # Plot power spectrum
    plt.subplot(2,1,2)
    #plt.pcolor(kx[Sy:Sy+20,Sx:Sx+20],ky[Sy:Sy+20,Sx:Sx+20],qhat[Sy:Sy+20,Sx:Sx+20])
    plt.pcolor(kx[Sy:int(Sk*Sy),Sx:int(Sk*Sx)],ky[Sy:int(Sk*Sy),Sx:int(Sk*Sx)],
               qhat[Sy:int(Sk*Sy),Sx:int(Sk*Sx)])
    plt.axis([0, 10, 0, 10])
    plt.colorbar()
    name = "PS at t = %5.2f" % (t/(3600.0*24.0))
    plt.title(name)

    plt.draw()
예제 #17
0
def find_foci(evt, type,key,type2,key2,minPhase=-500000, maxPhase=500000, steps=101, field_of_view_rad=100, wavelength=1.053, CCD_S_DIST=0.375, PX_SIZE=75e-6):
    img = evt[type][key].data
    centroids = evt[type2][key2].data

    Nfoci = centroids.shape[0]
    Xrange, Yrange = img.shape
    Npixel = field_of_view_rad
    
    p = numpy.linspace(-Xrange/2, Xrange/2-1, Xrange)
    q = numpy.linspace(-Yrange/2, Yrange/2-1, Yrange)
    pp, qq = numpy.meshgrid(p, q)
   
    phase_matrix = (2*numpy.pi/wavelength)*numpy.sqrt(1-((PX_SIZE/CCD_S_DIST)**2)*(qq**2 + pp**2))
    prop_length = numpy.linspace(minPhase, maxPhase, steps)
    
    variance = numpy.zeros([steps, Nfoci])
    # shift stuff for performance reasons
    img_shifted = fftshift(img)
    phase_matrix_shifted = fftshift(phase_matrix)
    
    for idx, phase in enumerate(prop_length):
        
        img_propagated = img_shifted * numpy.exp(1.j*phase*phase_matrix_shifted)
        recon = fftshift(ifft2(img_propagated))
        
        for CC in numpy.arange(Nfoci):
            centerx, centery = centroids[CC, :]
            ###print  centerx, centery
            reconcut = numpy.abs(recon[numpy.max([0, centerx-Npixel-1]).astype(int): numpy.min([Xrange-1, centerx+Npixel]).astype(int), numpy.max([0, centery-Npixel-1]).astype(int): numpy.min([Yrange-1, centery+Npixel]).astype(int)])
            variance[idx, CC] = reconcut.var()
    
    focus_distance = numpy.zeros(Nfoci)
    CC_size = numpy.zeros(Nfoci)
    focused_CC = numpy.zeros(4*Npixel**2 * Nfoci).reshape(Nfoci, 2*Npixel, 2*Npixel)
    
    for CC in numpy.arange(Nfoci):
        ind_max = numpy.argmax(variance[:, CC])
        tmp = variance[:, CC]
        # get max which is not at border
        loc_max_bool = numpy.r_[True, tmp[1:] > tmp[:-1]] & numpy.r_[tmp[:-1] > tmp[1:], True]
        loc_max_bool[0] = False
        loc_max_bool[-1] = False
        ind_max = numpy.argmax(tmp*loc_max_bool)
        
        focus_distance[CC] = prop_length[ind_max]
        img_propagated = img_shifted * numpy.exp(1.j * focus_distance[CC]  * phase_matrix_shifted)
        recon = fftshift(ifft2(img_propagated))
        
        centerx, centery = centroids[CC, :]
        
        reconcut = numpy.real(recon[numpy.max([0, centerx-Npixel]).astype(int): numpy.min([Xrange-1, centerx+Npixel]).astype(int), numpy.max([0, centery-Npixel]).astype(int): numpy.min([Yrange-1, centery+Npixel]).astype(int)])
        focused_CC[CC, 0:reconcut.shape[0], 0:reconcut.shape[1]] = reconcut
        CC_size[CC] = numpy.sum(get_CC_size(reconcut))
    
    if len(focused_CC):
        add_record(evt["analysis"], "analysis", "focused_CC", focused_CC[0])
        add_record(evt["analysis"], "analysis", "focus distance", focus_distance)
        add_record(evt["analysis"], "analysis", "CC_size", CC_size)
        add_record(evt["analysis"], "analysis", "propagation length", prop_length)
예제 #18
0
    def fourierTransform(self, fromPos, toPos, only = []):
        self.checkToPos(toPos)
        if len(only) > 0:
            self.allFid[toPos] = np.array([fftshift(fft(self.allFid[fromPos][fidIndex])) for fidIndex in only])
        else:
            self.allFid[toPos] = np.array([fftshift(fft(fid)) for fid in self.allFid[fromPos]])

        self.frequency = np.linspace(-self.sweepWidthTD2/2,self.sweepWidthTD2/2,len(self.allFid[fromPos][0]))
예제 #19
0
def f2(file1, file2):
  from scipy.fftpack import fftshift
  (imgarr1,w,h) = pgm.pgmread(file1)
  (imgarr2,w,h) = pgm.pgmread(file2)
  imgarr1 = np.float32(imgarr1)
  imgarr2 = np.float32(imgarr2)
  print imgarr1.shape, imgarr2.shape
  #
  dftArr1 = dft_2d_from_1d(imgarr1)
  dftArr2 = dft_2d_from_1d(imgarr2)
  #
  absArr1 = np.abs(dftArr1)
  absArr2 = np.abs(dftArr2)
  phaseArr1 = np.angle(dftArr1)
  phaseArr2 = np.angle(dftArr2)
  #
  newArr1 = absArr1 * np.exp(1j * phaseArr2)
  newArr2 = absArr2 * np.exp(1j * phaseArr1)
  #print 'Error : ', np.sum((newArr1 - dftArr1)**2)
  #print 'Error : ', np.sum((newArr2 - dftArr2)**2)
  #
  idftArr1 = idft_2d_from_1d(newArr1)
  idftArr2 = idft_2d_from_1d(newArr2)
  idftArr1 = np.round(idftArr1.real)
  idftArr2 = np.round(idftArr2.real)
  #
  dftArrAbs1 = np.abs(fftshift(dftArr1))
  dftArrAbs2 = np.abs(fftshift(dftArr2))
  #
  plt.figure()
  plt.subplot(121)
  plt.title(file1)
  plt.imshow(imgarr1, cmap=cm.gray)
  #plt.colorbar()
  plt.subplot(122)
  plt.title(file2)
  plt.imshow(imgarr2, cmap=cm.gray)
  #plt.colorbar()
  #
  plt.figure()
  plt.subplot(121)
  plt.title('DFT of ' + file1)
  plt.imshow(np.int32(np.log(dftArrAbs1)), cmap=cm.gray)
  plt.colorbar()
  plt.subplot(122)
  plt.title('DFT of ' + file2)
  plt.imshow(np.int32(np.log(dftArrAbs2)), cmap=cm.gray)
  plt.colorbar()
  #
  plt.figure()
  plt.subplot(121)
  plt.title('IDFT1')
  plt.imshow(np.int32(idftArr1), cmap=cm.gray)
  #plt.colorbar()
  plt.subplot(122)
  plt.title('IDFT2')
  plt.imshow(np.int32(idftArr2), cmap=cm.gray)
예제 #20
0
def plot_fft_shifted(x, y, *args, **kwargs):
    import pylab
    symmetric = False
    if "symmetric" in kwargs:
        symmetric = kwargs.pop("symmetric")
    if symmetric and np.mod(x.shape[0],2)==0:
        pylab.plot(fftp.fftshift(x)[1:], fftp.fftshift(y)[1:], *args, **kwargs)
    else:
        pylab.plot(fftp.fftshift(x), fftp.fftshift(y), *args, **kwargs)
예제 #21
0
 def test_definition(self):
     x = [0,1,2,3,4,-4,-3,-2,-1]
     y = [-4,-3,-2,-1,0,1,2,3,4]
     assert_array_almost_equal(fftshift(x),y)
     assert_array_almost_equal(ifftshift(y),x)
     x = [0,1,2,3,4,-5,-4,-3,-2,-1]
     y = [-5,-4,-3,-2,-1,0,1,2,3,4]
     assert_array_almost_equal(fftshift(x),y)
     assert_array_almost_equal(ifftshift(y),x)
예제 #22
0
def plot_all_domains(inputfile, fs):
    #fs= float(50/3 * 1000000.0)   
    fs=25*1000000.0


    if inputflag==1:
        [x,y, mag, phase,z] = filereader(inputfile,int(fs))
        del x, y, phase
        #mag=butter_lowpass_filter(mag, upper_cut, fs, 6)
        #mag = butter_bandpass_filter(mag, lower_cut, upper_cut, fs, order=5)
        #print "done with bandpass filter"
        ceps, _ = complex_cepstrum(mag)
        t = [i for i in range(0,len(mag))] 
        fig = plt.figure(figsize=(12,10))
        ax0 = fig.add_subplot(311)
        ax0.plot(t, mag)
        ax0.set_ylim(0,0.18)
        ax0.set_xlabel('[time domain]  time (1 unit=10^-7 sec)')
        ax0.set_ylabel('amplitude modulus')
        #ax0.set_xlim(0.0, 0.05)

        ax1 = fig.add_subplot(312)
        ax1.plot(t, ceps)
        ax1.set_xlabel('[cepstral domain] quefrency in 1 unit')
        ax1.set_ylabel('magnitude')
        ax1.set_ylim(-80,80)
        ax1.set_xscale('log')

        ax2 = fig.add_subplot(313)

        '''
        f, Pxx_den = signal.periodogram(mag, fs)
        ax2.plot(f, Pxx_den)
        ax2.set_xlabel('frequency')
        ax2.set_ylabel('magnitude')
        ax2.set_ylim(0,7e-8)
        ax2.set_xscale('log')
        plt.savefig(outputfile+'.pdf')
        '''

        from scipy.fftpack import fft, fftfreq, fftshift
        N=len(mag)
        freqs = fftfreq(N, 1.0/fs)
        freqs = fftshift(freqs)
        yf= 1.0/N *fft(mag)
        yf = fftshift(yf)
        ax2.plot(freqs,  np.abs(yf))
        #print "freqs is ", freqs
        #print "FFT vals are",  np.abs(yf)
        ax2.set_xlabel('[spectral domain] frequency')
        ax2.set_ylabel('magnitude (log)')
        ax2.set_yscale('log')
        ax2.set_xlim(0,500000)
        ax2.set_ylim(10e-9,10e-1)

        plt.savefig(outputfile+'.pdf')
예제 #23
0
    def test_Eady(self, atol=5e-2, nz=20, Ah=0.):
        """ Eady setup
        """
        ###########
        # prepare parameters for Eady
        ###########
        nz = nz
        zin = np.arange(nz+1, dtype=np.float64)/nz
        N2 = np.full(nz, 1.)
        f0 = 1.
        beta = 0.
        Nx = 10
        Ny = 1
        dx = 1e-1
        dy = 1e-1
        k = fft.fftshift( fft.fftfreq(Nx, dx) )
        l = fft.fftshift( fft.fftfreq(Ny, dy) )
        vbar = np.zeros(nz+1)
        ubar = zin
        etax = np.zeros(2)
        etay = np.zeros(2)

        z, growth_rate, vertical_modes = \
            modes.instability_analysis_from_N2_profile(
                .5*(zin[1:]+zin[:-1]), N2, f0, beta, k, l,
                zin, ubar, vbar, etax, etay, depth=1., sort='LI', num=2
        )

        self.assertEqual(nz+1, vertical_modes.shape[0],
            msg='modes array must be in the right shape')

        self.assertTrue(np.all( np.diff(
                    growth_rate.reshape((growth_rate.shape[0], len(k)*len(l))).imag.max(axis=1) ) <= 0.),
            msg='imaginary part of modes should be descending')

        mode_amplitude1 = (np.absolute(vertical_modes[:, 0])**2).sum(axis=0)
        self.assertTrue(np.allclose(1., mode_amplitude1),
            msg='mode1 should be normalized to amplitude of 1 at all horizontal wavenumber points')

        mode_amplitude2 = (np.absolute(vertical_modes[:, 1])**2).sum(axis=0)
        self.assertTrue(np.allclose(1., mode_amplitude2),
            msg='mode2 should be normalized to amplitude of 1 at all horizontal wavenumber points')

        #########
        # Analytical solution for Eady growth rate
        #########
        growthEady = np.zeros(len(k))
        for i in range(len(k)):
            if (k[i]==0) or ((np.tanh(.5*k[i])**-1 - .5*k[i]) * (.5*k[i] - np.tanh(.5*k[i])) < 0):
                growthEady[i] = 0.
            else:
                growthEady[i] = ubar.max() * np.sqrt( (np.tanh(.5*k[i])**-1 - .5*k[i]) * (.5*k[i] - np.tanh(.5*k[i])) )

        self.assertTrue( np.allclose(growth_rate.imag[0, 0, :], growthEady, atol=atol),
            msg='The numerical growth rates should be close to the analytical Eady solution' )
예제 #24
0
파일: twod.py 프로젝트: natl/norotate
 def gravity(self):
   '''
   Evaluate the gravitational field, with a call to Bose.gravity()
   Gravitaional field is the convolution of the density and the log of distance
   '''
   den = abs(self.psi)**2.  #calculate the probability density
   
   #return the convolution, after multiplying by scaled gravity and 
   #correcting for grid scaling (due to 2 forward FFTs, and only one inverse
   return self.G*self.dx*self.dy*(ff.fftshift(ff.ifft2(ff.fft2(ff.fftshift(den)
     )*abs(ff.fft2(ff.fftshift(-self.log))))))
예제 #25
0
파일: utils.py 프로젝트: marcoviero/Utils
def alex_power_spec(map1, map2=None, deltal = 1, pixsize = 5.0):

  dims = np.shape(map1)
  if (map2 != None):
    spec = fftpack.fftshift(fftpack.fft2(map1)) * np.conj(fftpack.fftshift(fftpack.fft2(map2))) * (pi*pixsize/10800./60.)**2.0 * (dims[0]*dims[1])
  else:
    spec = np.abs(fftpack.fftshift(fftpack.fft2(map1))*(pi*pixsize/10800./60.))**2.0 * (dims[0]*dims[1])

  spec1d = radial_data(spec, annulus_width = deltal)

  return spec1d
예제 #26
0
	def _FilterElectrons(self,sign):
 		'''
		Routine that uses the Fourier transform to filter positrons/electrons
		Options:
			sign=1   Leaves electrons
			sign=-1	 Leaves positrons
		'''
		print '  '
		print '  	Filter Electron routine '
		print '  '
                min_Px = np.pi*self.X_gridDIM/(2*self.min_X)
		dPx = 2*np.abs(min_Px)/self.X_gridDIM
		px_Vector  = fftpack.fftshift ( np.linspace(min_Px, np.abs(min_Px) - dPx, self.X_gridDIM ))

		min_Py = np.pi*self.Y_gridDIM/(2*self.min_Y)
		dPy = 2*np.abs(min_Py)/self.Y_gridDIM
		py_Vector  = fftpack.fftshift ( np.linspace(min_Py, np.abs(min_Py) - dPy, self.Y_gridDIM ))


		px = px_Vector[np.newaxis,:]
		py = py_Vector[:,np.newaxis]


		sqrtp = sign*2*np.sqrt( self.mass*self.mass*self.c**4 + self.c*self.c*px*px + self.c*self.c*py*py )
		aa = sign*self.mass*self.c*self.c/sqrtp
		bb = sign*(px/sqrtp - 1j*py/sqrtp)
		cc = sign*(px/sqrtp + 1j*py/sqrtp)
	        
		ElectronProjector = np.matrix([ [0.5+aa , 0.  , 0.  , bb  ],
						[0. , 0.5+aa  , cc  , 0.  ],
						[0. , bb  , 0.5-aa  , 0.  ],
						[cc , 0.  , 0.  , 0.5-aa] ])

		psi1_fft = fftpack.fft2( self.Psi1_init   ) 
		psi2_fft = fftpack.fft2( self.Psi2_init   ) 
		psi3_fft = fftpack.fft2( self.Psi3_init   ) 
		psi4_fft = fftpack.fft2( self.Psi4_init   ) 		
		
		psi1_fft_electron = ElectronProjector[0,0]*psi1_fft + ElectronProjector[0,1]*psi2_fft +\
		ElectronProjector[0,2]*psi3_fft + ElectronProjector[0,3]*psi4_fft	

		psi2_fft_electron = ElectronProjector[1,0]*psi1_fft + ElectronProjector[1,1]*psi2_fft +\
		ElectronProjector[1,2]*psi3_fft + ElectronProjector[1,3]*psi4_fft

                psi3_fft_electron = ElectronProjector[2,0]*psi1_fft + ElectronProjector[2,1]*psi2_fft +\
		ElectronProjector[2,2]*psi3_fft + ElectronProjector[2,3]*psi4_fft	

                psi4_fft_electron = ElectronProjector[3,0]*psi1_fft + ElectronProjector[3,1]*psi2_fft +\
		ElectronProjector[3,2]*psi3_fft + ElectronProjector[3,3]*psi4_fft

                self.Psi1_init  = fftpack.ifft2( psi1_fft_electron   ) 
		self.Psi2_init  = fftpack.ifft2( psi2_fft_electron   ) 
		self.Psi3_init  = fftpack.ifft2( psi3_fft_electron   ) 
		self.Psi4_init  = fftpack.ifft2( psi4_fft_electron   ) 					
예제 #27
0
def myconv2(A, B, zeropadding = False):
    # TO DO: zero padding to get rid of aliasing!
    if zeropadding:
        origdim = A.shape
        nextpow = pow(2, numpy.ceil(numpy.log(numpy.max(origdim))/numpy.log(2))+1)
        A = zeropad(A, nextpow.astype(int), nextpow.astype(int))
        B = zeropad(B, nextpow.astype(int), nextpow.astype(int))
    output = fftshift(ifft2( numpy.multiply(fft2(fftshift(A)), fft2(fftshift(B)) )))
    if zeropadding:
        output = output[nextpow/2 - origdim[0]/2: nextpow/2 + origdim[0]/2,nextpow/2 - origdim[1]/2: nextpow/2 + origdim[1]/2]
    return output
예제 #28
0
파일: cmb.py 프로젝트: amanzotti/PyCosmo
 def add_noise(self, temp):
   """
   Add per-pixel Gaussian random noise.
   """
   self.noise = random.normal(0,temp,[self.npix,self.npix])
   self.Fnoise = ft.fftshift(ft.fft2(self.noise))
   self.Txy = self.Txy + self.noise
   self.Fxy = ft.fftshift(ft.fft2(self.Txy))
   
   self.Clnoise = ((temp*self.mapsize_rad/self.npix)*self.Bl)**-2.e0
   self.Pknoise = np.interp(self.modk, self.k, self.Clnoise)
예제 #29
0
파일: dsi.py 프로젝트: jgors/dipy
 def pdf(self,s):
     values=s*self.filter
     #create the signal volume    
     Sq=np.zeros((self.sz,self.sz,self.sz))
     #fill q-space
     for i in range(self.dn):
         qx,qy,qz=self.q[i]            
         Sq[qx,qy,qz]+=values[i]
     #apply fourier transform
     Pr=fftshift(np.abs(np.real(fftn(fftshift(Sq),(self.sz,self.sz,self.sz)))))
     return Pr
예제 #30
0
def fftshift(x):
    # Wrapper for fftshift that handles CXData objects
    if isinstance(x, CXData):
        l=[]
        for i in xrange(len(x)):
            l.append(spf.fftshift(x.data[i]))

        return CXData(data=l)
    elif isinstance(x, np.ndarray):
        return spf.fftshift(x)
    else:
        raise Exception('Unknown data type passed to fftshift')
예제 #31
0
 def test_inverse(self):
     for n in [1,4,9,100,211]:
         x = random((n,))
         assert_array_almost_equal(ifftshift(fftshift(x)),x)
예제 #32
0
# Plot the window and its frequency response:

from scipy import signal
from scipy.fftpack import fft, fftshift
import matplotlib.pyplot as plt

window = signal.cosine(51)
plt.plot(window)
plt.title("Cosine window")
plt.ylabel("Amplitude")
plt.xlabel("Sample")

plt.figure()
A = fft(window, 2048) / (len(window) / 2.0)
freq = np.linspace(-0.5, 0.5, len(A))
response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
plt.plot(freq, response)
plt.axis([-0.5, 0.5, -120, 0])
plt.title("Frequency response of the cosine window")
plt.ylabel("Normalized magnitude [dB]")
plt.xlabel("Normalized frequency [cycles per sample]")
plt.show()
예제 #33
0
    # Simple Moving Average low pass filter
    ntaps = 1000
    coeffs = np.ones(ntaps)
    filt_out = sig.lfilter(coeffs, ntaps, out)
    plt.plot(filt_out)
    # exponential MAF
    alpha = 0.999
    filt_out2 = sig.lfilter([1 - alpha], [1, -alpha], out)
    plt.plot(filt_out2)

    # frequency response of simple moving avg
    w, h = sig.freqz(coeffs, whole=True, fs=Fs)
    plt.figure()
    db_mag = hf.db(h)
    plt.plot((w - Fs / 2) / 1e3, fft.fftshift(db_mag), label='simple moving avg')
    plt.xlabel('Frequency [kHz]')
    plt.ylabel('Magnitude [dB]')
    plt.title('Filter Frequency Response')
    # both mag and phase plot
    # hf.responsePlot(w, h, 'simple moving avg frequency response')

    # frequency response of simple moving avg
    w, h = sig.freqz([1 - alpha], [1, -alpha], whole=True, fs=Fs)
    # plt.figure()
    db_mag = hf.db(h)
    plt.plot((w - Fs / 2) / 1e3, fft.fftshift(db_mag), label='exponential MAF')
    plt.legend()

    # example spectrum
    plt.figure()
예제 #34
0
for i in np.arange(1990, 2021, 1):
    r.append(Time('{}-01-01 00:00:00'.format(i), format='iso').jd - 2451544.5)

r = np.array(r)

#########################################################################
x = eph[0]
y = eph[7]

# number of signal points
N = len(eph[0])
# sample spacing
T = (x.max() - x.min()) / N
yf = fft(y)
xf = fftfreq(N, T)
xf = fftshift(xf)
yplot = fftshift(yf)
fig, ax = plt.subplots(2, 1)
ax[0].plot(x, y)
ax[0].set_xlabel('Time')
ax[0].set_ylabel('Amplitude')
#ax[0].set_ticks(r)
#ax[0].set_ticklabels(['{}'.format(i) for i in np.arange(1990,2021,1)], rotation=90)
ax[1].plot(xf, 1.0 / N * np.abs(yplot), 'r')  # plotting the spectrum
ax[1].set_xlabel(r'Freq ($day^{-1}$)')
ax[1].set_ylabel('|Y(freq)|')
#plt.plot(xf, 1.0/N * np.abs(yplot))
plt.grid()
ax[1].set_xlim(0.00, 0.01)
plt.savefig('freq_x.png', dpi=100)
예제 #35
0
import cv2
import numpy, math
import scipy.fftpack as fftim
from PIL import Image

# Opening the image and converting it to grayscale.
a = Image.open('../Figures/endothelium.png').convert('L')
# Performing FFT.
b = fftim.fft2(a)
# Shifting the Fourier frequency image.
c = fftim.fftshift(b)

# Intializing variables for convolution function.
M = c.shape[0]
N = c.shape[1]
# H is defined and values in H are initialized to 1.
H = numpy.ones((M, N))
center1 = M / 2
center2 = N / 2
d_0 = 30.0  # cut-off radius
t1 = 2 * d_0

# Defining the convolution function for GHPF.
for i in range(1, M):
    for j in range(1, N):
        r1 = (i - center1)**2 + (j - center2)**2
        # Euclidean distance from
        # origin is computed.
        r = math.sqrt(r1)
        # Using cut-off radius to
        # eliminate low frequency.
예제 #36
0
def profileFit(r, Nmin, mu):
    """
    This function calculates the power spectrum profile using
    a shifted exponential decay model.

    """
    f = N0 * np.exp(-mu * r) + Nmin
    return f


#--Main Program
testImage = skio.imread('testBiofilmImage.tif')

# perform the Fourier Transform
fft1 = scfft.fft2(testImage)
fft2 = scfft.fftshift(fft1)

# calculate the power spectrum
ps = np.abs(fft2)
ps = 20 * np.log10(ps)
ps = ps.astype(int)
h, w = ps.shape

# make sure all power spectrum values greater than or equal to
# zero
for r in range(h):
    for c in range(w):
        if ps[r, c] < 0:
            ps[r, c] = 0
# define angles
thetaMax = 85
예제 #37
0
                                y1_filt[len(y1) - 1]) / 3
        y2_filt[len(y2) - 2] = (y2_filt[len(y2) - 3] + y2_filt[len(y2) - 2] +
                                y2_filt[len(y2) - 1]) / 3

# Transformada de fourier:
#   yn_fft x_fft: realizam a trasnformada de fourier no espectro de frequência
#   yn_fft_plot x_fft_plot: inicialmente é usado um 'shift'(deslocamento) para jogar as
#       componentes negativas que estão após as componentes positivas quando usamos
#       numpy.fft.fftshift, para o início do array.
#   yn_fft_plot x_fft_plot: são usados novamente para agora selecionar somente as frequências
#       positivas e suas componentes

y1_fft = fft(y1_filt)
y2_fft = fft(y2_filt)
x_fft = fftfreq(N, T)
x_fft_plot = fftshift(x_fft)
x_fft_plot = x_fft_plot[N / 2:N]
y1_fft_plot = fftshift(y1_fft)
y2_fft_plot = fftshift(y2_fft)
y1_fft_plot = np.abs(y1_fft_plot[N / 2:N])
y2_fft_plot = np.abs(y2_fft_plot[N / 2:N])

# Transformada de fourier na metade de todo período:
N_half = int(N / 2)
t_half = float(t_final + t_inicial) / 2

x_half_fft = fftfreq(N_half, T)
x_half_fft = fftshift(x_half_fft)
x_half_fft = x_half_fft[math.floor(N_half / 2):N_half]

y1_half_1_fft = fft(y1_filt[0:N_half])
예제 #38
0
def get_shifted_fourier_chart(img):
	fourier = fftpack.fft2(img)
	fourier_shifted = fftpack.fftshift( fourier ) # shift so that low spatial frequencies are in the center.
	fourier_abs = np.abs(fourier_shifted) #This array that we use is the absolute value of the shifted fourier transform

	return fourier_shifted, fourier_abs
예제 #39
0
    def reconstruction(self):
        """main reconstruction function"""
        #initiate time counters
        timestart = time.time()
        timershow = 0  #for measuring the time interval from the last results indication
        Showstep = 0.5  #time interval between showing results
        timercheck = 0  #for measuring the time interval from the last inputs check
        Checkstep = 0.25  #time interval between checking inputs (including stop)

        while self.Stop and self.Results['Step'] < self.Args[
                'ret_iterations'] and self.Results['G'] > self.Args['G_goal']:
            (self.Results['pulse'], self.Results['gate'], self.Results['G'],
             self.Results['frog_out']) = PCGPA.PCGPA_step(
                 self.Results['pulse'],
                 self.Results['gate'],
                 self.Results['frog_in'],
                 Type=self.Args['type'])

            if self.Args['fix_fund_spec']:
                """fixing the fundumental spectrum"""
                pulse_w = np.sqrt(self.Results['Sfund']) * np.exp(
                    1j *
                    np.angle(fftshift(fft(fftshift(self.Results['pulse'])))))
                pulse_t = ifftshift(ifft(ifftshift(pulse_w)))
                if self.Args['type'] == 'SHG-FROG':
                    gate_t = np.copy(pulse_t)
                elif self.Args['type'] == 'TG-FROG':
                    gate_t = np.abs(np.abs(np.copy(pulse_t)))**2
                self.Results['pulse'] = pulse_t
                #self.Results['pulse_w']=pulse_w
                self.Results['gate'] = gate_t
                #recalculate frog_sim and G for the corrected pulse
                (self.Results['G'], self.Results['frog_out']) = PCGPA.PCGPA_G(
                    self.Results['pulse'], self.Results['gate'],
                    self.Results['frog_in'])

            if self.Results['Step'] == 0:
                self.Results['G_best'] = self.Results['G']
                self.Results['pulse_best'] = self.Results['pulse']
                self.Results['gate_best'] = self.Results['gate']
                self.Results['frog_out_best'] = self.Results['frog_out']
                self.Results['pulse_w_best'] = fftshift(
                    fft(fftshift(self.Results['pulse_best'])))

            #save the best reconstruction
            if self.Results['G'] < self.Results['G_best'] and self.Results[
                    'Step'] > 0:
                (self.Results['pulse'],
                 self.Results['gate']) = PCGPA.shift2zerodelay(
                     self.Results['pulse'], self.Results['gate'])
                self.Results['G_best'] = self.Results['G']
                self.Results['pulse_best'] = self.Results['pulse']
                self.Results['gate_best'] = self.Results['gate']
                self.Results['frog_out_best'] = self.Results['frog_out']
                #shift to 0 delay

            self.Results['Time'] = time.time() - timestart
            if (self.Results['Time'] - timershow) > Showstep:
                timershow = self.Results['Time']

                self.Results['pulse_w_best'] = fftshift(
                    fft(fftshift(self.Results['pulse_best'])))
                self.showresults()
            if (self.Results['Time'] - timercheck) > Checkstep:
                timercheck = self.Results['Time']
                self.app.processEvents()

            if self.Results['Step'] == 0:
                self.showresults()

            self.Results['Step'] += 1
    def update_data(self, x, taps, psd, syms, table):
        try:
            eqdata_key = 'dtv_atsc_equalizer0::taps'
            symdata_key = 'dtv_atsc_equalizer0::data'
            rs_nump_key = 'dtv_atsc_rs_decoder0::num_packets'
            rs_numbp_key = 'dtv_atsc_rs_decoder0::num_bad_packets'
            rs_numerrs_key = 'dtv_atsc_rs_decoder0::num_errors_corrected'
            vt_metrics_key = 'dtv_atsc_viterbi_decoder0::decoder_metrics'
            snr_key = 'probe2_f0::SNR'

            data = self.radio.getKnobs([])
            eqdata = data[eqdata_key]
            symdata = data[symdata_key]
            rs_num_packets = data[rs_nump_key]
            rs_num_bad_packets = data[rs_numbp_key]
            rs_num_errors_corrected = data[rs_numerrs_key]
            vt_decoder_metrics = data[vt_metrics_key]
            snr_est = data[snr_key]

            vt_decoder_metrics = scipy.mean(vt_decoder_metrics.value)
            self._viterbi_metric.pop()
            self._viterbi_metric.insert(0, vt_decoder_metrics)

        except:
            sys.stderr.write("Lost connection, exiting")
            sys.exit(1)

        ntaps = len(eqdata.value)
        taps.set_ydata(eqdata.value)
        taps.set_xdata(xrange(ntaps))
        self._sp0.set_xlim(0, ntaps)
        self._sp0.set_ylim(min(eqdata.value), max(eqdata.value))

        fs = 6.25e6
        freq = scipy.linspace(-fs / 2, fs / 2, 10000)
        H = fftpack.fftshift(fftpack.fft(eqdata.value, 10000))
        HdB = 20.0 * scipy.log10(abs(H))
        psd.set_ydata(HdB)
        psd.set_xdata(freq)
        self._sp1.set_xlim(0, fs / 2)
        self._sp1.set_ylim([min(HdB), max(HdB)])
        self._sp1.set_yticks([min(HdB), max(HdB)])
        self._sp1.set_yticklabels(["min", "max"])

        nsyms = len(symdata.value)
        syms.set_ydata(symdata.value)
        syms.set_xdata(nsyms * [
            0,
        ])
        self._sp2.set_xlim([-1, 1])
        self._sp2.set_ylim([-10, 10])

        per = float(rs_num_bad_packets.value) / float(rs_num_packets.value)
        ber = float(rs_num_errors_corrected.value) / float(
            187 * rs_num_packets.value)

        table._cells[(1, 0)]._text.set_text("{0}".format(rs_num_packets.value))
        table._cells[(1, 1)]._text.set_text("{0:.2g}".format(ber))
        table._cells[(1, 2)]._text.set_text("{0:.2g}".format(per))
        table._cells[(1, 3)]._text.set_text("{0:.1f}".format(
            scipy.mean(self._viterbi_metric)))
        table._cells[(1, 4)]._text.set_text("{0:.4f}".format(snr_est.value[0]))

        return (taps, psd, syms, table)
예제 #41
0
import scipy.misc
import numpy, math
import scipy.fftpack as fftim
from scipy.misc.pilutil import Image

# opening the image and converting it to grayscale
a = Image.open('../Figures/endothelium.png').convert('L')
# a is converted to an ndarray
b = scipy.misc.fromimage(a)
# performing FFT
c = fftim.fft2(b)
# shifting the Fourier frequency image
d = fftim.fftshift(c)

# intializing variables for convolution function
M = d.shape[0]
N = d.shape[1]
# H is defined and
# values in H are initialized to 1
H = numpy.ones((M, N))
center1 = M / 2
center2 = N / 2
d_0 = 30.0  # cut-off radius

# defining the convolution function for IHPF
for i in range(1, M):
    for j in range(1, N):
        r1 = (i - center1)**2 + (j - center2)**2
        # euclidean distance from
        # origin is computed
        r = math.sqrt(r1)
예제 #42
0
#############################################################
# 4. Data & Globals
#############################################################

data_N = 40
data_m = m_e.value
data_L = 0.1e-3

x_samples = 10000
x_spacing = (2. * data_L) / x_samples

data_X = np.linspace(0, x_spacing * x_samples, x_samples)
data_T = np.linspace(0, 200e-6, 500)

data_K = fftshift(fftfreq(x_samples, x_spacing))

CACHE  = {
    'psiT': {},
    'psikT': {}
}

#############################################################
# 5. Lab-Specific Functions
#############################################################

def terminate():
    # Any memory clearing logic and stuff

    global CACHE
    purge_tree(CACHE)
예제 #43
0
    def __init__(self,
                 rho=False,
                 K=False,
                 N=256,
                 C=2e-6,
                 f=5,
                 kernel=True,
                 Mtot=1.,
                 L=1.,
                 hbar_=1e-6,
                 mpart=4e-6,
                 hbar=4e-12,
                 dt=1e-3,
                 label='g'):

        self.label = label

        self.N = N  # grid cells

        self.hbar_ = hbar_
        self.hbar = hbar
        self.mpart = mpart

        # density matrix, NxN complex numbers, diagonal sum is 1 NOT Mtot
        if rho:
            self.rho = rho
        else:
            self.rho = np.zeros((N, N)) + 0j

        self.C = C  # poisson constant

        self.Mtot = Mtot  # total mass

        self.L = L  # side length

        self.dx = L / N

        self.x = self.dx * (.5 + np.arange(-self.N / 2, self.N / 2))

        self.sig_x = self.dx * f

        self.T_scale = np.pi * 2. / np.sqrt(np.abs(
            C * Mtot / L))  # time scaling factor

        self.kx = 2 * np.pi * sp.fftfreq(N, d=L / N)
        Kj, Ki = np.meshgrid(-self.kx, self.kx)
        dK2 = Ki**2 - Kj**2
        self.HK = np.exp(self.hbar_ * dK2 * dt * self.T_scale / 4. *
                         1.0j)  #kinetic term for Hamiltonian

        self.u = hbar_ * sp.fftshift(self.kx)
        self.du = self.u[1] - self.u[0]

        self.omega0 = np.sqrt(np.abs(self.C * self.Mtot / self.L))
        self.u_c = self.L * self.omega0 / (2. * np.pi)

        self.dt = dt

        self.K = None
        if kernel:
            if K is None:
                self.setKernel()
            else:
                self.refer2Kernel(K)  # Husimi kernel
예제 #44
0
 def getRhoU(self):
     rho_u = sp.ifft(sp.fft(sp.ifft(sp.fft(self.rho, axis=3), axis=2),
                            axis=1),
                     axis=0)
     return sp.fftshift(self.Mtot * np.abs(np.einsum("aacc->ac", rho_u)))
    #plotting the mean intensity of each image as we cycle through images
    for i in radians:
        image = Image.open("./imagesbeads " + str(mode_num) + str(i) + ".tiff")
        imarray = np.asarray(image, dtype='uint16')
        fft2 = fftpack.fft2(imarray)
        masked_image = fftpack.fftshift(fft2) * ring_mask
        mean_pixel = np.mean(abs(masked_image))
        avfreq_vals.append(mean_pixel)
    return avfreq_vals


out_mask = MakeMask(radius, cut)
in_mask = (MakeMask(radius, cut * 0.6))
ring_mask = out_mask * ((in_mask - 1) * -1)
fft2 = fftpack.fft2(imarray)

masked_image = fftpack.fftshift(fft2) * ring_mask
plot_spectrum(masked_image)
plt.show()
#print(av_freq(mode_num1))
plt.title('Fourier transform')
#print('mean pixel value of this is', np.mean(abs(masked_image)))
#print(av_freq(mode_num1))
#print(av_intensity(mode_num1))
plt.plot(
    [1, 2, 3, 4, 5, 6, 7, 8],
    av_freq(mode_num1),
    'ro',
)
plt.show()
예제 #46
0
def main():
    # Create images folder

    Path("Imgs").mkdir(exist_ok=True)

    # Carga traza STEAD

    # st = '../Data_STEAD/Train_data.hdf5'
    #
    # with h5py.File(st, 'r') as h5_file:
    #     grp = h5_file['earthquake']['local']
    #     for idx, dts in enumerate(grp):
    #         st_trace = grp[dts][:, 0] / np.max(np.abs(grp[dts][:, 0]))
    #         break

    # 1984 trazas de 12600 muestras
    f = '../Data_Shaker/large shaker NEES_130910161319 (1).sgy'

    with segyio.open(f, ignore_geometry=True) as segy:
        segy.mmap()

        traces = segyio.tools.collect(segy.trace[:])
        # fs = segy.header[0][117] NO ES LA REAL

    # Sampling frequency
    fs = 200

    # Number of traces to plot
    n = 4

    # Traces to plot
    trtp = []

    # Init rng
    rng = default_rng()

    # Traces to plot numbers
    trtp_ids = rng.choice(len(traces), size=n, replace=False)
    trtp_ids.sort()

    # Retrieve selected traces
    for idx, trace in enumerate(traces):
        if idx in trtp_ids:
            trtp.append(trace)

    # Data len
    N = traces.shape[1]

    # Time axis for signal plot
    t_ax = np.arange(N) / fs

    # Frequency axis for FFT plot
    xf = np.linspace(-fs / 2.0, fs / 2.0 - 1 / fs, N)

    # Figure to plot
    plt.figure()

    # Plot n random traces with their spectrum
    for idx, trace in enumerate(trtp):
        yf = sfft.fftshift(sfft.fft(trace))

        plt.clf()
        plt.subplot(211)
        plt.plot(t_ax, trace)
        plt.title(f'Traza Shaker y espectro #{trtp_ids[idx]}')
        plt.xlabel('Tiempo [s]')
        plt.ylabel('Amplitud [-]')
        plt.grid(True)

        plt.subplot(212)
        plt.plot(xf, np.abs(yf) / np.max(np.abs(yf)))
        plt.xlabel('Frecuencia [Hz]')
        plt.ylabel('Amplitud [-]')
        plt.grid(True)
        plt.tight_layout()
        plt.savefig(f'Imgs/Shaker_{trtp_ids[idx]}')
예제 #47
0
파일: gam.py 프로젝트: IssamLaradji/wisenet
def deconvolve(star, psf):
    star_fft = fftpack.fftshift(fftpack.fftn(star))
    psf_fft = fftpack.fftshift(fftpack.fftn(psf))
    return fftpack.fftshift(
        fftpack.ifftn(fftpack.ifftshift(star_fft / psf_fft)))
예제 #48
0
def getpowerspectrum(g):
    gback = fftpack.fft2(g)
    gback2 = fftpack.fftshift(gback)
    gback2 = np.abs(gback2)**2
    ps2 = radialProfile.azimuthalAverage(gback2)
    return ps2
예제 #49
0
def main():
    tstart = time.time()

    tb = pfb_top_block()
    tb.run()

    tend = time.time()
    print "Run time: %f" % (tend - tstart)

    if 1:
        fig_in = pylab.figure(1, figsize=(16, 9), facecolor="w")
        fig1 = pylab.figure(2, figsize=(16, 9), facecolor="w")
        fig2 = pylab.figure(3, figsize=(16, 9), facecolor="w")
        fig3 = pylab.figure(4, figsize=(16, 9), facecolor="w")

        Ns = 650
        Ne = 20000

        fftlen = 8192
        winfunc = scipy.blackman
        fs = tb._fs

        # Plot the input signal on its own figure
        d = tb.snk_i.data()[Ns:Ne]
        spin_f = fig_in.add_subplot(2, 1, 1)

        X, freq = mlab.psd(d,
                           NFFT=fftlen,
                           noverlap=fftlen / 4,
                           Fs=fs,
                           window=lambda d: d * winfunc(fftlen),
                           scale_by_freq=True)
        X_in = 10.0 * scipy.log10(abs(fftpack.fftshift(X)))
        f_in = scipy.arange(-fs / 2.0, fs / 2.0, fs / float(X_in.size))
        pin_f = spin_f.plot(f_in, X_in, "b")
        spin_f.set_xlim([min(f_in), max(f_in) + 1])
        spin_f.set_ylim([-200.0, 50.0])

        spin_f.set_title("Input Signal", weight="bold")
        spin_f.set_xlabel("Frequency (Hz)")
        spin_f.set_ylabel("Power (dBW)")

        Ts = 1.0 / fs
        Tmax = len(d) * Ts

        t_in = scipy.arange(0, Tmax, Ts)
        x_in = scipy.array(d)
        spin_t = fig_in.add_subplot(2, 1, 2)
        pin_t = spin_t.plot(t_in, x_in.real, "b")
        pin_t = spin_t.plot(t_in, x_in.imag, "r")

        spin_t.set_xlabel("Time (s)")
        spin_t.set_ylabel("Amplitude")

        Ncols = int(scipy.floor(scipy.sqrt(tb._M)))
        Nrows = int(scipy.floor(tb._M / Ncols))
        if (tb._M % Ncols != 0):
            Nrows += 1

        # Plot each of the channels outputs. Frequencies on Figure 2 and
        # time signals on Figure 3
        fs_o = tb._fs / tb._M
        Ts_o = 1.0 / fs_o
        Tmax_o = len(d) * Ts_o
        for i in xrange(len(tb.snks)):
            # remove issues with the transients at the beginning
            # also remove some corruption at the end of the stream
            #    this is a bug, probably due to the corner cases
            d = tb.snks[i].data()[Ns:Ne]

            sp1_f = fig1.add_subplot(Nrows, Ncols, 1 + i)
            X, freq = mlab.psd(d,
                               NFFT=fftlen,
                               noverlap=fftlen / 4,
                               Fs=fs_o,
                               window=lambda d: d * winfunc(fftlen),
                               scale_by_freq=True)
            X_o = 10.0 * scipy.log10(abs(X))
            f_o = freq
            p2_f = sp1_f.plot(f_o, X_o, "b")
            sp1_f.set_xlim([min(f_o), max(f_o) + 1])
            sp1_f.set_ylim([-200.0, 50.0])

            sp1_f.set_title(("Channel %d" % i), weight="bold")
            sp1_f.set_xlabel("Frequency (Hz)")
            sp1_f.set_ylabel("Power (dBW)")

            x_o = scipy.array(d)
            t_o = scipy.arange(0, Tmax_o, Ts_o)
            sp2_o = fig2.add_subplot(Nrows, Ncols, 1 + i)
            p2_o = sp2_o.plot(t_o, x_o.real, "b")
            p2_o = sp2_o.plot(t_o, x_o.imag, "r")
            sp2_o.set_xlim([min(t_o), max(t_o) + 1])
            sp2_o.set_ylim([-2, 2])

            sp2_o.set_title(("Channel %d" % i), weight="bold")
            sp2_o.set_xlabel("Time (s)")
            sp2_o.set_ylabel("Amplitude")

            sp3 = fig3.add_subplot(1, 1, 1)
            p3 = sp3.plot(t_o, x_o.real)
            sp3.set_xlim([min(t_o), max(t_o) + 1])
            sp3.set_ylim([-2, 2])

        sp3.set_title("All Channels")
        sp3.set_xlabel("Time (s)")
        sp3.set_ylabel("Amplitude")

        pylab.show()
예제 #50
0
from smst.utils import audio

(fs, x) = audio.read_wav('../../../sounds/soprano-E4.wav')
N = 1024
x1 = np.blackman(N) * x[40000:40000 + N]

plt.figure(1, figsize=(9.5, 6))
X = np.array([])
x2 = np.zeros(N)

plt.subplot(4, 1, 1)
plt.title('x (soprano-E4.wav)')
plt.plot(x1, lw=1.5)
plt.axis([0, N, min(x1), max(x1)])

X = fft(fftshift(x1))
mX = 20 * np.log10(np.abs(X[0:N / 2]))
pX = np.angle(X[0:N / 2])

plt.subplot(4, 1, 2)
plt.title('mX = magnitude spectrum')
plt.plot(mX, 'r', lw=1.5)
plt.axis([0, N / 2, min(mX), max(mX)])

plt.subplot(4, 1, 3)
plt.title('pX1 = phase spectrum')
plt.plot(pX, 'c', lw=1.5)
plt.axis([0, N / 2, min(pX), max(pX)])

pX1 = np.unwrap(pX)
plt.subplot(4, 1, 4)
예제 #51
0
	def __init__(self, gridDIM, amplitude, dt, timeSteps, skipFrames = 1,frameSaveMode='Density'):

		X_amplitude,Y_amplitude = amplitude
		X_gridDIM, Y_gridDIM    = gridDIM
		

		self.dX = 2.*X_amplitude/np.float(X_gridDIM)
		self.dY = 2.*Y_amplitude/np.float(Y_gridDIM)
	
		self.X_amplitude = X_amplitude
		self.Y_amplitude = Y_amplitude

		self.X_gridDIM = X_gridDIM
		self.Y_gridDIM = Y_gridDIM
		
		self.min_X = -X_amplitude
		self.min_Y = -Y_amplitude
		
		self.timeSteps = timeSteps
		self.skipFrames = skipFrames
		self.frameSaveMode = frameSaveMode

		rangeX  = np.linspace(-X_amplitude, X_amplitude - self.dX,  X_gridDIM )
		rangeY  = np.linspace(-Y_amplitude, Y_amplitude - self.dY,  Y_gridDIM )

		self.X = fftpack.fftshift(rangeX)[np.newaxis, :  ]
		self.Y = fftpack.fftshift(rangeY)[:, np.newaxis  ]

		self.X_GPU     = gpuarray.to_gpu( np.ascontiguousarray( self.X + 0.*self.Y, dtype = np.complex128)     )
		self.Y_GPU     = gpuarray.to_gpu( np.ascontiguousarray( self.Y + 0.*self.X, dtype = np.complex128)     )

		# min_Px = np.pi*self.X_gridDIM/(2*self.min_X)

		Px_amplitude = np.pi/self.dX
		self.dPx     = 2*Px_amplitude/self.X_gridDIM
		Px_range     = np.linspace( -Px_amplitude, Px_amplitude - self.dPx, self.X_gridDIM )

		Py_amplitude = np.pi/self.dY
		self.dPy     = 2*Py_amplitude/self.Y_gridDIM
		Py_range     = np.linspace( -Py_amplitude, Py_amplitude - self.dPy, self.Y_gridDIM )

		self.Px = fftpack.fftshift(Px_range)[np.newaxis,:]
		self.Py = fftpack.fftshift(Py_range)[:,np.newaxis]

		self.Px_GPU = gpuarray.to_gpu( np.ascontiguousarray( self.Px + 0.*self.Py, dtype = np.complex128)     )
		self.Py_GPU = gpuarray.to_gpu( np.ascontiguousarray( self.Py + 0.*self.Px, dtype = np.complex128)     )

		self.dt = dt
		

		#................ Strings: mass,c,dt must be defined in children class.................... 
	
		self.CUDA_constants_essential  = '__constant__ double mass=%f; '%self.mass
		self.CUDA_constants_essential += '__constant__ double c=%f;    '%self.c
		self.CUDA_constants_essential += '__constant__ double dt=%f;   '%self.dt
		self.CUDA_constants_essential += '__constant__ double dX=%f;   '%self.dX
		self.CUDA_constants_essential += '__constant__ double dY=%f;   '%self.dY
 
		self.CUDA_constants_essential += '__constant__ double dPx=%f;   '%self.dPx
		self.CUDA_constants_essential += '__constant__ double dPy=%f;   '%self.dPy

		self.CUDA_constants = 	self.CUDA_constants_essential #+ self.CUDA_constants_additional	

		#................ CUDA Kernels ...........................................................
				

		self.DiracPropagatorK = SourceModule(BaseCUDAsource_K%self.CUDA_constants,arch="sm_20").get_function( "Kernel" )

		self.DiracPropagatorA  =  \
		SourceModule( DiracPropagatorA_source%(
					self.CUDA_constants,
					self.Potential_0_String, 
 					self.Potential_1_String, 
					self.Potential_2_String, 
					self.Potential_3_String),arch="sm_20").get_function( "DiracPropagatorA_Kernel" )

		self.Potential_0_Average_Function = \
			SourceModule( Potential_0_Average_source%(
			self.CUDA_constants,self.Potential_0_String) ).get_function("Kernel" )


		self.DiracAbsorbBoundary_xy  =  \
		SourceModule(BaseCUDAsource_AbsorbBoundary_xy,arch="sm_20").get_function( "AbsorbBoundary_Kernel" )

		#...........................FFT PLAN.................................................

		self.plan_Z2Z_2D = cuda_fft.Plan_Z2Z(  (self.X_gridDIM,self.Y_gridDIM)  )
import numpy as np
import matplotlib.pylab as plt
from scipy.fftpack import fft, fftfreq, fft2, ifft2, fftshift, ifftshift
from matplotlib.colors import LogNorm
from scipy import ndimage

# Guarda la imagene en un arreglo

imagen = plt.imread('moonlanding.png')

# Encuentra la transformada de Fourier de las imagen

transformadaImagen = fft2(imagen)

transformadaShift = fftshift(transformadaImagen)

# Genera el plot de la transformada de fourier de las imagen

plt.figure()
plt.imshow(np.abs(transformadaShift), norm=LogNorm(vmin=5))
plt.colorbar()
plt.savefig("Transformada.pdf")

# Funcion que me devuelve el punto medio de la lista


def mitadPunto(transformadaImagen):

    x = np.shape(transformadaImagen)[0] // 2
reduces the spectral leakage, making the "real" frequency information more
visible in the plot of the frequency component of the FFT.
"""

import matplotlib.pyplot as plt
import numpy as np
from scipy.fftpack import fft2, fftshift
from skimage import img_as_float
from skimage.color import rgb2gray
from skimage.data import astronaut
from skimage.filters import window

image = img_as_float(rgb2gray(astronaut()))

wimage = image * window('hann', image.shape)

image_f = np.abs(fftshift(fft2(image)))
wimage_f = np.abs(fftshift(fft2(wimage)))

fig, axes = plt.subplots(2, 2, figsize=(8, 8))
ax = axes.ravel()
ax[0].set_title("Original image")
ax[0].imshow(image, cmap='gray')
ax[1].set_title("Windowed image")
ax[1].imshow(wimage, cmap='gray')
ax[2].set_title("Original FFT (frequency)")
ax[2].imshow(np.log(image_f), cmap='magma')
ax[3].set_title("Window + FFT (frequency)")
ax[3].imshow(np.log(wimage_f), cmap='magma')
plt.show()
예제 #54
0
y = signal.detrend(qqq)


alldays = DayLocator()              
months = MonthLocator()
month_formatter = DateFormatter("%b %Y")

fig = plt.figure()
ax = fig.add_subplot(211)

ax.xaxis.set_minor_locator(alldays)
ax.xaxis.set_major_locator(months)
ax.xaxis.set_major_formatter(month_formatter)

amps = np.abs(fftpack.fftshift(fftpack.rfft(y)))
amps[amps < amps.max()] = 0

def residuals(p, y, x):
   A,k,theta = p
   err = y-A * np.sin(2* np.pi* k * x + theta)

   return err

filtered = -fftpack.irfft(fftpack.ifftshift(amps))
N = len(qqq)
f = np.linspace(-N/2, N/2, N)
p0 = [filtered.max(), f[amps.argmax()]/N, np.pi/3]
plsq = optimize.leastsq(residuals, p0, args=(filtered, dates))
p = plsq[0]
print p
예제 #55
0
 def RGB(self):
     image = np.log10(0.1 + abs(self.image)).astype(float)
     image = fp.fftshift(image.copy())
     return image / image.max()  #Normalized between 0-1
예제 #56
0
def main():
    ### Parse commandline arguments
    parser = argparse.ArgumentParser(
        description=
        'Processes time domain data to perform frequency domain analysis')
    parser.add_argument('-p',
                        '--path',
                        metavar='path',
                        default="./data",
                        help='define path of input files')
    parser.add_argument('-f1',
                        '--filename1',
                        metavar='filename',
                        default="test",
                        help='set filename for test dump')
    parser.add_argument('-f2',
                        '--filename2',
                        metavar='filename',
                        default="bg",
                        help='set filename for background dump')
    parser.add_argument('-fs',
                        '--fsampling',
                        metavar='N',
                        type=float,
                        default=2e6,
                        help='set sampling frequency of input data')
    parser.add_argument('-n',
                        '--fftsize',
                        metavar='N',
                        type=int,
                        default=16383,
                        help='set FFT size')
    parser.add_argument('-na',
                        '--nall',
                        action='store_false',
                        help='disabilitates overall frequency plot')
    parser.add_argument('-s',
                        '--step',
                        action='store_true',
                        help='abilitates step by step frequency plot')
    parser.add_argument(
        '-d',
        '--diff',
        action='store_true',
        help=
        'performs difference between spectrum with board and spectrum without board'
    )
    parser.add_argument('-g',
                        '--spg',
                        action='store_true',
                        help='show spectrogram')
    parser.add_argument('-P',
                        '--peaks',
                        action='store_true',
                        help='abilitates peak search')
    parser.add_argument(
        '-t',
        '--Pth',
        metavar='dB',
        type=int,
        default=-90,
        help='set power threshold for peak search (in dB) - default: -90 ')
    parser.add_argument('-e',
                        '--epeaks',
                        action='store_true',
                        help='exports peak search, -P option must be selected')
    parser.add_argument('-fP',
                        '--fpeaks',
                        metavar='filename',
                        default="scan",
                        help='set filename for peak export (default: scan)')
    parser.add_argument('-w',
                        '--efft',
                        action='store_true',
                        help='exports data inside compressed .npz files')
    parser.add_argument('-l',
                        '--load',
                        action='store_true',
                        help='load data from compressed .npz files')
    parser.add_argument(
        '-fw',
        '--fftname',
        metavar='filename',
        default="fft_export",
        help='choose filename for FFT export/load (default: fft_export)')
    parser.add_argument(
        '-fg',
        '--spgname',
        metavar='filename',
        default="spg_export",
        help='choose filename for spectrogram export/load (default: spg_export)'
    )
    parser.add_argument('frequency',
                        metavar='f',
                        type=int,
                        nargs=2,
                        default=[26, 28],
                        help='frequency range')

    args = parser.parse_args()

    ### Options
    export_fft = args.efft
    load_fft = args.load
    diff = args.diff
    find_peaks = args.peaks
    export_peaks = args.epeaks
    plot_step = args.step
    plot_all = args.nall
    show_spectrogram = args.spg

    ### Parameters
    fmin = args.frequency[0]  #minimum center frequency in MHz (MIN:25)
    fmax = args.frequency[1]  #maximum center frequency in MHz (MAX: 1000)
    if fmax < fmin:
        print("Error: fmin larger than fmax")
        quit()
    path = args.path + "/"  #path of acquired data
    data_filename = args.filename1
    diff_filename = args.filename2  #difference filename
    Pth = args.Pth  #set power threshold in negative dB
    peaks_filename = args.fpeaks  #filename of peaks export
    fft_filename = args.fftname
    Fs = args.fsampling  #data sampling frequency
    dT = 1 / Fs  #sampling rate
    fft_size = args.fftsize  #FFT size
    spg_filename = args.spgname

    f = fftfreq(fft_size, d=dT)  #x-axis for FFT
    f = fftshift(f)
    peaks = peaks1 = peaks2 = []
    if (export_peaks):
        suffix = str(dt.datetime.now()).replace(" ", "_").replace(
            ":", "").replace("-", "")[:-7] + ".txt"
        scan = path + peaks_filename + "_" + suffix  #path of scan output
        scan1 = path + peaks_filename + "1_" + suffix  #path of scan output
        scan2 = path + peaks_filename + "2_" + suffix  #path of scan output
    else:
        scan = ""
        scan1 = ""
        scan2 = ""

    if (load_fft == False):
        for f0 in range(fmin, fmax + 1, int(Fs / 1e6)):
            #### the step is used to avoid repetitions (default Fs is 2e6) ####
            ### Open file 1
            data = ldcomplex(path + data_filename + str(f0) + ".dat")
            ### FFT spectrum, Welch average method
            if (diff):
                ### Open file 2
                data2 = ldcomplex(path + diff_filename + str(f0) + ".dat")
                ### Compute difference between averaged FFts
                _, P1 = welch(data, Fs, 'hanning', fft_size, None, None,
                              'constant', True, 'spectrum')
                _, P2 = welch(data2, Fs, 'hanning', fft_size, None, None,
                              'constant', True, 'spectrum')
                P1 = fftshift(P1)
                P2 = fftshift(P2)
                P = np.square(np.sqrt(P1) - np.sqrt(P2))
                if (show_spectrogram):
                    fsg, tsg, Sxx1 = spectrogram(data,
                                                 Fs,
                                                 scaling='spectrum',
                                                 nperseg=1024)
                    _, _, Sxx2 = spectrogram(data2,
                                             Fs,
                                             scaling='spectrum',
                                             nperseg=1024)
                    Sxx = np.square(np.sqrt(Sxx1) - np.sqrt(Sxx2))
            else:
                _, P = welch(data, Fs, 'hanning', fft_size, None, None,
                             'constant', True, 'spectrum')
                P = fftshift(P)
                if (show_spectrogram):
                    fsg, tsg, Sxx = spectrogram(data,
                                                Fs,
                                                scaling='spectrum',
                                                nperseg=1024)
            if (plot_all or export_fft or export_peaks):
                ## APPEND DATA FOR GLOBAL PLOT
                if f0 == fmin:
                    f_global = f / 1e6 + f0
                    P_global = P
                    if (show_spectrogram):
                        fsg_global = fftshift(fsg / 1e6 + f0)
                        Sxx_global = fftshift(Sxx)
                    if (diff):
                        P1_global = P1
                        P2_global = P2
                        if (show_spectrogram):
                            Sxx1_global = fftshift(Sxx1)
                            Sxx2_global = fftshift(Sxx2)
                else:
                    f_global = np.append(f_global, f / 1e6 + f0)
                    P_global = np.append(P_global, P)
                    if (show_spectrogram):
                        fsg_global = np.append(fsg_global,
                                               fftshift(fsg / 1e6 + f0))
                        Sxx_global = np.concatenate(
                            (Sxx_global, fftshift(Sxx)), axis=0)
                    if (diff):
                        P1_global = np.append(P1_global, P1)
                        P2_global = np.append(P2_global, P2)
                        if (show_spectrogram):
                            Sxx1_global = np.concatenate(
                                (Sxx1_global, fftshift(Sxx1)), axis=0)
                            Sxx2_global = np.concatenate(
                                (Sxx2_global, fftshift(Sxx2)), axis=0)
            ### PLOT (f0)
            if (plot_step):
                f1 = plt.figure(1)
                if (diff):
                    plt.subplots_adjust(left=0.12,
                                        bottom=0.08,
                                        right=0.95,
                                        top=0.93,
                                        wspace=0.28,
                                        hspace=0.34)
                    plt.subplot(2, 2, 1)
                    if (find_peaks):
                        peaks1 = peakscannerdb(P1, Pth, export=False)
                        peaks2 = peakscannerdb(P2, Pth, export=False)
                    ldplotdb(f / 1e6 + f0, P1, f0, "1 ", peaks1)
                    plt.subplot(2, 2, 2)
                    ldplotdb(f / 1e6 + f0, P2, f0, "2 ", peaks2)
                    plt.subplot(2, 1, 2)
                if (find_peaks):
                    peaks = peakscannerdb(P, Pth, export=False)
                ldplotdb(f / 1e6 + f0, P, f0, "", peaks)
                plt.ion()  #interactive plot
                plt.show()
                if (show_spectrogram):
                    f2 = plt.figure(2)
                    if (diff):
                        plt.subplots_adjust(left=0.12,
                                            bottom=0.08,
                                            right=0.95,
                                            top=0.93,
                                            wspace=0.28,
                                            hspace=0.34)
                        plt.subplot(2, 2, 1)
                        ldmesh(tsg, fftshift(fsg / 1e6 + f0), fftshift(Sxx1),
                               f0, "1 ")
                        plt.subplot(2, 2, 2)
                        ldmesh(tsg, fftshift(fsg / 1e6 + f0), fftshift(Sxx2),
                               f0, "2 ")
                        plt.subplot(2, 1, 2)
                    ldmesh(tsg, fftshift(fsg / 1e6 + f0), fftshift(Sxx), f0)
                    plt.show()
                raw_input("Press any key to continue...")
                plt.close(f1)
                if (show_spectrogram):
                    plt.close(f2)
    else:
        fft_dict = np.load(path + fft_filename + ".npz")
        f_global = fft_dict['f']
        P_global = fft_dict['P']
        if (show_spectrogram):
            spg_dict = np.load(path + spg_filename + ".npz")
            tsg = spg_dict['tsg']
            fsg_global = spg_dict['fsg']
            Sxx_global = spg_dict['Sxx']
        if (diff):
            fft_dict = np.load(path + fft_filename + "_P1" + ".npz")
            P1_global = fft_dict['P']
            fft_dict = np.load(path + fft_filename + "_P2" + ".npz")
            P2_global = fft_dict['P']
            if (show_spectrogram):
                spg_dict = np.load(path + spg_filename + "_S1" + ".npz")
                Sxx1_global = spg_dict['Sxx']
                spg_dict = np.load(path + spg_filename + "_S2" + ".npz")
                Sxx2_global = spg_dict['Sxx']

    if ((plot_all and find_peaks) or export_peaks):
        peaks = peakscannerdb(P_global, Pth, export_peaks, f_global, scan)
        if (diff):
            peaks1 = peakscannerdb(P1_global, Pth, export_peaks, f_global,
                                   scan1)
            peaks2 = peakscannerdb(P2_global, Pth, export_peaks, f_global,
                                   scan2)

    if (export_fft and not (load_fft)):
        np.savez_compressed(path + fft_filename, f=f_global, P=P_global)
        if (show_spectrogram):
            np.savez_compressed(path + spg_filename,
                                tsg=tsg,
                                fsg=fsg_global,
                                Sxx=Sxx_global)
        if (diff):
            np.savez_compressed(path + fft_filename + "_P1",
                                f=f_global,
                                P=P1_global)
            np.savez_compressed(path + fft_filename + "_P2",
                                f=f_global,
                                P=P2_global)
            if (show_spectrogram):
                np.savez_compressed(path + spg_filename + "_S1",
                                    tsg=tsg,
                                    fsg=fsg_global,
                                    Sxx=Sxx1_global)
                np.savez_compressed(path + spg_filename + "_S2",
                                    tsg=tsg,
                                    fsg=fsg_global,
                                    Sxx=Sxx2_global)

    ### PLOT (from fmin-Fs/2 to fmax+Fs/2)
    if (plot_all):
        f1 = plt.figure(1)
        if (diff):
            plt.subplots_adjust(left=0.12,
                                bottom=0.08,
                                right=0.95,
                                top=0.93,
                                wspace=0.28,
                                hspace=0.34)
            plt.subplot(2, 2, 1)
            ldplotdb(f_global, P1_global, (fmax + fmin) / 2, "1 ", peaks1)
            plt.subplot(2, 2, 2)
            ldplotdb(f_global, P2_global, (fmax + fmin) / 2, "2 ", peaks2)
            plt.subplot(2, 1, 2)
        ldplotdb(f_global, P_global, (fmax + fmin) / 2, "", peaks)
        plt.ion()  #interactive plot
        plt.show()
        if (show_spectrogram):
            f2 = plt.figure(2)
            if (diff):
                plt.subplots_adjust(left=0.12,
                                    bottom=0.08,
                                    right=0.95,
                                    top=0.93,
                                    wspace=0.28,
                                    hspace=0.34)
                plt.subplot(2, 2, 1)
                ldmesh(tsg, fsg_global, Sxx1_global, (fmax + fmin) / 2, "1 ")
                plt.subplot(2, 2, 2)
                ldmesh(tsg, fsg_global, Sxx2_global, (fmax + fmin) / 2, "2 ")
                plt.subplot(2, 1, 2)
            ldmesh(tsg, fsg_global, Sxx_global, (fmax + fmin) / 2)
            plt.show()
        raw_input("Press any key to close...")
        plt.close(f1)
        if (show_spectrogram):
            plt.close(f2)
예제 #57
0
    def applyFilter(
        self,
        parameter_ratio=0.2,
        mode='highpass',
        shape="radial",
        customFilter=None,
        isSpatial=True
    ):  #radius_ratio is ratio of radius of filter to smallest side of image
        """Applies a mask of passed shape with parameter of shape(side of square or radius of circle)
            This can be bypassed by passing a customFilter that is taken in fourier domain if it's a spatial filter and multiplied
            If the passed customFilter is an fft domain filter of class iImageFFT, it is directly multiplied
            """
        if customFilter is None:

            if not shape in ['radial', 'square']:
                shape = 'radial'  #default radial shape forced

            image = fp.fftshift(self.image.copy())
            parameter = parameter_ratio * min(
                self.image.shape
            ) / 2  #parameter ratio times min of shape of 2d V Channel
            x0, y0 = np.asarray(image.shape) / 2  #center of image
            radius = parameter
            side = parameter  #used in two types of filter masks

            def is_inside(i, j):  #Check if i,j is inside the filter radius
                if shape == 'square':
                    #return true if pixel (i,j) is inside the square mask of side `side`
                    if ((i > x0 - side and i < x0 + side)
                            and (j > y0 - side and j < y0 + side)):
                        return True
                    else:
                        return False
                elif shape == 'radial':
                    if ((x0 - i)**2 + (y0 - j)**2)**0.5 < radius:
                        return True  #return true if point i,j is inside the radial makk
                    else:
                        return False

            if mode == 'highpass':

                def inner(i, j):
                    return 0

                def outer(i, j):
                    return image[i, j]
            elif mode == 'lowpass':

                def inner(i, j):
                    return image[i, j]

                def outer(i, j):
                    return 0
            else:

                raise NotImplementedError  #other modes of filters are not implemented

            image = np.asarray([[
                inner(i, j) if is_inside(i, j) else outer(i, j)
                for j in range(image.shape[1])
            ] for i in range(image.shape[0])])
            self.image = fp.ifftshift(image)
            return self
        else:  #if custom filter is passed
            if isinstance(customFilter, iImage):
                filter = (customFilter.pad(
                    target=self).fft().image.astype('float'))
            elif isinstance(customFilter, np.ndarray) and isSpatial:
                filter = (iImage(customFilter).pad(
                    target=self.image).fft().image.astype('float'))
            elif isinstance(customFilter, iImageFFT):
                assert (customFilter.image.shape == self.image.shape
                        ), "passed customFilter of type iImageFFT \
                                                                          should be of shape of the target image or \
                                                                          pass spatial filter of type np.ndarray or iImage so \
                                                                          it can be padded to required image shape automatically"

                # filter=customFilter.image.astype('float')
                filter = customFilter.image

            else:
                raise TypeError(
                    "filter can be spatial 2d numpy.ndarray or iImageFFT object of same shape as target iImageFFT object only"
                )
            # filter=filter/filter.max() #normalize the filter
            filter = abs(filter)  #Taking absolute values of filter
            self.image *= filter  #multiply the image with the fft filter
            return self
# Plot the window and its frequency response:

from scipy import signal
from scipy.fftpack import fft, fftshift
import matplotlib.pyplot as plt

window = signal.triang(51)
plt.plot(window)
plt.title("Triangular window")
plt.ylabel("Amplitude")
plt.xlabel("Sample")

plt.figure()
A = fft(window, 2048) / (len(window) / 2.0)
freq = np.linspace(-0.5, 0.5, len(A))
response = np.abs(fftshift(A / abs(A).max()))
response = 20 * np.log10(np.maximum(response, 1e-10))
plt.plot(freq, response)
plt.axis([-0.5, 0.5, -120, 0])
plt.title("Frequency response of the triangular window")
plt.ylabel("Normalized magnitude [dB]")
plt.xlabel("Normalized frequency [cycles per sample]")
예제 #59
0
f1 = fs / 4
f2 = f1 + (10 * fs / N)

a2dB = -250
a2 = 10**(a2dB / 20)

x1 = np.sin(2 * np.pi * f1 * tt)
x2 = a2 * np.sin(2 * np.pi * f2 * tt)

x = x1 + x2

xw = np.transpose(np.vstack([x * this_win for this_win in ventanas]))

X = fft(xw, axis=0)
modX = np.abs(fftshift(X)) * 2 / N
center = int(np.floor(N / 2))
modX = modX[center:N]
modX = 20 * np.log10(modX)
freq = np.linspace(0, 0.5, len(modX))
plt.figure("Modulo bitonal", figsize=(10, 10))
plt.suptitle('Mediciones para ejercicio 2b (a2=-250dB y f2 = f1 + (10*fs/N))',
             fontsize=20)
for ii in range(V):
    plt.subplot(3, 2, ii + 1)
    plt.tight_layout(pad=2, w_pad=0.5, h_pad=5)
    plt.plot(freq, modX[:, ii], label=ventanas_names[ii])
    plt.title(ventanas_names[ii], fontsize=20)
    plt.xlim(0.2, 0.3)
    plt.xlabel("Frecuencia normalizada", fontsize=20)
    plt.ylabel("Amplitud en dB", fontsize=20)
예제 #60
0
              kind='quadratic')
Fc = interp1d(datos_incompletos[:, 0], datos_incompletos[:, 1], kind='cubic')

# datos basicos de la senal
periodo = datos_senal[1, 0] - datos_senal[0, 0]
frecuencia = 1 / periodo
n = len(datos_senal[:, 0])  # numero de datos
frecuencias = np.linspace(-frecuencia / 2, frecuencia / 2,
                          n)  # vector de frecuencias

# crear arreglos con todos los valores de k y n
kk, nn = np.meshgrid(np.arange(n), np.arange(n))
theta = -2 * np.pi * kk * nn / n  # Theta es lo que va en la exponencial
transformada = np.sum(datos_senal[:, 1] * np.exp(1j * theta),
                      1)  # hacer las sumas de la transformada
transformada = fftshift(
    transformada)  # rotar el arreglo para que coincida con las frecuencias

print(
    "Frecuencias calculadas con codigo propio teniendo en cuenta la resolucion de frecuencia y al frecuencia de Nyquist"
)

fig, ax = plt.subplots(figsize=(10, 6))
ax.plot(datos_senal[:, 0], datos_senal[:, 1])
ax.set_xlabel('t')
plt.grid()
fig.savefig('CaceresAlejandra_signal.pdf', type='pdf')

fig, ax = plt.subplots(figsize=(10, 6))
ax.plot(frecuencias, np.abs(transformada))
ax.set_yscale('log')
ax.set_xlim([-3000, 3000])