def _phase_map(self):
     self.dphi = (2*P.pi * self.nhop * P.arange(self.nfft/2+1)) / self.nfft
     A = P.diff(P.angle(self.STFT),1) # Complete Phase Map
     U = P.c_[P.angle(self.STFT[:,0]), A - P.atleast_2d(self.dphi).T ]
     U = U - P.np.round(U/(2*P.pi))*2*P.pi
     self.dPhi = U
     return U
 def _phase_map(self):
     self.dphi = (2*P.pi * self.nhop * P.arange(self.nfft/2+1)) / self.nfft
     A = P.diff(P.angle(self.STFT),1) # Complete Phase Map
     U = P.c_[P.angle(self.STFT[:,0]), A - P.matrix(self.dphi).T ]
     U = U - P.np.round(U/(2*P.pi))*2*P.pi
     self.dPhi = U
     return U
Exemple #3
0
 def analysis(self,x):
   X = stft(x,self.win,self.n)
   delta = pl.angle(X) - self.phs
   self.phs = pl.angle(X)
   delta = unwrap(delta)
   freqs = self.fc + delta*self.sr/(2*pl.pi*self.h) 
   self.n += self.h
   return abs(X),freqs
Exemple #4
0
def xyamb(xytab,qu,xyout=''):

    mytb=taskinit.tbtool()

    if not isinstance(qu,tuple):
        raise Exception,'qu must be a tuple: (Q,U)'

    if xyout=='':
        xyout=xytab
    if xyout!=xytab:
        os.system('cp -r '+xytab+' '+xyout)

    QUexp=complex(qu[0],qu[1])
    print 'Expected QU = ',qu   # , '  (',pl.angle(QUexp)*180/pi,')'

    mytb.open(xyout,nomodify=False)

    QU=mytb.getkeyword('QU')['QU']
    P=pl.sqrt(QU[0,:]**2+QU[1,:]**2)

    nspw=P.shape[0]
    for ispw in range(nspw):
        st=mytb.query('SPECTRAL_WINDOW_ID=='+str(ispw))
        if (st.nrows()>0):
            q=QU[0,ispw]
            u=QU[1,ispw]
            qufound=complex(q,u)
            c=st.getcol('CPARAM')
            fl=st.getcol('FLAG')
            xyph0=pl.angle(pl.mean(c[0,:,:][pl.logical_not(fl[0,:,:])]),True)
            print 'Spw = '+str(ispw)+': Found QU = '+str(QU[:,ispw])  # +'   ('+str(pl.angle(qufound)*180/pi)+')'
            #if ( (abs(q)>0.0 and abs(qu[0])>0.0 and (q/qu[0])<0.0) or
            #     (abs(u)>0.0 and abs(qu[1])>0.0 and (u/qu[1])<0.0) ):
            if ( pl.absolute(pl.angle(qufound/QUexp)*180/pi)>90.0 ):
                c[0,:,:]*=-1.0
                xyph1=pl.angle(pl.mean(c[0,:,:][pl.logical_not(fl[0,:,:])]),True)
                st.putcol('CPARAM',c)
                QU[:,ispw]*=-1
                print '   ...CONVERTING X-Y phase from '+str(xyph0)+' to '+str(xyph1)+' deg'
            else:
                print '      ...KEEPING X-Y phase '+str(xyph0)+' deg'
            st.close()
    QUr={}
    QUr['QU']=QU
    mytb.putkeyword('QU',QUr)
    mytb.close()
    QUm=pl.mean(QU[:,P>0],1)
    QUe=pl.std(QU[:,P>0],1)
    Pm=pl.sqrt(QUm[0]**2+QUm[1]**2)
    Xm=0.5*atan2(QUm[1],QUm[0])*180/pi

    print 'Ambiguity resolved (spw mean): Q=',QUm[0],'U=',QUm[1],'(rms=',QUe[0],QUe[1],')','P=',Pm,'X=',Xm

    stokes=[1.0,QUm[0],QUm[1],0.0]
    print 'Returning the following Stokes vector: '+str(stokes)
    
    return stokes
