def fresnelSingleTransformFW(self,d) : i2 = Intensity2D(self.nx,self.startx,self.endx, self.ny,self.starty,self.endy, self.wl) u1p = self.i*pl.exp(-1j*pl.pi/(d*self.wl)*(self.xgrid**2+self.ygrid**2)) ftu1p = pl.fftshift(pl.fft2(pl.fftshift(u1p))) i2.i = ftu1p*1j/(d*self.wl)*pl.exp(-1j*pl.pi/(d*self.wl)*(self.xgrid**2+self.ygrid**2)) return i2
def fresnelSingleTransformFW(self, d): i2 = Intensity2D(self.nx, self.startx, self.endx, self.ny, self.starty, self.endy, self.wl) u1p = self.i * pl.exp(-1j * pl.pi / (d * self.wl) * (self.xgrid**2 + self.ygrid**2)) ftu1p = pl.fftshift(pl.fft2(pl.fftshift(u1p))) i2.i = ftu1p * 1j / (d * self.wl) * pl.exp( -1j * pl.pi / (d * self.wl) * (self.xgrid**2 + self.ygrid**2)) return i2
def frc(image): from PYME.Analysis import binAvg import numpy as np import pylab voxelsize = image.voxelsize shape = image.data.shape[0:2] hwin = np.sqrt(np.outer(np.hanning(shape[0]), np.hanning(shape[1]))) #assume we have exactly 2 channels #FIXME - add a selector #grab image data imA = hwin * image.data[:, :, :, 0].squeeze() imB = hwin * image.data[:, :, :, 1].squeeze() X, Y = np.mgrid[0:float(imA.shape[0]), 0:float(imA.shape[1])] X = X / X.shape[0] Y = Y / X.shape[1] X = X - .5 Y = Y - .5 R = np.sqrt(X**2 + Y**2) H1 = pylab.fft2(imA) H2 = pylab.fft2(imB) ringwidth = 1 # in pixels rB = np.linspace(0, 0.5, 0.5 * imA.shape[0] / ringwidth) bn, bm, bs = binSum(R, pylab.fftshift(H1 * H2.conjugate()), rB) bn1, bm1, bs1 = binSum(R, pylab.fftshift(abs(H1 * H1.conjugate())), rB) bn2, bm2, bs2 = binSum(R, pylab.fftshift(abs(H2 * H2.conjugate())), rB) bmr = np.real(bm) pylab.figure() ax = pylab.gca() freqpnm = rB / voxelsize[0] ax.plot(freqpnm[:-1], bmr / np.sqrt(bm1 * bm2)) ax.plot(freqpnm[:-1], 2. / np.sqrt(bn / 2)) ax.plot(freqpnm[:-1], 0 * bmr + 1.0 / 7) ax.plot(freqpnm[:-1], 0 * bmr, '--') xt = np.array([10., 15, 20, 30, 50, 80, 100, 150]) rt = 1.0 / xt pylab.xticks(rt[::-1], ['%d' % xi for xi in xt[::-1]]) pylab.show() return H1, H2, R, bmr / np.sqrt(bm1 * bm2), bn, bm, bm1, bm2, rB
def fresnelSingleTransformVW(self,d) : # compute new window x2 = self.nx*pl.absolute(d)*self.wl/(self.endx-self.startx) y2 = self.ny*pl.absolute(d)*self.wl/(self.endy-self.starty) # create new intensity object i2 = Intensity2D(self.nx,-x2/2,x2/2, self.ny,-y2/2,y2/2, self.wl) # compute intensity u1p = self.i*pl.exp(-1j*pl.pi/(d*self.wl)*(self.xgrid**2+self.ygrid**2)) ftu1p = pl.fftshift(pl.fft2(pl.fftshift(u1p))) i2.i = ftu1p*1j/(d*i2.wl)*pl.exp(-1j*pl.pi/(d*i2.wl)*(i2.xgrid**2+i2.ygrid**2)) return i2
def Fraunhofer(i, z) : print "Propagation:Fraunhofer" ft = pl.fftshift(pl.fftn(pl.fftshift(i.i))) dx = i.wl*z/(i.nx*i.dx) dy = i.wl*z/(i.ny*i.dy) po = pl.exp(1j*2*pl.pi/i.wl*i.dx*i.dx)/(1j*i.wl*z) p = pl.arange(0,i.nx)-(i.nx+0.5)/2.0 q = pl.arange(0,i.ny)-(i.ny+0.5)/2.0 [pp,qq] = pl.meshgrid(p,q) pm = pl.exp(1j*pl.pi/(i.wl*z)*((pp*dx)**2+(qq*dy)**2)) i2 = Intensity.Intensity2D(i.nx,-i.nx*dx/2,i.nx*dy/2,i.ny,-i.ny*dy/2,i.ny*dy/2) i2.i = po*pm*ft return i2 print "Propagation:Fraunhofer>",dx,dy,i.nx*dx,i.ny*dy
def compute_response(self, **kargs): """Compute the window data frequency response :param norm: True by default. normalised the frequency data. :param int NFFT: total length of the final data sets( 2048 by default. if less than data length, then NFFT is set to the data length*2). The response is stored in :attr:`response`. .. note:: Units are dB (20 log10) since we plot the frequency response) """ from pylab import fft, fftshift, log10 norm = kargs.get('norm', self.norm) # do some padding. Default is max(2048, data.len*2) NFFT = kargs.get('NFFT', 2048) if NFFT < len(self.data): NFFT = self.data.size * 2 # compute the fft modulus A = fft(self.data, NFFT) mag = abs(fftshift(A)) # do we want to normalise the data if norm is True: mag = mag / max(mag) response = 20. * log10(mag) # factor 20 we are looking at the response # not the powe #response = clip(response,mindB,100) self.__response = response
def fresnelConvolutionTransform(self, d): # make intensity distribution i2 = Intensity2D(self.nx, self.startx, self.endx, self.ny, self.starty, self.endy, self.wl) # FT on inital distribution u1ft = pl.fft2(self.i) # 2d convolution kernel k = 2 * pl.pi / i2.wl # make spatial frequency matrix maxsfx = 2 * pl.pi / self.dx maxsfy = 2 * pl.pi / self.dy dsfx = 2 * maxsfx / (self.nx) dsfy = 2 * maxsfy / (self.ny) self.sfx = pl.arange(-maxsfx / 2, maxsfx / 2 + 1e-15, dsfx / 2) self.sfy = pl.arange(-maxsfy / 2, maxsfy / 2 + 1e-15, dsfy / 2) [self.sfxgrid, self.sfygrid] = pl.fftshift(pl.meshgrid(self.sfx, self.sfy)) # make convolution kernel kern = pl.exp(1j * d * (self.sfxgrid**2 + self.sfygrid**2) / (2 * k)) # apply convolution kernel and invert i2.i = pl.ifft2(kern * u1ft) return i2
def fresnelSingleTransformVW(self, d): # compute new window x2 = self.nx * pl.absolute(d) * self.wl / (self.endx - self.startx) y2 = self.ny * pl.absolute(d) * self.wl / (self.endy - self.starty) # create new intensity object i2 = Intensity2D(self.nx, -x2 / 2, x2 / 2, self.ny, -y2 / 2, y2 / 2, self.wl) # compute intensity u1p = self.i * pl.exp(-1j * pl.pi / (d * self.wl) * (self.xgrid**2 + self.ygrid**2)) ftu1p = pl.fftshift(pl.fft2(pl.fftshift(u1p))) i2.i = ftu1p * 1j / (d * i2.wl) * pl.exp(-1j * pl.pi / (d * i2.wl) * (i2.xgrid**2 + i2.ygrid**2)) return i2
def Fraunhofer(i, z): print "Propagation:Fraunhofer" ft = pl.fftshift(pl.fftn(pl.fftshift(i.i))) dx = i.wl * z / (i.nx * i.dx) dy = i.wl * z / (i.ny * i.dy) po = pl.exp(1j * 2 * pl.pi / i.wl * i.dx * i.dx) / (1j * i.wl * z) p = pl.arange(0, i.nx) - (i.nx + 0.5) / 2.0 q = pl.arange(0, i.ny) - (i.ny + 0.5) / 2.0 [pp, qq] = pl.meshgrid(p, q) pm = pl.exp(1j * pl.pi / (i.wl * z) * ((pp * dx)**2 + (qq * dy)**2)) i2 = Intensity.Intensity2D(i.nx, -i.nx * dx / 2, i.nx * dy / 2, i.ny, -i.ny * dy / 2, i.ny * dy / 2) i2.i = po * pm * ft return i2 print "Propagation:Fraunhofer>", dx, dy, i.nx * dx, i.ny * dy
def fresnelConvolutionTransform(self,d) : # make intensity distribution i2 = Intensity2D(self.nx,self.startx,self.endx, self.ny,self.starty,self.endy, self.wl) # FT on inital distribution u1ft = pl.fft2(self.i) # 2d convolution kernel k = 2*pl.pi/i2.wl # make spatial frequency matrix maxsfx = 2*pl.pi/self.dx maxsfy = 2*pl.pi/self.dy dsfx = 2*maxsfx/(self.nx) dsfy = 2*maxsfy/(self.ny) self.sfx = pl.arange(-maxsfx/2,maxsfx/2+1e-15,dsfx/2) self.sfy = pl.arange(-maxsfy/2,maxsfy/2+1e-15,dsfy/2) [self.sfxgrid, self.sfygrid] = pl.fftshift(pl.meshgrid(self.sfx,self.sfy)) # make convolution kernel kern = pl.exp(1j*d*(self.sfxgrid**2+self.sfygrid**2)/(2*k)) # apply convolution kernel and invert i2.i = pl.ifft2(kern*u1ft) return i2
def _gen_bead_pupil(X, Y, beadsize): r2 = X*X + Y*Y dx = X[1, 0] - X[0, 0] bead_proj = np.sqrt(np.maximum(beadsize*beadsize - (r2 - dx*dx), 0)) return abs(fftshift(fftn(bead_proj)))
def angularSpectrum(self, d): # make intensity distribution i2 = Intensity2D(self.nx, self.startx, self.endx, self.ny, self.starty, self.endy, self.wl) # Angular spectrum (FT of input wavefield) a = pl.fft2(pl.fftshift(self.i)) print a # 2d convolution kernel k = 2 * pl.pi / self.wl print k # make spatial frequency matrix maxsfx = 2 * pl.pi / self.dx maxsfy = 2 * pl.pi / self.dy print maxsfx, maxsfy dsfx = 2 * maxsfx / (self.nx) dsfy = 2 * maxsfy / (self.ny) self.sfx = pl.arange(-maxsfx / 2, maxsfx / 2 + 1e-15, dsfx / 2) self.sfy = pl.arange(-maxsfy / 2, maxsfy / 2 + 1e-15, dsfy / 2) print self.sfx print self.sfy [self.sfxgrid, self.sfygrid] = pl.meshgrid(self.sfx, self.sfy) # angular spectrum propagation kernel aspk = pl.fftshift( pl.exp(1j * d * pl.sqrt(k**2 - (self.sfxgrid**2 + self.sfygrid**2)))) print "Angular spectrum propagation kernel" print aspk # apply angular spectrum propagation kernel and inverse Fourier transform i2.i = pl.fftshift(pl.ifft2(aspk * a)) print i2.i return i2
def angularSpectrum(self,d) : # make intensity distribution i2 = Intensity2D(self.nx,self.startx,self.endx, self.ny,self.starty,self.endy, self.wl) # Angular spectrum (FT of input wavefield) a = pl.fft2(pl.fftshift(self.i)) print a # 2d convolution kernel k = 2*pl.pi/self.wl print k # make spatial frequency matrix maxsfx = 2*pl.pi/self.dx maxsfy = 2*pl.pi/self.dy print maxsfx,maxsfy dsfx = 2*maxsfx/(self.nx) dsfy = 2*maxsfy/(self.ny) self.sfx = pl.arange(-maxsfx/2,maxsfx/2+1e-15,dsfx/2) self.sfy = pl.arange(-maxsfy/2,maxsfy/2+1e-15,dsfy/2) print self.sfx print self.sfy [self.sfxgrid, self.sfygrid] = pl.meshgrid(self.sfx,self.sfy) # angular spectrum propagation kernel aspk = pl.fftshift(pl.exp(1j*d*pl.sqrt(k**2 -(self.sfxgrid**2 + self.sfygrid**2)))) print "Angular spectrum propagation kernel" print aspk # apply angular spectrum propagation kernel and inverse Fourier transform i2.i = pl.fftshift(pl.ifft2(aspk*a)) print i2.i return i2
def OnColoc(self, event): from PYME.Analysis import binAvg voxelsize = self.image.voxelsize #assume we have exactly 2 channels #FIXME - add a selector #grab image data imA = self.image.data[:,:,:,0].squeeze() imB = self.image.data[:,:,:,1].squeeze() X, Y = np.mgrid[0:float(imA.shape[0]), 0:float(imA.shape[1])] X = X/X.shape[0] Y = Y/X.shape[1] X = X - .5 Y = Y - .5 R = np.sqrt(X**2 + Y**2) H1 = pylab.fftn(imA) H2 = pylab.fftn(imB) rB = np.linspace(0,R.max()) bn, bm, bs = binAvg.binAvg(R, pylab.fftshift(abs(H1*H2)), rB) bn1, bm1, bs1 = binAvg.binAvg(R, pylab.fftshift(abs(H1*H1)), rB) bn2, bm2, bs2 = binAvg.binAvg(R, pylab.fftshift(abs(H2*H2)), rB) pylab.figure() ax = pylab.gca() ax.plot(rB[:-1], bm/np.sqrt(bm1*bm2)) ax.plot(rB[:-1], 2./np.sqrt(bn/2)) xt = np.array([10., 15, 20, 30, 50, 80, 100, 150]) rt = voxelsize[0]/xt pylab.xticks(rt[::-1],['%d' % xi for xi in xt[::-1]]) pylab.show()
def abscorrel(a, b): from scipy.fftpack import fftn, ifftn from pylab import fftshift, ifftshift import numpy as np F0 = fftn(a) Fi = ifftn(b) corr = abs(fftshift(ifftn(F0 * Fi))) return corr
def plot_image(in_file, function, plot_mask, plot_log, plot_shifted): # try: # #img = spimage.sp_image_read(in_file,0) image, mask = sphelper.import_spimage(in_file, ['image', 'mask']) # except: # raise TypeError("Error: %s is not a readable .h5 file\n" % in_file) plot_flags = ['abs','mask','phase','real','imag'] shift_flags = ['shift'] log_flags = ['log'] plot_flag = 0 shift_flag = 0 log_flag = 0 colormap = "jet" if function == "phase": colormap = "hsv" if plot_shifted: #img = spimage.sp_image_shift(img) image = pylab.fftshift(image) mask = pylab.fftshift(mask) def no_log(x): return x if plot_log: log_function = pylab.log else: log_function = no_log if plot_mask: plot_input = mask else: plot_input = image function_dict = {"abs" : abs, "phase" : pylab.angle, "real" : pylab.real, "imag" : pylab.imag} pylab.imshow(log_function(function_dict[function](plot_input)), cmap=colormap, origin="lower", interpolation="nearest") pylab.show()
def FourierDerivative(f): """ this derivatie just works for periodic 2*pi multiple series have to figure out how to make that work for any function """ N = np.size(f) n = np.arange(0,N) # df discrete differential operator df = np.complex(0,1)*py.fftshift(n-N/2) dfdt = py.ifft( df*py.fft(f) ) return py.real(dfdt)
def FourierDerivative(f): """ this derivatie just works for periodic 2*pi multiple series have to figure out how to make that work for any function """ N = np.size(f) n = np.arange(0, N) # df discrete differential operator df = np.complex(0, 1) * py.fftshift(n - N / 2) dfdt = py.ifft(df * py.fft(f)) return py.real(dfdt)
def test_plot(fpgaclient, bandwidth, snap_depth, dec_rate, n_inputs, signal_input, lof): """ fpgaclient: bandwidth: ADC working badnwidth snap_depth: depth of the snap blocks dec_rate: decimation rate n_inputs: number of simutaneous inputs (2^n) signal_input: known frequency of the test tone lof: lo frequency """ data_dict = read_snaps(fpgaclient, snap_depth) pol1_re = data_dict['cic1_re'] pol1_re = pol1_re[0::(dec_rate/(2**n_inputs))] x = [] a = -bandwidth*1.0/dec_rate for i in range(size(pol1_re)): x.append(a) a = a + 2.0*(bandwidth/dec_rate)/size(pol1_re) pylab.ion() pylab.figure() pylab.subplot(231) pylab.title('ADC data') pylab.xlabel('N') pylab.plot(data_dict['adc1'][100:500], '-o') pylab.hold(False) pylab.subplot(232) pylab.title('mixer_data') pylab.plot(data_dict['s1_mixer'][100:200], '-o') pylab.hold(False) pylab.subplot(233) pylab.title('cic data') pylab.plot(pol1_re[100:200], '-o') pylab.hold(False) pol1_re_fft = fft(pol1_re) pylab.subplot(234) pylab.title('Mixed FFT, Signal: '+str(signal_input)+'MHz, LO: '+str(lof)+'MHz') pylab.xlabel('Frequency: MHz') pylab.semilogy(x,abs(pylab.fftshift((pol1_re_fft)))) pylab.subplot(235) pylab.title('first cic data') pylab.plot(data_dict['s1_firstcic'][100:200], '-o') pylab.hold(False) pylab.subplot(236) pylab.title('halfband data') pylab.plot(data_dict['s1_halfband'][100:200], '-o') return pol1_re, x
def handler(self, msg): # get input x = pmt.to_python(pmt.cdr(msg)) meta = pmt.car(msg) samples = pmt.cdr(msg) # pass data self.curve_data[0] = ( numpy.linspace(1, len(x), len(x)), 10 * numpy.log10(numpy.abs(pylab.fftshift(numpy.fft.fft(x))))) # trigger update self.emit(QtCore.SIGNAL("updatePlot(int)"), 0)
def OnColoc(self, event): from PYME.Analysis import binAvg voxelsize = self.image.voxelsize #assume we have exactly 2 channels #FIXME - add a selector #grab image data imA = self.image.data[:, :, :, 0].squeeze() imB = self.image.data[:, :, :, 1].squeeze() X, Y = np.mgrid[0:float(imA.shape[0]), 0:float(imA.shape[1])] X = X / X.shape[0] Y = Y / X.shape[1] X = X - .5 Y = Y - .5 R = np.sqrt(X**2 + Y**2) H1 = pylab.fftn(imA) H2 = pylab.fftn(imB) rB = np.linspace(0, R.max()) bn, bm, bs = binAvg.binAvg(R, pylab.fftshift(abs(H1 * H2)), rB) bn1, bm1, bs1 = binAvg.binAvg(R, pylab.fftshift(abs(H1 * H1)), rB) bn2, bm2, bs2 = binAvg.binAvg(R, pylab.fftshift(abs(H2 * H2)), rB) pylab.figure() ax = pylab.gca() ax.plot(rB[:-1], bm / np.sqrt(bm1 * bm2)) ax.plot(rB[:-1], 2. / np.sqrt(bn / 2)) xt = np.array([10., 15, 20, 30, 50, 80, 100, 150]) rt = voxelsize[0] / xt pylab.xticks(rt[::-1], ['%d' % xi for xi in xt[::-1]]) pylab.show()
def OnCheckSpacing(self, event): voxx = 0.07 voxy = 0.07 im = self.scope.frameWrangler.currentFrame F = (abs(pylab.fftshift(pylab.fftn(im - im.mean()))) + 1e-2).squeeze() currVoxelSizeID = self.scope.settingsDB.execute( "SELECT sizeID FROM VoxelSizeHistory ORDER BY time DESC").fetchone( ) if not currVoxelSizeID is None: voxx, voxy = self.scope.settingsDB.execute( "SELECT x,y FROM VoxelSizes WHERE ID=?", currVoxelSizeID).fetchone() pylab.figure(2) pylab.clf() xd = F.shape[0] / 2. yd = F.shape[1] / 2. cd = xd * 2 * voxx / 5 #kill central spike F[(xd - cd):(xd + cd), (yd - cd):(yd + cd)] = F.mean() pylab.imshow(F.T, interpolation='nearest', cmap=cm.hot) xd = F.shape[0] / 2. yd = F.shape[1] / 2. pylab.plot( xd + (xd * 2 * voxx / 1.8) * np.cos(np.arange(0, 2.1 * np.pi, .1)), yd + (xd * 2 * voxx / 1.8) * np.sin(np.arange(0, 2.1 * np.pi, .1)), lw=2, label='$1.8 {\mu}m$') pylab.plot( xd + (xd * 2 * voxx / 2.) * np.cos(np.arange(0, 2.1 * np.pi, .1)), yd + (xd * 2 * voxx / 2.) * np.sin(np.arange(0, 2.1 * np.pi, .1)), lw=1, label='$2 {\mu}m$') pylab.plot( xd + (xd * 2 * voxx / 1.6) * np.cos(np.arange(0, 2.1 * np.pi, .1)), yd + (xd * 2 * voxx / 1.6) * np.sin(np.arange(0, 2.1 * np.pi, .1)), lw=1, label='$1.6 {\mu}m$') pylab.xlim(xd - xd * 2 * voxx / 1, xd + xd * 2 * voxx / 1) pylab.ylim(yd - xd * 2 * voxx / 1, yd + xd * 2 * voxx / 1) pylab.legend() self.F = F
def OnCorrelate(self, event): from scipy.fftpack import fftn, ifftn from pylab import fftshift, ifftshift import numpy as np #ch0 = self.image.data[:,:,:,0] chanList = self.image.data.dataList for i in range(len(self.rbs)): if self.rbs[i].GetValue(): ch0 = self.image.data[:, :, :, i] ch0 = np.maximum(ch0 - ch0.mean(), 0) F0 = fftn(ch0) for i in range(self.image.data.shape[3]): if not self.rbs[i].GetValue(): ch0 = self.image.data[:, :, :, i] ch0 = np.maximum(ch0 - ch0.mean(), 0) Fi = ifftn(ch0) corr = abs(fftshift(ifftn(F0 * Fi))) corr -= corr.min() corr = np.maximum(corr - corr.max() * .75, 0) xi, yi, zi = np.where(corr) corr_s = corr[corr > 0] corr_s /= corr_s.sum() dxi = ((xi * corr_s).sum() - corr.shape[0] / 2.) * chanList[i].voxelsize[0] dyi = ((yi * corr_s).sum() - corr.shape[1] / 2.) * chanList[i].voxelsize[1] dzi = ((zi * corr_s).sum() - corr.shape[2] / 2.) * chanList[i].voxelsize[2] self.xctls[i].SetValue(str(int(dxi))) self.yctls[i].SetValue(str(int(dyi))) self.zctls[i].SetValue(str(int(dzi))) self.OnApply(None)
def propagate(self, F, z): """ Propagate a complex pupil, F, a distance z from the nominal focus and return the electric field amplitude Parameters ========== F : 2D array complex pupil z : float distance in nm to propagate """ pf = self.propFac*float(z) fs = F*self.pfm*(np.cos(pf) + j*np.sin(pf)) self._F[:] = ifftshift(fs) self._plan_F_f() return fftshift(self._f/np.sqrt(self._f.size))
def OnCorrelate(self, event): from scipy.fftpack import fftn, ifftn from pylab import fftshift, ifftshift import numpy as np # ch0 = self.image.data[:,:,:,0] chanList = self.image.data.dataList for i in range(len(self.rbs)): if self.rbs[i].GetValue(): ch0 = self.image.data[:, :, :, i] ch0 = np.maximum(ch0 - ch0.mean(), 0) F0 = fftn(ch0) for i in range(self.image.data.shape[3]): if not self.rbs[i].GetValue(): ch0 = self.image.data[:, :, :, i] ch0 = np.maximum(ch0 - ch0.mean(), 0) Fi = ifftn(ch0) corr = abs(fftshift(ifftn(F0 * Fi))) corr -= corr.min() corr = np.maximum(corr - corr.max() * 0.75, 0) xi, yi, zi = np.where(corr) corr_s = corr[corr > 0] corr_s /= corr_s.sum() dxi = ((xi * corr_s).sum() - corr.shape[0] / 2.0) * chanList[i].voxelsize[0] dyi = ((yi * corr_s).sum() - corr.shape[1] / 2.0) * chanList[i].voxelsize[1] dzi = ((zi * corr_s).sum() - corr.shape[2] / 2.0) * chanList[i].voxelsize[2] self.xctls[i].SetValue(str(int(dxi))) self.yctls[i].SetValue(str(int(dyi))) self.zctls[i].SetValue(str(int(dzi))) self.OnApply(None)
def propagate_r(self, f, z): """ Backpropagate an electric field distribution, f, at defocus z to the nominal focus and return the complex pupil Parameters ---------- f : 2D array complex electric field amplitude z : float nominal distance of plane from focus in nm Returns ------- """ self._f[:] = fftshift(f) self._plan_f_F() pf = -self.propFac*float(z) return (ifftshift(self._F)*(np.cos(pf)+j*np.sin(pf)))/np.sqrt(self._f.size)
def propagate(self, F, z): """ Propagate a complex pupil, F, a distance z from the nominal focus and return the electric field amplitude Parameters ========== F : 2D array complex pupil z : float distance in nm to propagate """ pf = self.propFac*float(z) r = max(self.appR*(1 -self.apertureZGrad*z), 0) M = (self.x*self.x + self.y*self.y) < (r*r) fs = F*M*self.pfm*(np.cos(pf) + j*np.sin(pf)) self._F[:] = fftshift(fs) self._plan_F_f() return ifftshift(self._f/np.sqrt(self._f.size))
T = arange(0.0,float(N),1.0) MyPi = 3.1416 xReal = cos(2.0*MyPi*f0MHz*T/fsMHz); xRealmul = cos(2.0*MyPi*f0MHz*T/fsMHz)*cos(2.0*MyPi*f0MHzmul*T/fsMHz) xComplex = exp(1j*2.0*MyPi*f0MHz*T/fsMHz); xComplexneg = exp(-1j*2.0*MyPi*f0MHz*T/fsMHz); xRealF = (1.0/N)*fft(xReal,N); xRealFmul= (1.0/N)*fft(xRealmul,N); xComplexF = (1.0/N)*fft(xComplex,N); xComplexFneg = (1.0/N)*fft(xComplexneg,N); Tplot = arange(-N/2.0,N/2.0,1) subplot(5,1,1) plot(Tplot*fsMHz/N,(fftshift(abs(xRealF)))); subplot(5,1,2) plot(Tplot*fsMHz/N,(fftshift(abs(xComplexF)))); subplot(5,1,3) plot(Tplot*fsMHz/N,(fftshift(abs(xComplexFneg)))); subplot(5,1,4) plot(Tplot*fsMHz/N,(fftshift(abs(xRealFmul)))); show() f=open('output.txt','w') file_output.comple_w(f, xReal, 'xReal') file_output.comple_w(f, xComplex, 'xComplex') file_output.comple_w(f, xRealF, 'xRealF') file_output.comple_w(f, xComplexF, 'xComplexF') f.close()
#get the gaussian kernel w = 100 h = 100 in_mask = np.zeros((h, w), dtype=np.float32) in_mask[int(h / 2), int(w / 2)] = 1 img_kernel = ndimage.gaussian_laplace(in_mask, sigma=2) # kernel = img_kernel[50 - 10:50 + 10, 50 - 10:50 + 10] kernel_ft = fftpack.fft2(kernel, shape=img.shape[:2], axes=(0, 1)) #manual pad zeros, same results. kernel_pad = np.zeros_like(img, dtype='float') kh, kw = kernel.shape[:2] kernel_pad[:kh, :kw] = kernel kernel_pad_ft = fftpack.fft2(kernel_pad, axes=(0, 1)) fig1, axs = plt.subplots(1, 3) axs[0].imshow(np.abs(pylab.fftshift(kernel_ft))) axs[1].imshow(np.abs(pylab.fftshift(kernel_pad_ft))) axs[2].imshow(np.abs(kernel_pad_ft - kernel_ft)) # convolve img_ft = fftpack.fft2(img, axes=(0, 1)) img2_ft = kernel_ft * img_ft img2 = fftpack.ifft2(img2_ft, axes=(0, 1)).real img2 = (img2 - np.min(img2)) / (np.max(img2) - np.min(img2)) axes[2].imshow(img2, cmap='gray') axes[2].set_title('blur via Gaussian filter') plt.show()
MyPi = pi ModRatio = 0.5 xInput = cos(2.0*MyPi*finput*T/fsmod) xCarrier = cos(2.0*MyPi*fcarr*T/fsmod) xMod = (xInput * ModRatio + 1) * xCarrier xInputF = (1.0/N)*fft(xInput,N); xCarrierF = (1.0/N)*fft(xCarrier,N); xModF = (1.0/N)*fft(xMod,N); #xComplexFneg = (1.0/N)*fft(xComplexneg,N); Tplot = arange(-N/2.0,N/2.0,1) pic_n=5 subplot(pic_n,1,1) plot(Tplot*fsmod/N,(fftshift(abs(xModF)))); subplot(pic_n,1,2) plot(Tplot*fsmod/N,(fftshift(abs(xCarrierF)))); subplot(pic_n,1,3) plot(T,xInput); subplot(pic_n,1,4) plot(T,xMod); subplot(pic_n,1,5) plot(T,xCarrier); #subplot(5,1,4) #plot(Tplot*fsMHz/N,(fftshift(abs(xRealFmul)))); show() #f=open('output.txt','w') #file_output.comple_w(f, xReal, 'xReal') #file_output.comple_w(f, xComplex, 'xComplex')
measureData[i, :] = analyzeSignal1 T1 = T1 / M print('T1 = ', T1) Vres = c0 / (2 * f0 * T1 * M * Mpad) for ii in range(M): sigRWin[ii, :] = measureData[ii, :] * windowFunction1 for ii in range(M): sigRfft[ii, :] = fft(sigRWin[ii, :], N * Npad) for ii in range(N * Npad): sigDWin[:, ii] = sigRfft[:, ii] * windowFunction2 for ii in range(N * Npad): sigDfft[:, ii] = fftshift(fft(sigDWin[:, ii], M * Mpad)) ''' plt.figure(1) plt.contourf(Rres*np.arange(1,N*Npad+1),Vres*(np.arange(1,M*Mpad+1) - M*Mpad/2),np.abs(sigDfft)) plt.xlabel('Range/m') plt.ylabel('Velocity/mps') plt.pause(0.000001) plt.cla() ''' ''' np.savetxt('./Rres/Rres'+str(j)+'.txt',Rres*np.arange(1,N*Npad+1)) np.savetxt('./Vres/Vres'+str(j)+'.txt',Vres*(np.arange(1,M*Mpad+1) - M*Mpad/2)) np.savetxt('./sigDfft/sigDfft'+str(j)+'.txt',np.abs(sigDfft)) ''' plt.figure(1)
sigReceive = S1 + S2 + S3 sigRWin = np.zeros((L, N), dtype=complex) sigDWin = np.zeros((L, N * Npad), dtype=complex) sigRfft = np.zeros((L, N * Npad), dtype=complex) sigDfft = np.zeros((L * Lpad, N * Npad), dtype=complex) windowFunction1 = np.hanning(N) # windowFunction windowFunction2 = np.hanning(L) # windowFunction for ii in range(L): sigRWin[ii, :] = sigReceive[ii, :] * windowFunction1 for ii in range(L): sigRfft[ii, :] = fft(sigRWin[ii, :], N * Npad) for ii in range(N * Npad): sigDWin[:, ii] = sigRfft[:, ii] * windowFunction2 for ii in range(N * Npad): sigDfft[:, ii] = fftshift(fft(sigDWin[:, ii], L * Lpad)) Rres = c / (2 * B * Npad) Vres = c / (2 * 24.25 * 10**9 * T * L * Lpad) plt.contourf(Rres * np.arange(1, N * Npad + 1), Vres * (np.arange(1, L * Lpad + 1) - L * Lpad / 2), np.abs(sigDfft)) plt.xlabel('Range/m') plt.ylabel('Velocity/mps') plt.title('Range-Doppler Map') plt.minorticks_on() plt.show()
MyPi = pi ModRatio = 0.5 xInput = cos(2.0 * MyPi * finput * T / fsmod) xCarrier = cos(2.0 * MyPi * fcarr * T / fsmod) xMod = (xInput * ModRatio + 1) * xCarrier xInputF = (1.0 / N) * fft(xInput, N) xCarrierF = (1.0 / N) * fft(xCarrier, N) xModF = (1.0 / N) * fft(xMod, N) #xComplexFneg = (1.0/N)*fft(xComplexneg,N); Tplot = arange(-N / 2.0, N / 2.0, 1) pic_n = 5 subplot(pic_n, 1, 1) plot(Tplot * fsmod / N, (fftshift(abs(xModF)))) subplot(pic_n, 1, 2) plot(Tplot * fsmod / N, (fftshift(abs(xCarrierF)))) subplot(pic_n, 1, 3) plot(T, xInput) subplot(pic_n, 1, 4) plot(T, xMod) subplot(pic_n, 1, 5) plot(T, xCarrier) #subplot(5,1,4) #plot(Tplot*fsMHz/N,(fftshift(abs(xRealFmul)))); show() #f=open('output.txt','w') #file_output.comple_w(f, xReal, 'xReal') #file_output.comple_w(f, xComplex, 'xComplex')
pylab.plot(mixer_data[100:200], '-o') #pylab.semilogy(abs(fft(mixer_data))) pylab.hold(False) pylab.subplot(223) pylab.title('Available LO frequencies') pylab.ylabel('MHz') #pylab.plot(lof_avail,'-o') pylab.plot(pol1_re[100:200], '-o') pylab.hold(False) pol1_re_fft = fft(pol1_re) pylab.subplot(224) pylab.title('Mixed FFT, Signal: '+str(signal_input)+'MHz, LO: '+str(lof_output)+'MHz') pylab.xlabel('Frequency: MHz') pylab.semilogy(x,abs(pylab.fftshift((pol1_re_fft)))) pylab.hold(False) pylab.draw() pol1_re = read_snaps(snap_depth) pol1_re = pol1_re[0::(dec_rate/8)] time.sleep(2) #cic1_data, hb_data, cic2_data = read_cic_snaps(fpga, dec_rate, snap_depth) #pylab.figure() #pylab.subplot(221) #pylab.semilogy(abs(pylab.fftshift(fft(cic1_data[0:1024])))) #pylab.title('FFT of the output of CIC_1') #pylab.subplot(222)
def correction_light(I, method, show_light, mask=None): """Corrige la derive eclairement :I: array_like ou iplimage :method: 'polynomial' or 'frequency' :show_light: option affiche correction (true|false) :mask: array de zone non interet :returns: iplimage 32bit """ from progress import * import Tkinter if type(I) == cv.iplimage: if I.nChannels == 3: if method == 'None': I = RGB2L(I) I = cv2array(I)[:, :, 0] I = pymorph.hmin(I, 15, pymorph.sedisk(3)) I = array2cv(I) cv.EqualizeHist(I, I) return I I = RGB2L(I) I_32bit = cv.CreateImage(cv.GetSize(I), cv.IPL_DEPTH_32F, 1) cv.ConvertScale(I, I_32bit, 3000.0, 0.0) I = cv.CloneImage(I_32bit) I = cv2array(I)[:, :, 0] elif len(I.shape) == 3: I = (I[:, :, 0] + I[:, :, 0] + I[:, :, 0])\ / 3.0 # A modifier: non utiliser dans notre cas elif method == 'None': I = array2cv(I) cv.EqualizeHist(I, I) return I I = np.log(I + 10 ** (-6)) (H, W) = np.shape(I) I_out = I * 0 + 10 ** (-6) if method == 'polynomial': ## I = M.A avec A coeff. du polynome I_flat = I.flatten() degree = 3 print("modification degree 3") #degree du polynome nb_coeff = (degree + 1) * (degree + 2) / 2 # nombre coefficient [yy, xx] = np.meshgrid(np.arange(W, dtype=np.float64), np.arange(H, dtype=np.float64)) if mask is not None: xx[mask] = 0 yy[mask] = 0 # Creation de M try: M = np.zeros((H * W, nb_coeff), dtype=np.float64) except MemoryError: print MemoryError return MemoryError i, j = 0, 0 # i,j degree de x,y #Bar progression bar = Tkinter.Tk(className='Correcting Light...') m = Meter(bar, relief='ridge', bd=3) m.pack(fill='x') m.set(0.0, 'Starting correction...') for col in np.arange(nb_coeff): M[:, col] = (xx.flatten() ** i) * (yy.flatten() ** j) i += 1 m.set(0.5 * float(col) / (nb_coeff - 1)) if i + j == degree + 1: i = 0 j += 1 # Resolution au sens des moindres carree: pseudo-inverse try: M = pl.pinv(M) A = np.dot(M, I_flat) except ValueError: return ValueError # Calcul de la surface i, j = 0, 0 surface = np.zeros((H, W), dtype=np.float64) for cmpt in np.arange(nb_coeff): surface += A[cmpt] * (xx ** i) * (yy ** j) # forme quadratique i += 1 m.set(0.5 + 0.5 * float(cmpt) / (nb_coeff - 1)) if i + j == degree + 1: i = 0 j += 1 bar.destroy() I_out = np.exp(I / surface) light = surface elif method == 'frequency': Rx, Ry = 2, 2 # zero padding N = [H, W] filtre = np.zeros((N[1], N[0])) centre_x = round(N[0] / 2) centre_y = round(N[1] / 2) print("FFT2D...") I_fourier = pl.fftshift(pl.fft2(I, N)) # Gaussian filter [xx, yy] = np.meshgrid(np.arange(N[0], dtype=np.float), np.arange(N[1], dtype=np.float)) filtre = np.exp(-2 * ((xx - centre_x) ** 2 + (yy - centre_y) ** 2) / (Rx ** 2 + Ry ** 2)) filtre = pl.transpose(filtre) I_fourier = I_fourier * filtre print("IFFT2D...") I_out = (np.abs(pl.ifft2(pl.ifftshift(I_fourier), N)))[0:H, 0:W] light = I_out I_out = np.exp(I / I_out) else: light = I * 0 I_out = I # Display Light if show_light: light = ((light - light.min()) * 3000.0 / light.max()).astype('float32') light = array2cv(light) fig = pl.figure() pl.imshow(light) fig.show() I_out = (I_out - I_out.min()) * 3000.0 / I_out.max() I_out = I_out.astype('uint8') #chapeau haut de forme I_out = pymorph.hmin(I_out, 25, pymorph.sedisk(3)) #Conversion en iplimage et ajustement contraste gr = array2cv(I_out) cv.EqualizeHist(gr, gr) return gr
MyPi = 3.1416 xReal = cos(2.0 * MyPi * f0MHz * T / fsMHz) xRealmul = cos(2.0 * MyPi * f0MHz * T / fsMHz) * cos( 2.0 * MyPi * f0MHzmul * T / fsMHz) xComplex = exp(1j * 2.0 * MyPi * f0MHz * T / fsMHz) xComplexneg = exp(-1j * 2.0 * MyPi * f0MHz * T / fsMHz) xRealF = (1.0 / N) * fft(xReal, N) xRealFmul = (1.0 / N) * fft(xRealmul, N) xComplexF = (1.0 / N) * fft(xComplex, N) xComplexFneg = (1.0 / N) * fft(xComplexneg, N) Tplot = arange(-N / 2.0, N / 2.0, 1) subplot(5, 1, 1) plot(Tplot * fsMHz / N, (fftshift(abs(xRealF)))) subplot(5, 1, 2) plot(Tplot * fsMHz / N, (fftshift(abs(xComplexF)))) subplot(5, 1, 3) plot(Tplot * fsMHz / N, (fftshift(abs(xComplexFneg)))) subplot(5, 1, 4) plot(Tplot * fsMHz / N, (fftshift(abs(xRealFmul)))) show() f = open('output.txt', 'w') file_output.comple_w(f, xReal, 'xReal') file_output.comple_w(f, xComplex, 'xComplex') file_output.comple_w(f, xRealF, 'xRealF') file_output.comple_w(f, xComplexF, 'xComplexF') f.close()
def handler(self, msg): # get input x = pmt.to_python(pmt.cdr(msg)) meta = pmt.car(msg); samples = pmt.cdr(msg); # pass data self.curve_data[0] = (numpy.linspace(1,len(x),len(x)), 10*numpy.log10(numpy.abs(pylab.fftshift(numpy.fft.fft(x))))); # trigger update self.emit(QtCore.SIGNAL("updatePlot(int)"), 0)