Exemple #5
0
  def update_design(self):
    ax = self.ax
    ax.cla()
    ax2 = self.ax2
    ax2.cla()

    wp = self.wp
    ws = self.ws
    gpass = self.gpass
    gstop = self.gstop
    b, a = ss.iirdesign(wp, ws, gpass, gstop, ftype=self.ftype, output='ba')
    self.a = a
    self.b = b
    #b = [1,2]; a = [1,2]
    #Print this on command line so we can use it in our programs
    print 'b = ', pylab.array_repr(b)
    print 'a = ', pylab.array_repr(a)

    my_w = pylab.logspace(pylab.log10(.1*self.ws[0]), 0.0, num=512)
    #import pdb;pdb.set_trace()
    w, h = freqz(b, a, worN=my_w*pylab.pi)
    gp = 10**(-gpass/20.)#Go from db to regular
    gs = 10**(-gstop/20.)
    self.design_line, = ax.plot([.1*self.ws[0], self.ws[0], wp[0], wp[1], ws[1], 1.0], [gs, gs, gp, gp, gs, gs], 'ko:', lw=2, picker=5)
    ax.semilogx(w/pylab.pi, pylab.absolute(h),lw=2)
    ax.text(.5,1.0, '{:d}/{:d}'.format(len(b), len(a)))
    pylab.setp(ax, 'xlim', [.1*self.ws[0], 1.2], 'ylim', [-.1, max(1.1,1.1*pylab.absolute(h).max())], 'xticklabels', [])

    ax2.semilogx(w/pylab.pi, pylab.unwrap(pylab.angle(h)),lw=2)
    pylab.setp(ax2, 'xlim', [.1*self.ws[0], 1.2])
    ax2.set_xlabel('Normalized frequency')

    pylab.draw()
 def _pvoc2(self, X_hat, Phi_hat=None, R=None):
     """
     ::
       alternate (batch) implementation of phase vocoder - time-stretch
       inputs:
         X_hat - estimate of signal magnitude
         [Phi_hat] - estimate of signal phase
         [R] - resynthesis hop ratio
       output:
         updates self.X_hat with modified complex spectrum
     """
     N, W, H = self.nfft, self.wfft, self.nhop
     R = 1.0 if R is None else R
     dphi = P.atleast_2d((2*P.pi * H * P.arange(N/2+1)) / N).T
     print "Phase Vocoder Resynthesis...", N, W, H, R
     A = P.angle(self.STFT) if Phi_hat is None else Phi_hat
     U = P.diff(A,1) - dphi
     U = U - P.np.round(U/(2*P.pi))*2*P.pi
     t = P.arange(0,n_cols,R)
     tf = t - P.floor(t)
     phs = P.c_[A[:,0], U] 
     phs += U[:,idx[1]] + dphi # Problem, what is idx ?
     Xh = (1-tf)*Xh[:-1] + tf*Xh[1:]
     Xh *= P.exp( 1j * phs)
     self.X_hat = Xh
 def _pvoc(self, X_hat, Phi_hat=None, R=None):
     """
     ::
       a phase vocoder - time-stretch
       inputs:
         X_hat - estimate of signal magnitude
         [Phi_hat] - estimate of signal phase
         [R] - resynthesis hop ratio
       output:
         updates self.X_hat with modified complex spectrum
     """
     N = self.nfft
     W = self.wfft
     H = self.nhop
     R = 1.0 if R is None else R
     dphi = (2*P.pi * H * P.arange(N/2+1)) / N
     print "Phase Vocoder Resynthesis...", N, W, H, R
     A = P.angle(self.STFT) if Phi_hat is None else Phi_hat
     phs = A[:,0]
     self.X_hat = []
     n_cols = X_hat.shape[1]
     t = 0
     while P.floor(t) < n_cols:
         tf = t - P.floor(t)            
         idx = P.arange(2)+int(P.floor(t))
         idx[1] = n_cols-1 if t >= n_cols-1 else idx[1]
         Xh = X_hat[:,idx]
         Xh = (1-tf)*Xh[:,0] + tf*Xh[:,1]
         self.X_hat.append(Xh*P.exp( 1j * phs))
         U = A[:,idx[1]] - A[:,idx[0]] - dphi
         U = U - P.np.round(U/(2*P.pi))*2*P.pi
         phs += (U + dphi)
         t += P.randn()*P.sqrt(PVOC_VAR*R) + R # 10% variance
     self.X_hat = P.np.array(self.X_hat).T
def plot_phases(in_file, plot_type, plot_log):
    flags = ['histogram','phases']
    plot_flag = 0
    log_flag = 0

    def no_log(x):
        return x

    fig = pylab.figure(1)
    ax = fig.add_subplot(111)

    try:
        img = spimage.sp_image_read(in_file,0)
    except:
        raise IOError("Can't read %s." % in_file)

    values = img.image.reshape(pylab.size(img.image))

    if plot_log:
        log_function = pylab.log
    else:
        log_function = no_log

    if plot_type == PHASES:
        hist = pylab.histogram(pylab.angle(values),bins=500)
        ax.plot((hist[1][:-1]+hist[1][1:])/2.0,log_function(hist[0]))
    elif plot_flag == HISTOGRAM:
        hist = pylab.histogram2d(pylab.real(values),pylab.imag(values),bins=500)
        ax.imshow(log_function(hist[0]),extent=(hist[2][0],hist[2][-1],-hist[1][-1],-hist[1][0]),interpolation='nearest')
    else:
        ax.plot(pylab.real(values),pylab.imag(values),'.')
    return fig
Exemple #9
0
 def _pvoc(self, X_hat, Phi_hat=None, R=None):
     """
     ::
       a phase vocoder - time-stretch
       inputs:
         X_hat - estimate of signal magnitude
         [Phi_hat] - estimate of signal phase
         [R] - resynthesis hop ratio
       output:
         updates self.X_hat with modified complex spectrum
     """
     N = self.nfft
     W = self.wfft
     H = self.nhop
     R = 1.0 if R is None else R
     dphi = (2 * P.pi * H * P.arange(N / 2 + 1)) / N
     print("Phase Vocoder Resynthesis...", N, W, H, R)
     A = P.angle(self.STFT) if Phi_hat is None else Phi_hat
     phs = A[:, 0]
     self.X_hat = []
     n_cols = X_hat.shape[1]
     t = 0
     while P.floor(t) < n_cols:
         tf = t - P.floor(t)
         idx = P.arange(2) + int(P.floor(t))
         idx[1] = n_cols - 1 if t >= n_cols - 1 else idx[1]
         Xh = X_hat[:, idx]
         Xh = (1 - tf) * Xh[:, 0] + tf * Xh[:, 1]
         self.X_hat.append(Xh * P.exp(1j * phs))
         U = A[:, idx[1]] - A[:, idx[0]] - dphi
         U = U - P.np.round(U / (2 * P.pi)) * 2 * P.pi
         phs += (U + dphi)
         t += P.randn() * P.sqrt(PVOC_VAR * R) + R  # 10% variance
     self.X_hat = P.np.array(self.X_hat).T
Exemple #10
0
def plot_phases(in_file, plot_type, plot_log):
    plot_flag = 0

    def no_log(x):
        return x

    fig = pylab.figure(1)
    ax = fig.add_subplot(111)

    try:
        img = spimage.sp_image_read(in_file, 0)
    except IOError:
        raise IOError("Can't read %s." % in_file)

    values = img.image.reshape(pylab.size(img.image))

    if plot_log:
        log_function = pylab.log
    else:
        log_function = no_log

    if plot_type == PHASES:
        hist = pylab.histogram(pylab.angle(values), bins=500)
        ax.plot((hist[1][:-1] + hist[1][1:]) / 2, log_function(hist[0]))
    elif plot_flag == HISTOGRAM:
        hist = pylab.histogram2d(pylab.real(values),
                                 pylab.imag(values),
                                 bins=500)
        ax.imshow(log_function(hist[0]),
                  extent=(hist[2][0], hist[2][-1], -hist[1][-1], -hist[1][0]),
                  interpolation='nearest')
    else:
        ax.plot(pylab.real(values), pylab.imag(values), '.')
    return fig
Exemple #11
0
 def _pvoc2(self, X_hat, Phi_hat=None, R=None):
     """
     ::
       alternate (batch) implementation of phase vocoder - time-stretch
       inputs:
         X_hat - estimate of signal magnitude
         [Phi_hat] - estimate of signal phase
         [R] - resynthesis hop ratio
       output:
         updates self.X_hat with modified complex spectrum
     """
     N, W, H = self.nfft, self.wfft, self.nhop
     R = 1.0 if R is None else R
     dphi = P.atleast_2d((2 * P.pi * H * P.arange(N / 2 + 1)) / N).T
     print("Phase Vocoder Resynthesis...", N, W, H, R)
     A = P.angle(self.STFT) if Phi_hat is None else Phi_hat
     U = P.diff(A, 1) - dphi
     U = U - P.np.round(U / (2 * P.pi)) * 2 * P.pi
     t = P.arange(0, n_cols, R)
     tf = t - P.floor(t)
     phs = P.c_[A[:, 0], U]
     phs += U[:, idx[1]] + dphi  # Problem, what is idx ?
     Xh = (1 - tf) * Xh[:-1] + tf * Xh[1:]
     Xh *= P.exp(1j * phs)
     self.X_hat = Xh
    def _istftm(self, X_hat=None, Phi_hat=None, pvoc=False, usewin=True, resamp=None):
        """
        :: 
            Inverse short-time Fourier transform magnitude. Make a signal from a |STFT| transform.
            Uses phases from self.STFT if Phi_hat is None.

            Inputs:
            X_hat - N/2+1 magnitude STFT [None=abs(self.STFT)]
            Phi_hat - N/2+1 phase STFT   [None=exp(1j*angle(self.STFT))]
            pvoc - whether to use phase vocoder [False]      
            usewin - whether to use overlap-add [False]

            Returns:
             x_hat - estimated signal
        """
        if not self._have_stft:
                return None
        X_hat = P.np.abs(self.STFT) if X_hat is None else P.np.abs(X_hat)
        if pvoc:
            self._pvoc(X_hat, Phi_hat, pvoc)
        else:
            Phi_hat = P.angle(self.STFT) if Phi_hat is None else Phi_hat
            self.X_hat = X_hat *  P.exp( 1j * Phi_hat )
        if usewin:
            self.win = P.hanning(self.nfft) 
            self.win *= 1.0 / ((float(self.nfft)*(self.win**2).sum())/self.nhop)
        else:
            self.win = P.ones(self.nfft)
        if resamp:
            self.win = sig.resample(self.win, int(P.np.round(self.nfft * resamp)))
        fp = self._check_feature_params()
        self.x_hat = self._overlap_add(P.real(self.nfft * P.irfft(self.X_hat.T)), usewin=usewin, resamp=resamp)
        if self.verbosity:
            print "Extracted iSTFTM->self.x_hat"        
        return self.x_hat
Exemple #13
0
    def _istftm(self,
                X_hat=None,
                Phi_hat=None,
                pvoc=False,
                usewin=True,
                resamp=None):
        """
        :: 
            Inverse short-time Fourier transform magnitude. Make a signal from a |STFT| transform.
            Uses phases from self.STFT if Phi_hat is None.

            Inputs:
            X_hat - N/2+1 magnitude STFT [None=abs(self.STFT)]
            Phi_hat - N/2+1 phase STFT   [None=exp(1j*angle(self.STFT))]
            pvoc - whether to use phase vocoder [False]      
            usewin - whether to use overlap-add [False]

            Returns:
             x_hat - estimated signal
        """
        if not self._have_stft:
            return None
        X_hat = self.X if X_hat is None else P.np.abs(X_hat)
        if pvoc:
            self._pvoc(X_hat, Phi_hat, pvoc)
        else:
            Phi_hat = P.angle(self.STFT) if Phi_hat is None else Phi_hat
            self.X_hat = X_hat * P.exp(1j * Phi_hat)
        if usewin:
            if self.win is None:
                self.win = P.ones(
                    self.wfft) if self.window == 'rect' else P.np.sqrt(
                        P.hanning(self.wfft))
            if len(self.win) != self.nfft:
                self.win = P.r_[self.win, P.np.zeros(self.nfft - self.wfft)]
            if len(self.win) != self.nfft:
                error.BregmanError(
                    "features_base.Features._istftm(): assertion failed len(self.win)==self.nfft"
                )
        else:
            self.win = P.ones(self.nfft)
        if resamp:
            self.win = sig.resample(self.win,
                                    int(P.np.round(self.nfft * resamp)))
        fp = self._check_feature_params()
        self.x_hat = self._overlap_add(P.real(P.irfft(self.X_hat.T)),
                                       usewin=usewin,
                                       resamp=resamp)
        if self.verbosity:
            print("Extracted iSTFTM->self.x_hat")
        return self.x_hat
Exemple #14
0
    def _icqft(self, V_hat):
        """
        ::

            Inverse constant-Q Fourier transform. Make a signal from a constant-Q transform.
        """
        if not self._have_cqft:
                return False        
        fp = self._check_feature_params()
        X_hat = pylab.array( pylab.dot(self.Q.T, V_hat) ) * pylab.exp( 1j * pylab.angle(self.STFT) )
        self.x_hat = self._overlap_add( pylab.real(fp['nfft'] * pylab.irfft(X_hat.T)) )
        if fp['verbosity']:
            print "Extracted iCQFT->x_hat"
        return True
Exemple #15
0
def plot_image(in_file,*arguments):
    
    try:
        img = spimage.sp_image_read(in_file,0)
    except:
        print "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

    for flag in arguments:
        flag = flag.lower()
        if flag in plot_flags:
            plot_flag = flag
        elif flag in shift_flags:
            shift_flag = flag
        elif flag in log_flags:
            log_flag = flag
        else:
            print "unknown flag %s" % flag

    if shift_flag:
        img = spimage.sp_image_shift(img)

    def no_log(x):
        return x

    if log_flag:
        log_function = pylab.log
    else:
        log_function = no_log

    if (plot_flag == "mask"):
        pylab.imshow(img.mask,origin='lower',interpolation="nearest")
    elif(plot_flag == "phase"):
        pylab.imshow(pylab.angle(img.image),cmap='hsv',origin='lower',interpolation="nearest")
    elif(plot_flag == "real"):
        pylab.imshow(log_function(pylab.real(img.image)),origin='lower',interpolation="nearest")
    elif(plot_flag == "imag"):
        pylab.imshow(log_function(pylab.imag(img.image)),origin='lower',interpolation="nearest")
    else:
        pylab.imshow(log_function(abs(img.image)),origin='lower',interpolation="nearest")

    pylab.show()
Exemple #16
0
    def _istftm(self, X_hat, Phi_hat=None):
        """
        ::

            Inverse short-time Fourier transform magnitude. Make a signal from a |STFT| transform.
            Uses phases from self.STFT if Phi_hat is None.
        """
        if not self._have_stft:
                return False        
        if Phi_hat is None:
            Phi_hat = pylab.exp( 1j * pylab.angle(self.STFT))
        fp = self._check_feature_params()
        X_hat = X_hat *  Phi_hat
        self.x_hat = self._overlap_add( pylab.real(fp['nfft'] * pylab.irfft(X_hat.T)) )
        if fp['verbosity']:
            print "Extracted iSTFTM->self.x_hat"
        return True
    def _istftm(self, X_hat=None, Phi_hat=None, pvoc=False, usewin=True, resamp=None):
        """
        :: 
            Inverse short-time Fourier transform magnitude. Make a signal from a |STFT| transform.
            Uses phases from self.STFT if Phi_hat is None.

            Inputs:
            X_hat - N/2+1 magnitude STFT [None=abs(self.STFT)]
            Phi_hat - N/2+1 phase STFT   [None=exp(1j*angle(self.STFT))]
            pvoc - whether to use phase vocoder [False]      
            usewin - whether to use overlap-add [False]

            Returns:
             x_hat - estimated signal
        """
        if not self._have_stft:
            return None
        X_hat = self.X if X_hat is None else P.np.abs(X_hat)
        if pvoc:
            self._pvoc(X_hat, Phi_hat, pvoc)
        else:
            Phi_hat = P.angle(self.STFT) if Phi_hat is None else Phi_hat
            self.X_hat = X_hat * P.exp(1j * Phi_hat)
        if usewin:
            if self.win is None:
                self.win = P.ones(self.wfft) if self.window == 'rect' else P.np.sqrt(
                    P.hanning(self.wfft))
            if len(self.win) != self.nfft:
                self.win = P.r_[self.win, P.np.zeros(self.nfft - self.wfft)]
            if len(self.win) != self.nfft:
                error.BregmanError(
                    "features_base.Features._istftm(): assertion failed len(self.win)==self.nfft")
        else:
            self.win = P.ones(self.nfft)
        if resamp:
            self.win = sig.resample(
                self.win, int(P.np.round(self.nfft * resamp)))
        fp = self._check_feature_params()
        self.x_hat = self._overlap_add(
            P.real(P.irfft(self.X_hat.T)), usewin=usewin, resamp=resamp)
        if self.verbosity:
            print("Extracted iSTFTM->self.x_hat")
        return self.x_hat
Exemple #18
0
    def calc_phase(self):
        
        self.s = (fourier.rb_fft_1d(self.r, undersampling=0, fft_shift_flag=1)).T
#        self.s = self.s.T
        self.abs_array = abs(self.s)
        self.phase_array = pylab.angle(self.s)
        for i in range(0, np.shape(self.phase_array)[0]):
            for j in range(0, np.shape(self.phase_array)[1]):
                  self.phase_array[i][j] = self.phase_array[i][j]*180/np.pi
        
        
        
        
        n_i=np.shape(self.r)[0]
        n_t=np.shape(self.r)[1]
        
        #calculate the frequency axis
        self.s_axis[0]=np.fft.fftfreq(n_t, 3e8*100*2.11e-15)
        self.s_axis[0]=self.s_axis[0][:n_t/2]
        
        self.i_max=self.abs_array[0].argmax()
        
        print("Frequency, rough guess:", self.s_axis[0][self.i_max])
        #now refine this by weighted averaging???
        #this function is general, but it assumes that s[0] is the best interferogram
        w0=np.average(self.s_axis[0][self.i_max-2:self.i_max+3], weights=self.abs_array[0][self.i_max-2:self.i_max+3])
        print("Frequency, refined guess:", w0)	
        tau=1/(w0*3e8*100e-15)

        #now find the phases at the i_max and the point before and after
        i_fit=list(range(self.i_max-1, self.i_max+2)) #these are three points
        ph=np.zeros(n_i)
        for j in range(0, n_i):
            ph[j]=np.average(self.phase_array[j][i_fit])
        
        print(ph[0], ph[1])
	
        simple_phase= (ph[0] - ph[1])
	
        print(simple_phase)
Exemple #19
0
    def _calculatefdData(self,tdData):
        #no need to copy it before (access member variable is ugly but shorter)

        #calculate the fft of the X channel
        fd=py.fft(tdData.getEX())
        #calculate absolute and phase values
        fdabs=abs(fd)
        fdph=abs(py.unwrap(py.angle(fd)))
        #calculate frequency axis
        dfreq=py.fftfreq(tdData.num_points,tdData.dt)
        #extrapolate phase to 0 and 0 frequency
        fdph=self.removePhaseOffset(dfreq,fdph)
        #set up the fdData array
        t=py.column_stack((dfreq,fd.real,fd.imag,fdabs,fdph))
        
        #this is so not nice!
        self.fdData=t
        unc=self.calculateFDunc()
        t=self.getcroppedData(t,0,unc[-1,0])
        
        #interpolate uncertainty        
        intpunc=interp1d(unc[:,0],unc[:,1:],axis=0)        
        unc=intpunc(t[:,0])
        return py.column_stack((t,unc))
Exemple #20
0
    for flag in arguments:
        if flag in flags:
            plot_flag = flag
        elif flag in log_flags:
            log_flag = flag
        else:
            print "unknown flag %s" % flag

    if log_flag == 'log':
        log_function = pylab.log
    else:
        log_function = no_log

    if plot_flag == 'phases':
        hist = pylab.histogram(pylab.angle(values),bins=50)
        ax.plot((hist[1][:-1]+hist[1][1:])/2.0,log_function(hist[0]))
    elif plot_flag == 'histogram':
        hist = pylab.histogram2d(pylab.real(values),pylab.imag(values),bins=500)
        ax.imshow(log_function(hist[0]),extent=(hist[2][0],hist[2][-1],-hist[1][-1],-hist[1][0]),interpolation='nearest')
    else:
        ax.plot(pylab.real(values),pylab.imag(values),'.')
    return fig
    


if __name__ == "__main__":
    try:
        plot_phases(sys.argv[1],*sys.argv[2:])
        pylab.show()
    except:
Exemple #21
0
pi = pl.pi
sig = pl.cos(2 * pi * 5 * t / T) + pl.sin(
    2 * pi * 15 * t / T) + pl.cos(2 * pi * 10 * t / T - pl.pi / 4)

spec = dft(sig)

pl.figure(figsize=(10, 5))
pl.subplot(221)
pl.title('Real (cosines)')
pl.ylim(-1, 1)
pl.stem(t, spec.real, 'k-', linewidth=1)
pl.subplot(222)
pl.title('Imaginary (sines)')
pl.ylim(-1, 1)
pl.stem(t, spec.imag, 'k-', linewidth=1)
pl.subplot(223)
pl.title('Magnitudes')
pl.ylim(0, 1.1)
pl.stem(t, abs(spec), 'k-', linewidth=1)
pl.subplot(224)
pl.title('Phases')
pl.ylim(0, 1.1)
j = 0
for i in abs(spec):
    if abs(i) < 0.1: spec[j] = 0 + 0j
    j += 1
pl.stem(t, pl.angle(spec), 'k-', linewidth=1)
pl.ylim(-pi, pi)
pl.tight_layout()
pl.show()
Exemple #22
0
    def calculateinitsunc(self,H,l,sigma_L = 1e-6,sigma_Theta = 1,n_exact = 1,filename=None):
        # Calculates the uncertianty on n and k according to:
        # W. Withayachumnankul, B. M. Fisher, H. Lin, D. Abbott, "Uncertainty in terahertz time-domain spectroscopy measurement", J. Opt. Soc. Am. B., Vol. 25, No. 6, June 2008, pp. 1059-1072
        #
        # sigma_L = standard uncertainty on sample thickness in meter
        # sigma_Theta = interval of sample misallignment in degree
        # n_exact = exact value of the refractive index of air during the measurements
        
        n, k = self.calculateinits(H,l)
        n = py.asarray(n)
        k = py.asarray(k)      
        
        Asam = []
        Aref = []
        Bsam = []
        Bref = []
        for i in range(len(self.H.getfreqs())):
            Asam.append((py.sum(py.imag(self.H.fdsam.getFAbs().tolist()[i]*py.exp(1j*2*py.pi*self.H.getfreqs().tolist()[i]*self.H.fdsam._tdData.getTimes()))*self.H.fdsam._tdData.getUncEX())**2))
            Aref.append((py.sum(py.imag(self.H.fdref.getFAbs().tolist()[i]*py.exp(1j*2*py.pi*self.H.getfreqs().tolist()[i]*self.H.fdref._tdData.getTimes()))*self.H.fdref._tdData.getUncEX())**2))
            Bsam.append((py.sum(py.real(self.H.fdsam.getFAbs().tolist()[i]*py.exp(1j*2*py.pi*self.H.getfreqs().tolist()[i]*self.H.fdsam._tdData.getTimes()))*self.H.fdsam._tdData.getUncEX())**2))
            Bref.append((py.sum(py.real(self.H.fdref.getFAbs().tolist()[i]*py.exp(1j*2*py.pi*self.H.getfreqs().tolist()[i]*self.H.fdref._tdData.getTimes()))*self.H.fdref._tdData.getUncEX())**2))
        
        # Uncertainty on n
        sn_Esam_2 = ((c/(2*py.pi*self.H.getfreqs()*l))**2 * py.asarray(Asam)/self.H.fdsam.getFAbs()**4)/self.H.fdsam._tdData.numberOfDataSets
        sn_Eref_2 = ((c/(2*py.pi*self.H.getfreqs()*l))**2 * py.asarray(Aref)/self.H.fdref.getFAbs()**4)/self.H.fdref._tdData.numberOfDataSets
        sn_l_2 = ((n-self.n_0)*sigma_L/l)**2
        #sn_l_2_1 = (c*self.H.getFPh()/(2*py.pi*self.H.getfreqs()*l*l))**2 * sigma_L**2
        #sn_H_2 = (c/(2*py.pi*self.H.getfreqs()*l))**2 * self.H.getFPhUnc()**2
        fn_Theta = (n-self.n_0.real)*(1/py.cos(sigma_Theta*py.pi/180)-1)
        fn_H = (c/(2*py.pi*self.H.getfreqs()*l))*py.absolute(-py.angle(4*(n-1j*k)*self.n_0/(n-1j*k+self.n_0)**2))
        fn_FP = (c/(2*py.pi*self.H.getfreqs()*l))*py.absolute(-py.angle(1/(1-((n-1j*k-self.n_0)/(n-1j*k+self.n_0))**2*py.exp(-2*1j*(n-1j*k)*2*py.pi*self.H.getfreqs()*l/c))))
        fn_n0 = abs(self.n_0.real - n_exact)*py.ones(len(self.H.getFPh()))
        u_n = py.sqrt(sn_l_2+sn_Esam_2+sn_Eref_2)+fn_Theta+fn_H+fn_FP+fn_n0

        # Uncertianty on k
        sk_Esam_2 = ((c/(2*py.pi*self.H.getfreqs()*l))**2 *(Bsam/self.H.fdsam.getFAbs()**4 + ((n-self.n_0)/(n+self.n_0))**2 * sn_Esam_2/n**2))/self.H.fdsam._tdData.numberOfDataSets
        sk_Eref_2 = ((c/(2*py.pi*self.H.getfreqs()*l))**2 *(Bref/self.H.fdref.getFAbs()**4 + ((n-self.n_0)/(n+self.n_0))**2 * sn_Eref_2/n**2))/self.H.fdref._tdData.numberOfDataSets
        sk_l_2 = (k*sigma_L/l)**2 + (c*(n-self.n_0)/((n+self.n_0)*n*2*py.pi*self.H.getfreqs()*l))**2*sn_l_2
        #sk_l_2_1 = ((c/(2*py.pi*self.H.getfreqs()*l*l))*py.log(self.H.getFAbs()*(n+self.n_0.real)**2/(4*n*self.n_0.real)))**2 * sigma_L**2
        #sk_H_2 = (-c/(2*py.pi*self.H.getfreqs()*l*self.H.getFAbs()))**2 * self.H.getFAbsUnc()**2
        fk_Theta = k*(1/py.cos(sigma_Theta*py.pi/180)-1)+c*(n-self.n_0.real)*fn_Theta/(n*2*py.pi*self.H.getfreqs()*l*(n+self.n_0.real))
        fk_H = (c/(2*py.pi*self.H.getfreqs()*l))*(py.log(py.absolute(n/(n-1j*k)*((n-1j*k+self.n_0.real)/(n+self.n_0.real))**2))+py.absolute(fn_H)*(n-self.n_0.real)/(n*(n+self.n_0.real)))
        fk_FP = (c/(2*py.pi*self.H.getfreqs()*l))*(py.absolute(-py.log(py.absolute(1/(1-((n-1j*k-self.n_0)/(n-1j*k+self.n_0))**2*py.exp(-2*1j*(n-1j*k)*2*py.pi*self.H.getfreqs()*l/c)))))+py.absolute(fn_FP)*(n-self.n_0.real)/(n*(n+self.n_0.real)))
        fk_n0 = (c/(2*py.pi*self.H.getfreqs()*l))*(n-self.n_0.real)*(self.n_0.real - n_exact)/(n*self.n_0.real)
        u_k = py.sqrt(sk_l_2+sk_Esam_2+sk_Eref_2)+fk_Theta+fk_H+fk_FP+fk_n0
        
        # Convert n in epsilon Epsilon = Epsilon_1 + j Epsilon_2 = (n+jk)**2
        # Epsilon_1 = n**2 - k**2
        # Epsilon_2 = -2nk
        Epsilon_1 = n**2 - k **2
        Epsilon_2 = -2 * n * k
        u_Epsilon_1 = py.sqrt((2*n*u_n)**2 + (-2*k*u_k)**2)
        u_Epsilon_2 = py.sqrt((-2*k*u_n)**2 + (-2*n*u_k)**2)
        
        # Calculate absorption coefficient
        # alpha = 4 * pi * k * f / c1
        alpha = 4 * py.pi * k * self.H.getfreqs() / (100 * c)      # in cm^-1
        u_alpha = 4 * py.pi * u_k * self.H.getfreqs() / (100 * c)  # in cm^-1
        
        # Calculate maximum measurable absorption coefficient according to
        # P. U. Jepsen and B. M. Fisher: "Dynamic Range in terahertz time-domain transmission and reflection spectroscopy", Optics Letters, Vol. 30, n. 1, pp. 29-31, Jan 2005
        
        alpha_max = 2 * py.log((self.H.fdsam.getDR() * 4 * n)/(n + 1)**2) / (100 * l) # in cm^-1
        
        # Save results into a table accessible from outside
        self.n_with_unc=py.real(py.column_stack((
        self.H.getfreqs(),                            # frequencies
        n, k,                                         # real and imaginary part of n
        u_n, u_k,                                     # k=1 combined uncertainty on n and k
        py.sqrt(sn_l_2), py.sqrt(sn_Esam_2), py.sqrt(sn_Eref_2), fn_Theta, fn_H, fn_FP, fn_n0, # Uncertainty components of n due to thickness, H, sample misallignment, k<<<, Neglect FP, ref ind of air
        py.sqrt(sk_l_2), py.sqrt(sk_Esam_2), py.sqrt(sk_Eref_2), fk_Theta, fk_H, fk_FP, fk_n0, # Uncertainty components of k due to thickness, H, sample misallignment, k<<<, Neglect FP, ref ind of air
        Epsilon_1, Epsilon_2,                         # Real and imaginary part of Epsilon
        u_Epsilon_1, u_Epsilon_2,                     # k = 1 uncertainty on the real and imaginary part of Epsilon
        alpha, u_alpha,                               # Absorption coefficient and its k = 1 uncertainty
        alpha_max,                                     # Maximum measurable absorption coefficient
        )))
        return
Exemple #23
0
   return sig/N

def dft(s):
   N = len(s)
   out = pl.zeros(N)*1j;
   for k in range(0,N):
    for t in range(0,N):
      out[k] += s[t]*(pl.cos(2*pl.pi*k*t/N)
                     - 1j*pl.sin(2*pl.pi*k*t/N))
   return out/N

T = 100
saw = pl.zeros(T)
t  = pl.arange(0,T)
N = T // 2 
for k in range(1,N):
    saw += (1/k)*pl.sin(2*pl.pi*k*t/T)
saw += 0.001 + 0.001*pl.cos(pl.pi*t/T)
saw *= 2/(pl.pi)    

spec = dft(saw)
print(abs(spec[0]))
phs = pl.angle(spec)

pl.figure(figsize=(8,3))
pl.stem(t,phs, 'k-', linewidth=1)
pl.ylim(-pl.pi-0.5, +pl.pi+0.5)
pl.tight_layout()
pl.show()

Exemple #24
0
def xyamb(xytab, qu, xyout=''):

    mytb = taskinit.tbtool()

    if not isinstance(qu, tuple):
        raise Exception, 'qu must be a tuple: (Q,U)'

    if xyout == '':
        xyout = xytab
    if xyout != xytab:
        os.system('cp -r ' + xytab + ' ' + xyout)

    QUexp = complex(qu[0], qu[1])
    print 'Expected QU = ', qu  # , '  (',pl.angle(QUexp)*180/pi,')'

    mytb.open(xyout, nomodify=False)

    QU = mytb.getkeyword('QU')['QU']
    P = pl.sqrt(QU[0, :]**2 + QU[1, :]**2)

    nspw = P.shape[0]
    for ispw in range(nspw):
        st = mytb.query('SPECTRAL_WINDOW_ID==' + str(ispw))
        if (st.nrows() > 0):
            q = QU[0, ispw]
            u = QU[1, ispw]
            qufound = complex(q, u)
            c = st.getcol('CPARAM')
            fl = st.getcol('FLAG')
            xyph0 = pl.angle(pl.mean(c[0, :, :][pl.logical_not(fl[0, :, :])]),
                             True)
            print 'Spw = ' + str(ispw) + ': Found QU = ' + str(
                QU[:, ispw])  # +'   ('+str(pl.angle(qufound)*180/pi)+')'
            #if ( (abs(q)>0.0 and abs(qu[0])>0.0 and (q/qu[0])<0.0) or
            #     (abs(u)>0.0 and abs(qu[1])>0.0 and (u/qu[1])<0.0) ):
            if (pl.absolute(pl.angle(qufound / QUexp) * 180 / pi) > 90.0):
                c[0, :, :] *= -1.0
                xyph1 = pl.angle(
                    pl.mean(c[0, :, :][pl.logical_not(fl[0, :, :])]), True)
                st.putcol('CPARAM', c)
                QU[:, ispw] *= -1
                print '   ...CONVERTING X-Y phase from ' + str(
                    xyph0) + ' to ' + str(xyph1) + ' deg'
            else:
                print '      ...KEEPING X-Y phase ' + str(xyph0) + ' deg'
            st.close()
    QUr = {}
    QUr['QU'] = QU
    mytb.putkeyword('QU', QUr)
    mytb.close()
    QUm = pl.mean(QU[:, P > 0], 1)
    QUe = pl.std(QU[:, P > 0], 1)
    Pm = pl.sqrt(QUm[0]**2 + QUm[1]**2)
    Xm = 0.5 * atan2(QUm[1], QUm[0]) * 180 / pi

    print 'Ambiguity resolved (spw mean): Q=', QUm[0], 'U=', QUm[
        1], '(rms=', QUe[0], QUe[1], ')', 'P=', Pm, 'X=', Xm

    stokes = [1.0, QUm[0], QUm[1], 0.0]
    print 'Returning the following Stokes vector: ' + str(stokes)

    return stokes
Exemple #25
0
ti = int(ts*H)
scal = 3*D/4

def plock(phs):
    N = len(phs)
    x = p2r(pl.ones(N),phs) 
    y = pl.zeros(N)+0j
    y[0], y[N-1] = x[0], x[N-1]          
    for i in range(1,N-1):
       y[i] = x[i] - (x[i-1] + x[i+1])
    return y

for n in range(0,L-(N+H),ti):
    X1 = stft(signal[n:n+N],win)
    X2 = stft(signal[n+H:n+H+N],win)
    diffs = pl.angle(X2) - pl.angle(X1)
    phs += diffs
    Y = p2r(abs(X2),phs)                         
    output[np:np+N] += istft(Y,win)
    phs = pl.angle(plock(phs))
    np += H
  
output = pl.array(output*zdbfs/scal,dtype='int16')
wf.write(sys.argv[3],sr,output)

import os
try:
 os.spawnlp(os.P_WAIT, 'sndfile-play', 'sndfile-play', sys.argv[3])
except:
 pass
Exemple #26
0
L2 = len(in2)
if L2 > L1: L = L2
else: L = L1
signal1 = pl.zeros(L)
signal2 = pl.zeros(L)
signal1[:len(in1)] = in1 / zdbfs
signal2[:len(in2)] = in2 / zdbfs
output = pl.zeros(L)
win = pl.hanning(N)
scal = 1.5 * D / 4

for n in range(0, L, H):
    if (L - n < N): break
    frame1 = stft(signal1[n:n + N], win, n)
    frame2 = stft(signal2[n:n + N], win, n)
    mags = abs(frame1)
    env1 = spec_env(frame1, 20)
    env2 = spec_env(frame2, 20)
    phs = pl.angle(frame1)
    if (min(env1) > 0):
        frame = p2r(mags * env2 / env1, phs)
    else:
        frame = p2r(mags * env2, phs)
    output[n:n + N] += istft(frame, win, n)

a = max(signal1)
b = max(output)
c = a / b
output = pl.array(output * zdbfs * c / scal, dtype='int16')
wf.write(sys.argv[3], sr, output)
Exemple #27
0
H = N//D
zdbfs = 32768
(sr,signal) = wf.read(sys.argv[2])
signal = signal/zdbfs
L = len(signal)
win = pl.hanning(N)
phs = pl.zeros(N//2+1)
np = 0
ts = float(sys.argv[1])
output = pl.zeros(int(L/ts)+N)
ti = int(ts*H)
scal = 3*D/4

for n in range(0,L-(N+H),ti):
    X1 = stft(signal[n:n+N],win)
    X2 = stft(signal[n+H:n+H+N],win)
    diffs = pl.angle(X2) - pl.angle(X1)
    phs += diffs
    Y = p2r(abs(X2),phs)                              
    output[np:np+N] += istft(Y,win)
    np += H
  
output = pl.array(output*zdbfs/scal,dtype='int16')
wf.write(sys.argv[3],sr,output)

import os
try:
 os.spawnlp(os.P_WAIT, 'sndfile-play', 'sndfile-play', sys.argv[3])
except:
 pass