Esempio n. 1
0
    def computeFilterResponse(self):
        N = int(100 * self.samplingRate)

        noise = numpy.zeros(N)
        freq = numpy.fft.fftfreq(N, 1.0 / self.samplingRate)

        for i in range(N):
            noise[i] = random.random() - 0.5

        fftN = numpy.fft.fft(noise)[list(range(N / 2))]
        fftS = numpy.fft.fft(self.applyFilter(noise))[list(range(N / 2))]
        fftNA = abs(fftN)
        fftSA = abs(fftS)
        fftP = angle(fftS) - angle(fftN)

        Niter = 100
        for i in range(1, Niter):
            for i in range(N):
                noise[i] = random.random() - 0.5

            fftN = numpy.fft.fft(noise)[list(range(N / 2))]
            fftS = numpy.fft.fft(self.applyFilter(noise))[list(range(N / 2))]
            fftNA += abs(fftN)
            fftSA += abs(fftS)
            fftP += (angle(fftS) - angle(fftN))

        return freq[list(range(N /
                               2))], fftSA / Niter, fftNA / Niter, fftP / Niter
Esempio n. 2
0
def angle(x):
    # Wrapper for angle that handles CXData objects
    if isinstance(x, CXData):
        l=[]
        for i in xrange(len(x)):
            l.append(sp.angle(x.data[i]))

        return CXData(data=l)
    elif isinstance(x, np.ndarray):
        return sp.angle(x)
    else:
        raise Exception('Unknown data type passed to angle')
Esempio n. 3
0
def angle(x):
    # Wrapper for angle that handles CXData objects
    if isinstance(x, CXData):
        l = []
        for i in xrange(len(x)):
            l.append(sp.angle(x.data[i]))

        return CXData(data=l)
    elif isinstance(x, np.ndarray):
        return sp.angle(x)
    else:
        raise Exception('Unknown data type passed to angle')
Esempio n. 4
0
def symmetrydemo():
    a = sin(linspace(-5 * pi, 5 * pi, 10000))
    b = a + 2
    c = a - 0.5
    ah, bh, ch = hilbert(a), hilbert(b), hilbert(c)
    ph_a, ph_b, ph_c = unwrap(angle(ah)), unwrap(angle(bh)), unwrap(angle(ch))
    omega_a = diff(ph_a)
    omega_b = diff(ph_b)
    omega_c = diff(ph_c)
    subplot(211), plot(ph_a), plot(ph_b), plot(ph_c)
    subplot(212), plot(omega_a), plot(omega_b), plot(omega_c)
    grid()
    show()
    return a, b, c
Esempio n. 5
0
def symmetrydemo():
    a=sin(linspace(-5*pi,5*pi,10000))
    b=a+2
    c=a-0.5
    ah,bh,ch=hilbert(a),hilbert(b),hilbert(c)
    ph_a,ph_b,ph_c=unwrap(angle(ah)),unwrap(angle(bh)),unwrap(angle(ch))
    omega_a=diff(ph_a)
    omega_b=diff(ph_b)
    omega_c=diff(ph_c)
    subplot(211),plot(ph_a),plot(ph_b),plot(ph_c)
    subplot(212),plot(omega_a),plot(omega_b),plot(omega_c)
    grid()
    show()
    return a,b,c
Esempio n. 6
0
def inst_freq(x, t=None):
    """
    Compute the instantaneous frequency of an analytic signal at specific time
    instants using the trapezoidal integration rule.
    Parameters
    ----------
    x : array-like, shape (n_samples,)
        The input analytic signal.
    t : array-like, shape (n_samples,), optional
        The time instants at which to calculate the instantaneous frequency.
        Defaults to `np.arange(2, n_samples)`
    Returns
    -------
    array-like
        Normalized instantaneous frequencies of the input signal
    Examples
    --------
    """
    if x.ndim != 1:
        if 1 not in x.shape:
            raise TypeError("Input should be a one dimensional array.")
        else:
            x = x.ravel()
    if t is not None:
        if t.ndim != 1:
            if 1 not in t.shape:
                raise TypeError("Time instants should be a one dimensional "
                                "array.")
            else:
                t = t.ravel()
    else:
        t = np.arange(2, len(x))

    fnorm = 0.5 * (angle(-x[t] * np.conj(x[t - 2])) + np.pi) / (2 * np.pi)
    return fnorm, t
Esempio n. 7
0
def csr3(complex_n):
    ang = sp.angle(complex_n) # sp.arctan(a.imag/a.real) why it does not work?!?!
    r = sp.sqrt(sp.square(complex_n.real)+sp.square(complex_n.imag))
    if (sp.sin(ang/2)>=0): #sin>0
        return sp.sqrt(r)*(complex(sp.cos(ang/2),sp.sin(ang/2)))
    else:
        return sp.sqrt(r)*(complex(sp.cos((ang/2)+sp.pi),sp.sin((ang/2)+sp.pi)))
Esempio n. 8
0
 def get_fft(self, fs, taps, Npts):
     Ts = 1.0/fs
     fftpts = fftpack.fft(taps, Npts)
     self.freq = scipy.arange(0, fs, 1.0/(Npts*Ts))        
     self.fftdB = 20.0*scipy.log10(abs(fftpts))
     self.fftDeg = scipy.unwrap(scipy.angle(fftpts))
     self.groupDelay = -scipy.diff(self.fftDeg)
Esempio n. 9
0
def plot_freqz(b, a, w = None, npoints = None, title = '', db = False, createFigure = True, label = ''):
    # Create the omega array if necessary
    if npoints is None:
        npoints = 1000

    if w is None:
        w = scipy.arange(-scipy.pi, scipy.pi, 2*scipy.pi/(npoints))

    # Calculate the frequency response
    d = loudia.freqz(b.T, a.T, w)

    if db:
        mag = 20.0 * scipy.log10(abs(d[:,0]))
    else:
        mag = abs(d[:,0])

    import pylab
    if createFigure:
        pylab.figure()
        
    pylab.subplot(2,1,1)
    pylab.plot(w, mag, label = label)
    pylab.title('%s \n Magnitude of the Frequency Response' % title)

    pylab.subplot(2,1,2)
    pylab.plot(w, scipy.angle(d[:,0]), label = label)
    pylab.title('Angle of the Frequency Response')
Esempio n. 10
0
def plot_freqz(b,
               a,
               w=None,
               npoints=None,
               title='',
               db=False,
               createFigure=True,
               label=''):
    # Create the omega array if necessary
    if npoints is None:
        npoints = 1000

    if w is None:
        w = scipy.arange(-scipy.pi, scipy.pi, 2 * scipy.pi / (npoints))

    # Calculate the frequency response
    d = loudia.freqz(b.T, a.T, w)

    if db:
        mag = 20.0 * scipy.log10(abs(d[:, 0]))
    else:
        mag = abs(d[:, 0])

    import pylab
    if createFigure:
        pylab.figure()

    pylab.subplot(2, 1, 1)
    pylab.plot(w, mag, label=label)
    pylab.title('%s \n Magnitude of the Frequency Response' % title)

    pylab.subplot(2, 1, 2)
    pylab.plot(w, scipy.angle(d[:, 0]), label=label)
    pylab.title('Angle of the Frequency Response')
Esempio n. 11
0
def ACphase(tf, unit='deg', unwrapTol=0.5):
	"""
	Return the phase in desired *unit* of a transfer function *tf*
	
	* ``deg`` stands for degrees
	* ``rad`` stands for radians
	
	The phase is unwrapped (discontinuities are stiched together to make it 
	continuous). The tolerance of the unwrapping (in radians) is 
	*unwrapTol* times ``pi``. 
	"""
	# Get argument
	ph=angle(tf)
	
	# Unwrap if requested
	if (unwrapTol>0) and (unwrapTol<1):
		ph=unwrap(ph, unwrapTol*pi)
	
	# Convert to requested unit
	if unit=='deg':
		return ph/pi*180.0
	elif unit=='rad':
		return ph
	else:
		raise Exception, "Bad phase unit."
Esempio n. 12
0
 def test_phasez_1(self):
     # Testcase for return radian form
     fil = FIRDesign.fir1(self.order, self.cut)
     w, h = signal.freqz(fil[0], fil[1], worN=512, fs=2 * np.pi)
     phase = sp.unwrap(sp.angle(h))
     ww, pp = FilterSpec.phasez(fil)
     self.assertTrue(np.all(w == ww) and np.all(pp == phase))
Esempio n. 13
0
def ACphase(tf, unit='deg', unwrapTol=0.5):
    """
	Return the phase in desired *unit* of a transfer function *tf*
	
	* ``deg`` stands for degrees
	* ``rad`` stands for radians
	
	The phase is unwrapped (discontinuities are stiched together to make it 
	continuous). The tolerance of the unwrapping (in radians) is 
	*unwrapTol* times ``pi``. 
	"""
    # Get argument
    ph = angle(tf)

    # Unwrap if requested
    if (unwrapTol > 0) and (unwrapTol < 1):
        ph = unwrap(ph, unwrapTol * pi)

    # Convert to requested unit
    if unit == 'deg':
        return ph / pi * 180.0
    elif unit == 'rad':
        return ph
    else:
        raise Exception, "Bad phase unit."
Esempio n. 14
0
def phase(abc, deg=False):
    """
    return the (sine-)phase given the coefficients of\n
    y = a*sin(2*pi*f0*t) + b*cos(2*pi*f0*t) + c \n
    returns angle in rad by default, in degree if deg=True
    """
    return sp.angle(abc[1] + 1j * abc[0], deg=deg)
Esempio n. 15
0
def mmse_stsa(infile, outfile, noise_sum):
    signal, params = read_signal(infile, WINSIZE)
    nf = len(signal)/(WINSIZE/2) - 1
    sig_out=sp.zeros(len(signal),sp.float32)

    G = sp.ones(WINSIZE)
    prevGamma = G
    alpha = 0.98
    window = sp.hanning(WINSIZE)
    gamma15=spc.gamma(1.5)
    lambdaD = noise_sum / 5.0
    percentage = 0
    for no in xrange(nf):
        p = int(math.floor(1. * no / nf * 100))
        if (p > percentage):
            percentage = p
            print "{}%".format(p),

        y = get_frame(signal, WINSIZE, no)
        Y = sp.fft(y*window)
        Yr = sp.absolute(Y)
        Yp = sp.angle(Y)
        gamma = Yr**2/lambdaD
        xi = alpha * G**2 * prevGamma + (1-alpha)*sp.maximum(gamma-1, 0)
        prevGamma = gamma
        nu = gamma * xi / (1+xi)
        G = (gamma15 * sp.sqrt(nu) / gamma ) * sp.exp(-nu/2) * ((1+nu)*spc.i0(nu/2)+nu*spc.i1(nu/2))
        idx = sp.isnan(G) + sp.isinf(G)
        G[idx] = xi[idx] / (xi[idx] + 1)
        Yr = G * Yr
        Y = Yr * sp.exp(Yp*1j)
        y_o = sp.real(sp.ifft(Y))
        add_signal(sig_out, y_o, WINSIZE, no)
    
    write_signal(outfile, params, sig_out)
 def get_fft(self, fs, taps, Npts):
     Ts = 1.0 / fs
     fftpts = fftpack.fft(taps, Npts)
     self.freq = scipy.arange(0, fs, 1.0 / (Npts * Ts))
     self.fftdB = 20.0 * scipy.log10(abs(fftpts))
     self.fftDeg = scipy.unwrap(scipy.angle(fftpts))
     self.groupDelay = -scipy.diff(self.fftDeg)
Esempio n. 17
0
def pulse_phase_thermography(thermogram,
                             frames_to_process=-1,
                             frame_start=0,
                             return_phase=1):
    """ Expects a thermogram as a u_int16 3D numpy multdimensional array where
    each dimension is: [frame, row, column]. 
    frames_to_process sets the numbers of frames to use in FFT analysis, uses all frames
    by default.
    Return_phase controls what phase will be returned, 0 is always a blank map;
    should almost always be 1.
    Returns an array of 2D phase maps in the format: [frame_index, row, column]
    """

    yLength = thermogram.shape[1]
    #Note that y is before x; a carry over from
    xLength = thermogram.shape[2]
    # Matlab...
    #Preallocate phase maps
    phasemap = numpy.zeros([1, yLength, xLength], dtype=numpy.complex64)

    # Perform FFT over the range specified
    fftmap = scipy.fft(thermogram[frame_start:frame_start +
                                  frames_to_process, :, :],
                       axis=0)
    phasemap[0, :, :] = scipy.angle(fftmap[return_phase, :, :])

    return phasemap
Esempio n. 18
0
    def redraw(self):
        self.clearStems()

        for i in range(0, 3):
            axes = pylab.subplot('13' + str(1 + i))
            if (self.mode == "phase"):
                self.plots[i][0].set_ydata(
                    scipy.angle(self.fts[self.index + i]))
            else:
                mag = abs(self.fts[self.index + i])
                self.plots[i][0].set_ydata(mag)
                peak = max(mag)
                peakInd = list(mag).index(peak)
                stem_marker, stem_lines, stem_base = pylab.stem([peakInd],
                                                                [peak], 'r-',
                                                                'ro')
                self.stemMarkers.append(stem_marker)
                self.stemBase.append(stem_base)
                self.stemLines.append(stem_lines)
                xres = self.fov / self.xsize
                pylab.xlabel(self.axis[i] + ':' +
                             '{0:.3}'.format(xres *
                                             (peakInd - len(mag) / 2)) + ' mm')

            pylab.draw()
Esempio n. 19
0
def timescale(data, scaling=1):
    """Scales the playback_duration of input_filename, while keeping pitch constant."""
    length = len(data)

    phi = scipy.zeros(N)
    out = scipy.zeros(N, dtype=complex)
    sigout = scipy.zeros(length / scaling + N)

    amplitude = max(data)
    window = scipy.hanning(N)

    for index in scipy.arange(0, length - (N + H), H * scaling):
        spec1 = scipy.fft(window * data[index:index + N])
        spec2 = scipy.fft(window * data[index + H:index + N + H])

        phi += scipy.angle(spec2 / spec1)
        phi %= 2 * scipy.pi

        out.real, out.imag = scipy.cos(phi), scipy.sin(phi)

        out_index = int(index / scaling)
        sigout[out_index:out_index +
               N] += (window * scipy.ifft(scipy.absolute(spec2) * out)).real

    sigout *= amplitude / max(sigout)
    return scipy.array(sigout, dtype='int16')
Esempio n. 20
0
def floquet_modes(H, T, args=None, sort=False):
    """
    Calculate the initial Floquet modes Phi_alpha(0) for a driven system with
    period T.
    
    Returns a list of :class:`qutip.Qobj` instances representing the Floquet
    modes and a list of corresponding quasienergies, sorted by increasing
    quasienergy in the interval [-pi/T, pi/T]. The optional parameter `sort`
    decides if the output is to be sorted in increasing quasienergies or not.

    Parameters
    ----------
    
    H : :class:`qutip.Qobj`
        system Hamiltonian, time-dependent with period `T`
        
    args : dictionary
        dictionary with variables required to evaluate H
     
    T : float
        The period of the time-dependence of the hamiltonian. The default value
        'None' indicates that the 'tlist' spans a single period of the driving.
     
    Returns
    -------

    output : list of kets, list of quasi energies

        Two lists: the Floquet modes as kets and the quasi energies.

    """

    # get the unitary propagator
    U = propagator(H, T, [], args)

    # find the eigenstates for the propagator
    evals,evecs = la.eig(U.full())

    eargs = angle(evals)
    
    # make sure that the phase is in the interval [-pi, pi], so that the
    # quasi energy is in the interval [-pi/T, pi/T] where T is the period of the
    # driving.
    #eargs  += (eargs <= -2*pi) * (2*pi) + (eargs > 0) * (-2*pi)
    eargs  += (eargs <= -pi) * (2*pi) + (eargs > pi) * (-2*pi)
    e_quasi = -eargs/T

    # sort by the quasi energy
    if sort == True:
        order = np.argsort(-e_quasi)
    else:
        order = list(range(len(evals)))

    # prepare a list of kets for the floquet states
    new_dims  = [U.dims[0], [1] * len(U.dims[0])]
    new_shape = [U.shape[0], 1]
    kets_order = [Qobj(np.matrix(evecs[:,o]).T, dims=new_dims, shape=new_shape) for o in order]

    return kets_order, e_quasi[order]
Esempio n. 21
0
def multi_phase(abc, deg=False):  # abc = [bias, a1,b1 , a2,b2, ...]
    """
    return the initial phases given the coefficients of a multi-sine\n
    abc = [a1,b1 , a2,b2, ...,bias] \n
    y = sum_i (a_i*sin(2*pi*f0_i*t) + b_i*cos(2*pi*f0_i*t) + c_i
    """
    x = abc[1::2] + 1j * abc[2::2]
    return sp.angle(x, deg=deg)
Esempio n. 22
0
def getinstfreq(imfs):
    omega = zeros((imfs.shape[0], imfs.shape[1] - 1), dtype=float)
    for i in range(imfs.shape[0]):
        h = hilbert(imfs[i, :])
        theta = unwrap(angle(h))
        omega[i, :] = diff(theta)

    return omega
Esempio n. 23
0
def getinstfreq(imfs):
    omega=zeros((imfs.shape[0],imfs.shape[1]-1),dtype=float)
    for i in range(imfs.shape[0]):
        h=hilbert(imfs[i,:])
        theta=unwrap(angle(h))
        omega[i,:]=diff(theta)
        
    return omega
Esempio n. 24
0
def getinstfreq(imfs):
    # print 'freq:'
    omega = zeros((imfs.shape[0], imfs.shape[1]), dtype=float)
    for i in range(imfs.shape[0]):
        h = hilbert(imfs[i, :])
        theta = unwrap(angle(h))
        omega[i, 0:diff(theta).shape[0]] = diff(theta)
    # print 'freq:',np.shape(omega)
    return omega
Esempio n. 25
0
 def phase(self, degrees=False):
     '''
     Return an array of the phase angles of the wavelet coefficients,
     in radians (set degrees=True for degrees).
     '''
     phase = sp.angle(self.wave)
     if degrees:
         phase *= 180 / sp.pi
     return phase
Esempio n. 26
0
 def phase(self, degrees=False):
     '''
     Return an array of the phase angles of the wavelet coefficients,
     in radians (set degrees=True for degrees).
     '''
     phase = sp.angle(self.wave)
     if degrees:
         phase *= 180 / sp.pi
     return phase
def process_image(thermogram, return_phase=1):
    ''' Expects a thermogram as a u_int16 3D numpy multdimensional array where
    each dimension is: [frame, row, column]. Return_phase controls 
    what phase will be returned, 0 is always a blank map; should almost
    always be 1.
    Returns a 2D phase map in the format: [row, column]    
    '''
    fftmap = scipy.fft(thermogram, axis=0)
    phasemap = scipy.angle(fftmap[return_phase, :, :])
    return phasemap
 def compute_by_noise_pow(self,signal,n_pow):
     s_spec = sp.fft(signal*self._window)
     s_amp = sp.absolute(s_spec)
     s_phase = sp.angle(s_spec)
     amp = s_amp**2.0 - n_pow*self._coefficient
     amp = sp.maximum(amp,0.0)
     amp = sp.sqrt(amp)
     amp = self._ratio*amp + (1.0-self._ratio)*s_amp
     spec = amp * sp.exp(s_phase*1j)
     return sp.real(sp.ifft(spec))
def wiener(signal, noise, window):
    n_amp = sp.absolute(sp.fft(noise *
                               window))  # Calculates noise frame amplitude
    s_spec = sp.fft(signal * window)
    s_amp = sp.absolute(s_spec)  # Calculates signal frame amplitude
    s_phase = sp.angle(s_spec)  # Calculates signal frame phase

    out_spec = s_spec * ((s_amp**2) - 0.7 *
                         (n_amp**2)) / (s_amp**2)  # Performs wiener filtering
    return sp.real(sp.ifft(out_spec))  # Returns ifft
Esempio n. 30
0
    def __filter(self, im, mysize=None, noise=None):
        """
        Perform a noise filter on 1-dimensional array `im`.
        Parameters
        ----------
        im : ndarray
            An 1-dimensional array.
        mysize : int, optional
            A scalar giving the size of the Wiener filter window. It should be
            odd.
        noise : noise
        """
        im = np.asarray(im)
        if mysize is None:
            mysize = 3

        substraction_coeff = 5.0
        w = scipy.hanning(mysize)

        n_spec = scipy.fft(noise.signal[:mysize] * w)
        n_pow = scipy.absolute(n_spec)**2.0

        hopsamp = mysize / 2
        frames = np.array([
            scipy.fft(w * self.signal[i:i + mysize])
            for i in range(0, self.nsamples - mysize, hopsamp)
        ])

        # plt.figure()
        # plt.plot([sum(f) for f in frames])
        # plt.show()
        # new = np.zeros_like(frames)
        # for i, f in enumerate(frames):
        # # Estimate the local mean
        # lMean = scipy.signal.correlate(f, w, 'same') / mysize
        #
        # # Estimate the local variance
        # lVar = (scipy.signal.correlate(f ** 2, w ** 2, 'same') / mysize
        #         - lMean ** 2)
        #
        # res = lMean + (f - lMean)*(1 - noise / lVar)
        # new[i] = np.where(lVar < noise, lMean, res)

        n = sum(n_pow) / len(n_pow)
        y = scipy.absolute(frames)**2
        new = scipy.sqrt(scipy.maximum(y - substraction_coeff * n, 0.0))
        new = new / (1 - float(len(y.flatten()) * n) / sum(y.flatten()))
        new = new * scipy.exp(scipy.angle(frames) * 1j)

        x = np.zeros(self.nsamples)
        framesamp = new.shape[1]
        hopsamp = framesamp / 2
        for n, i in enumerate(range(0, self.nsamples - framesamp, hopsamp)):
            x[i:i + framesamp] += scipy.real(scipy.ifft(new[n]))
        return x
Esempio n. 31
0
def steady_state_response(zs, rmin, rmax):
    """
    Returns a plot with the steady state response of a
    single degree of freedom damped system.

    Parameters
    ----------
    zs: array
        Array with the damping values
    rmin, rmax: float
        Minimum and maximum frequency ratio

    Returns
    ----------
    r: Array
        Array containing the values for the frequency ratio
    A: Array
        Array containing the values for anmplitude

        Plot with steady state magnitude and phase

    Examples:
    >>> r, A = steady_state_response([0.1, 0.3, 0.8], 0, 2)
    >>> A[10]
    (0.98423159842039087-0.15988334018879749j)
    """

    if not isinstance(zs, list):
        zs = [zs]
    r = sp.linspace(rmin, rmax, 100*(rmax-rmin))
    A0 = sp.zeros((len(zs), len(r)), complex)
    for z in enumerate(zs):
        A0[z[0]] = (1/(1 - r**2 + 2*1j*r*z[1]))

    fig = plt.figure()
    ax1 = fig.add_subplot(211)
    ax2 = fig.add_subplot(212, sharex=ax1)
    plt.tight_layout()

    ax1.set_ylabel('Normalized Amplitude (dB)')
    ax1.set_title('Normalized Amplitude vs Frequency Ratio')

    ax2.set_xlabel('Frequency Ratio')
    ax2.set_ylabel('Phase Lag (deg)')
    ax2.set_title('Phase vs Frequency Ratio')

    for A in A0:
        ax1.plot(r, (sp.absolute(A)))
        ax2.plot(r, -sp.angle(A)/sp.pi*180)

    ax1.legend((['$\zeta$ = ' + (str(s)) for s in zs]))

    _ = plt.show()

    return r, A
Esempio n. 32
0
    def init_data(self, *args, **kwargs):

        if args[0] == 'det_mod':
            if CXP.actions.preprocess_data:
                self.read_in_data()
            else:
                self.load()

        elif args[0] == 'probe_det_mod':
            if CXP.actions.preprocess_data:
                #  Get list of white files
                CXP.log.info('Preprocessing probe detector modulus.')
                if CXP.io.whitefield_filename not in [None, '']: # If whitefields were measured

                    wfilename, wfilerange, wn_acqs = [CXP.io.whitefield_filename, CXP.io.whitefield_filename_range,
                                                      CXP.measurement.n_acqs_whitefield]
                    self.pattern = wfilename.count('{')
                    if self.pattern == 1:
                        wf = [wfilename.format(i) for i in range(wfilerange[0], wfilerange[1])]
                    elif self.pattern == 2:
                        wf = [wfilename.format(wfilerange[0], i) for i in range(wn_acqs)]
                    elif self.pattern == 3:
                        wf = glob.glob(wfilename.split('}')[0]+'}*')

                    res = self.preprocess_data_stack(0, 1, wf, self.pattern, None, None, no_decorate=True)
                    self.data = res[1]
                else: #Guesstimate the whitefield from the average of the diffraction patterns
                    pass
            else:
                self.load(CXData.raw_data_filename_string.format('probe_det_mod'))

            try:
                probe = self.__class__.__all__['probe']
                probe.data[0] = spf.ifft2(self.data[0]*exp(complex(0., 1.)*sp.angle(spf.fft2(probe.data[0]))))
                CXP.log.info('Applied probe modulus constraint.')
            except (AttributeError, KeyError):
                pass

        elif args[0] == 'dark':
            if CXP.actions.preprocess_data:
                # Get list of dark files
                CXP.log.info('Preprocessing darkfield.')
                dfilename, dfilerange, dn_acqs = [CXP.io.darkfield_filename, CXP.io.darkfield_filename_range,
                                                  CXP.measurement.n_acqs_darkfield]
                self.pattern = dfilename.count('{')
                if self.pattern == 1:
                    df = [dfilename.format(i) for i in range(dfilerange[0], dfilerange[1])]
                elif self.pattern == 2:
                    df = [dfilename.format(dfilerange[0], i) for i in range(dn_acqs)]
                elif self.pattern == 3:
                    df = glob.glob(dfilename.split('}')[0]+'}*')
                res = self.preprocess_data_stack(0, 1, df, self.pattern, None, None, no_decorate=True)
                self.data = res[1]
            else:
                self.load(CXData.raw_data_filename_string.format('probe_det_mod'))
def spec_sub(signal, noise, window):
    n_amp = sp.absolute(sp.fft(noise *
                               window))  # Calculates noise frame amplitude
    s_spec = sp.fft(signal * window)
    s_amp = sp.absolute(s_spec)  # Calculates signal frame amplitude
    s_phase = sp.angle(s_spec)  # Calculates signal frame phase

    out_amp = sp.sqrt((s_amp**2) - (n_amp**2))  # Performs spectral subtraction
    out_spec = out_amp * sp.exp(
        s_phase * 1j)  # Reconstructs spectrum using noisy phase
    return sp.real(sp.ifft(out_spec))  # Returns ifft
Esempio n. 34
0
def _griffin_lim(S):
    '''librosa implementation of Griffin-Lim
    Based on https://github.com/librosa/librosa/issues/434
    '''
    angles = sp.exp(2j * sp.pi * sp.random.rand(*S.shape))
    S_complex = np.abs(S).astype(np.complex)
    y = _istft(S_complex * angles)
    for i in range(hparams.griffin_lim_iters):
        angles = sp.exp(1j * sp.angle(_stft(y)))
        y = _istft(S_complex * angles)
    return y
Esempio n. 35
0
 def assert_is_analytic(self, signal, amlaw=None):
     """Assert that signal is analytic."""
     omega = angle(signal)
     if amlaw is not None:
         recons = np.exp(1j * omega) * amlaw
     else:
         recons = np.exp(1j * omega)
     real_identical = np.allclose(np.real(recons), np.real(signal))
     imag_identical = np.allclose(np.imag(recons), np.imag(signal))
     if not (imag_identical and real_identical):
         raise AssertionError("Signal is not analytic.")
Esempio n. 36
0
 def assert_is_analytic(self, signal, amlaw=None):
     """Assert that signal is analytic."""
     omega = angle(signal)
     if amlaw is not None:
         recons = np.exp(1j * omega) * amlaw
     else:
         recons = np.exp(1j * omega)
     real_identical = np.allclose(np.real(recons), np.real(signal))
     imag_identical = np.allclose(np.imag(recons), np.imag(signal))
     if not (imag_identical and real_identical):
         raise AssertionError("Signal is not analytic.")
Esempio n. 37
0
 def test_anaqpsk(self):
     """Test quaternary PSK signal."""
     signal, phases = ana.anaqpsk(512, 64, 0.25)
     self.assert_is_analytic(signal)
     # Count discontinuities in the signal and the phases and assert that
     # they appear in the same locations
     uphase = unwrap(angle(signal))
     dphase = np.diff(uphase)
     base_value = mode(dphase)[0][0]
     signal_phase_change = np.abs(dphase - base_value) > 0.0001
     ideal_phase_change = np.diff(phases) != 0
     np.testing.assert_allclose(signal_phase_change, ideal_phase_change)
Esempio n. 38
0
 def test_anaqpsk(self):
     """Test quaternary PSK signal."""
     signal, phases = ana.anaqpsk(512, 64, 0.25)
     self.assert_is_analytic(signal)
     # Count discontinuities in the signal and the phases and assert that
     # they appear in the same locations
     uphase = unwrap(angle(signal))
     dphase = np.diff(uphase)
     base_value = mode(dphase)[0][0]
     signal_phase_change = np.abs(dphase - base_value) > 0.0001
     ideal_phase_change = np.diff(phases) != 0
     np.testing.assert_allclose(signal_phase_change, ideal_phase_change)
Esempio n. 39
0
def phasez(system, worN: int = 512, fs=2 * np.pi, deg: bool = False) -> Tuple:
    """
    Phase response of a digital filter.
    
    Parameters
    ----------
        system : a tuple of array_like describing the system.
            The following gives the number of elements in the tuple and
            the interpretation:
                
                * (num, den)
                
        worN : {None, int, array_like}, optional
            If a single integer, then compute at that many frequencies 
            (default is N=512). This is a convenient alternative to:

                np.linspace(0, fs if whole else fs/2, N, endpoint=False)
            
            Using a number that is fast for FFT computations can result in 
            faster computations (see Notes).
            If an array_like, compute the response at the frequencies given. 
            These are in the same units as fs.
            
        fs : float, optional
            The sampling frequency of the digital system.
            Defaults to 2*pi radians/sample (so w is from 0 to pi).
            
        deg : bool, optional
            If True, the phase response is returned as degree.
            Default is False.
            
    Returns
    -------
        w : ndarray
            The frequencies at which h was computed, in the same units as fs.
            By default, w is normalized to the range [0, pi) (radians/sample).
            
        phase : ndarray
            The phase response.
    """

    # Calcurate the frequency response of the digital filter.
    w, h = freqz(system, worN=worN, fs=fs)

    # Calcurate the phase response from frequency response.
    phase = sp.unwrap(sp.angle(h))

    # If deg is True, return the phase response as degree
    if deg == True:
        phase = np.rad2deg(phase)

    return w, phase
Esempio n. 40
0
def ComplexNumToStr(val, eps=1e-12, fmt='%0.4g', polar=False, \
                    debug=0, strip_sympy=True):
    #Note that this also becomes the default class for all elements of
    #arrays, so the possibility of those elements being sympy
    #expressions or something exists.
    if debug:
        print('In ComplexNumToStr, val='+str(val))
        print('type(val)=%s' % type(val))
        test = is_sage(val)
        print('is_sage test = '+str(test))

    if hasattr(val,'ToLatex'):
        return val.ToLatex(eps=eps, fmt=fmt)
    elif is_sympy(val) or is_sage(val):
        sympy_out = sympy.latex(val, profile=sympy_profile)
        if strip_sympy:
            bad_list = ['\\begin{equation*}', \
                        '\\end{equation*}', \
                        '\\begin{equation}', \
                        '\\end{equation}', \
                        '$']
            for item in bad_list:
                sympy_out = sympy_out.replace(item,'')
        if debug:
            print('sympy_out='+sympy_out)
        return sympy_out
    val = AbsEpsilonCheck(val)#this zeros out any vals that have very small absolute values
    test = bool(isinstance(val, complex))
    #print('test = '+str(test))
    if isinstance(val, complex):
        realstr = ''
        imagstr = ''
        rpart = real(val)
        ipart = imag(val)
        if abs(ipart) < eps:
            return fmt % rpart
        elif abs(rpart) < eps:
            return fmt%ipart+'j'
        else:
            realstr = fmt % rpart
            imagstr = fmt % ipart+'j'
            if ipart > 0:
                rectstr = realstr+'+'+imagstr
            else:
                rectstr = realstr+imagstr
            outstr = rectstr
            if polar:
                polarstr = fmt%abs(val) + '  \\angle '+fmt%angle(val,1)+'^\\circ'
                outstr += ' \\; \\textrm{or} \\; ' +polarstr
            return outstr
    else:
        return fmt % val
Esempio n. 41
0
def plv(x, y, identities):
    """Function for computing phase-locking values between x and y.

    Output arguments:
    =================
    cplv : ndarray
        Complex-valued phase-locking values.
    """
    """Change to amplitude 1, keep angle using Euler's formula."""
    x = scipy.exp(1j * (asmatrix(scipy.angle(x))))
    y = scipy.exp(1j * (asmatrix(scipy.angle(y))))
    """Get cPLV needed for flips and weighting."""
    cplv = scipy.zeros(len(identities), dtype='complex')

    for i, identity in enumerate(identities):
        """Compute cPLV only of parcel source pairs of sources that
        belong to that parcel. One source belong to only one parcel."""
        if (identities[i] >= 0):
            cplv[i] = (scipy.sum((scipy.asarray(y[identity])) *
                                 scipy.conjugate(scipy.asarray(x[i]))))

    cplv /= np.shape(x)[1]
    return cplv
Esempio n. 42
0
def hilbert_phaser(s):
    """
    FUNC: hilbert_phaser
    DESCR: Return the instantaneous phase of s using the hilbert transform
    """
    #f = file("hilbert_fpe.pickle", "w")
    #pickle.dump(s, f)
    #f.close()
    #print "utils:hilbert_phaser(): sig.hilbert(", s[0:10], ")"
    h = scipy.signal.hilbert(s)
    #print "utils:hilbert_phaser(): scipy.absolute(", h[0:10], ")"
    a = scipy.absolute(h)
    #print "utils:hilbert_phaser(): scipy.angle(", h[0:10], ")"
    phase = scipy.angle(h)
    return phase
Esempio n. 43
0
def hilbert_phaser(s):
    """
    FUNC: hilbert_phaser
    DESCR: Return the instantaneous phase of s using the hilbert transform
    """
    #f = file("hilbert_fpe.pickle", "w")
    #pickle.dump(s, f)
    #f.close()
    #print "utils:hilbert_phaser(): sig.hilbert(", s[0:10], ")"
    h = scipy.signal.hilbert(s)
    #print "utils:hilbert_phaser(): scipy.absolute(", h[0:10], ")"    
    a = scipy.absolute(h)
    #print "utils:hilbert_phaser(): scipy.angle(", h[0:10], ")"    
    phase = scipy.angle(h)
    return phase
Esempio n. 44
0
def calc_noise(filepath):
    noise_sum=None
    signal, params = read_signal(filepath, WINSIZE)
    nf = len(signal)/(WINSIZE/2) - 1
    noise_sum=sp.zeros(WINSIZE,sp.float32)
    window = sp.hanning(WINSIZE)
    for no in xrange(nf):
        y = get_frame(signal, WINSIZE, no)
        Y = sp.fft(y*window)
        Yr = sp.absolute(Y)
        Yp = sp.angle(Y)
        if ( no < 20 ):
            noise_sum = noise_sum + Yr**2
        else:
            break
    return noise_sum
    def detect(self, verbose=False):

        frequencies, sdata = self._freqs, self._s_data

        if not self._fast:
            result = self._fit(verbose)
        else:
            amps = abs(self._s_data)
            phas = angle(self._s_data)
            min_idx = argmin(amps)
            result = frequencies[min_idx], min(amps), phas[min_idx]

        if result is not None:
            if self._plot and not verbose:
                self._port.plotall()
            return result
Esempio n. 46
0
def inst_freq(x, t=None):
    """
    Compute the instantaneous frequency of an analytic signal at specific time
    instants using the trapezoidal integration rule.

    Parameters
    ----------
    x : array-like, shape (n_samples,)
        The input analytic signal.
    t : array-like, shape (n_samples,), optional
        The time instants at which to calculate the instantaneous frequency.
        Defaults to `np.arange(2, n_samples)`

    Returns
    -------
    array-like
        Normalized instantaneous frequencies of the input signal

    Examples
    --------
    >>> from tftb.generators import fmsin
    >>> import matplotlib.pyplot as plt
    >>> x = fmsin(70, 0.05, 0.35, 25)[0]
    >>> instf, timestamps = inst_freq(x)
    >>> plt.plot(timestamps, instf) #doctest: +SKIP

    .. plot:: docstring_plots/utils/inst_freq.py

    """
    if x.ndim != 1:
        if 1 not in x.shape:
            raise TypeError("Input should be a one dimensional array.")
        else:
            x = x.ravel()
    if t is not None:
        if t.ndim != 1:
            if 1 not in t.shape:
                raise TypeError("Time instants should be a one dimensional "
                                "array.")
            else:
                t = t.ravel()
    else:
        t = np.arange(2, len(x))

    fnorm = 0.5 * (angle(-x[t] * np.conj(x[t - 2])) + np.pi) / (2 * np.pi)
    return fnorm, t
Esempio n. 47
0
def frfplot(f, H):
    plt.subplot(211)
    plt.plot(f, 20 * sp.log10(sp.absolute(sp.sum(H, axis=1))), '-')
    plt.grid('on')
    plt.xlabel('Frequency (Hz)')
    plt.ylabel('FRF (dB)')
    axlim = plt.axis()
    plt.axis(
        axlim + sp.array([0, 0, -0.1 * (axlim[3] - axlim[2]), 0.1 * (axlim[3] - axlim[2])]))

    plt.subplot(212)
    plt.plot(f, sp.unwrap(sp.angle(sp.sum(H, axis=1))) / sp.pi * 180, '-')
    plt.grid('on')
    plt.xlabel('Frequency (Hz)')
    plt.ylabel('Phase (deg)')
    axlim = plt.axis()
    plt.axis(
        axlim + sp.array([0, 0, -0.1 * (axlim[3] - axlim[2]), 0.1 * (axlim[3] - axlim[2])]))
Esempio n. 48
0
def inst_freq(x, t=None, L=1):
    """
    Compute the instantaneous frequency of an analytic signal at specific
    time instants using the trapezoidal integration rule.

    :param x: The input analytic signal
    :param t: The time instants at which to calculate the instantaneous frequencies.
    :param L: Non default values are currently not supported.
        If L is 1, the normalized instantaneous frequency is computed. If L > 1,
        the maximum likelihood estimate of the instantaneous frequency of the
        deterministic part of the signal.
    :type x: numpy.ndarray
    :type t: numpy.ndarray
    :type L: int
    :return: instantaneous frequencies of the input signal.
    :rtype: numpy.ndarray
    :Example:
    >>> from tftb.generators import fmsin
    >>> x = fmsin(70, 0.05, 0.35, 25)[0]
    >>> instf, timestamps = inst_freq(x)
    >>> plot(timestamps, instf) #doctest: +SKIP

    .. plot:: docstring_plots/processing/freq_domain/inst_freq.py
    """
    if x.ndim != 1:
        if 1 not in x.shape:
            raise TypeError("Input should be a one dimensional array.")
        else:
            x = x.ravel()
    if t is not None:
        if t.ndim != 1:
            if 1 not in t.shape:
                raise TypeError("Time instants should be a one dimensional "
                                "array.")
            else:
                t = t.ravel()
    else:
        t = np.arange(2, len(x))

    fnorm = 0.5 * (angle(-x[t] * np.conj(x[t - 2])) + np.pi) / (2 * np.pi)
    return fnorm, t
 def compute_by_noise_pow(self,signal,n_pow):
     s_spec = sp.fft(signal*self._window)
     s_amp = sp.absolute(s_spec)
     s_phase = sp.angle(s_spec)
     gamma = self._calc_aposteriori_snr(s_amp,n_pow)
     xi = self._calc_apriori_snr(gamma)
     self._prevGamma = gamma
     nu = gamma * xi / (1.0+xi)
     self._G = (self._gamma15*sp.sqrt(nu)/gamma)*sp.exp(-nu/2.0)* ((1.0+nu)*spc.i0(nu/2.0)+nu*spc.i1(nu/2.0))
     idx = sp.less(s_amp**2.0,n_pow)
     self._G[idx] = self._constant
     idx = sp.isnan(self._G) + sp.isinf(self._G)
     self._G[idx] = xi[idx] / ( xi[idx] + 1.0)
     idx = sp.isnan(self._G) + sp.isinf(self._G)
     self._G[idx] = self._constant
     self._G = sp.maximum(self._G,0.0)
     amp = self._G * s_amp
     amp = sp.maximum(amp,0.0)
     amp2 = self._ratio*amp + (1.0-self._ratio)*s_amp
     self._prevAmp = amp
     spec = amp2 * sp.exp(s_phase*1j)
     return sp.real(sp.ifft(spec))
 def compute_by_noise_pow(self,signal,n_pow):
     s_spec = sp.fft(signal *self._window)
     s_amp = sp.absolute(s_spec)
     s_phase = sp.angle(s_spec)
     gamma = self._calc_aposteriori_snr(s_amp,n_pow)
     #xi = self._calc_apriori_snr2(gamma,n_pow)
     xi = self._calc_apriori_snr(gamma)
     self._prevGamma = gamma
     u = 0.5 - self._mu/(4.0*sp.sqrt(gamma*xi))
     self._G = u + sp.sqrt(u**2.0 + self._tau/(gamma*2.0))
     idx = sp.less(s_amp**2.0,n_pow)
     self._G[idx] = self._constant
     idx = sp.isnan(self._G) + sp.isinf(self._G)
     self._G[idx] = xi[idx] / ( xi[idx] + 1.0)
     idx = sp.isnan(self._G) + sp.isinf(self._G)
     self._G[idx] = self._constant
     self._G = sp.maximum(self._G,0.0)
     amp = self._G * s_amp
     amp = sp.maximum(amp,0.0)
     amp2 = self._ratio*amp + (1.0-self._ratio)*s_amp
     self._prevAmp = amp
     spec = amp2 * sp.exp(s_phase*1j)
     return sp.real(sp.ifft(spec))
Esempio n. 51
0
suma = abs(d[npoints/2:,:]).sum(axis=1)
suma.resize((suma.shape[0], 1))
pylab.plot(w[npoints/2:], loudia.magToDb(suma), c = 'red')

ax = pylab.gca()

# Show half of the spectrum
ax.set_xlim([0, scipy.pi])

# Set the ticks units to radians per second
ticks = ax.get_xticks()
ax.set_xticklabels(['%.2f' % (float(tick) / (scipy.pi * 2.0)) for tick in ticks])

# Set the title and labels
pylab.title('Magnitude of the Frequency Response of a \n Gammatone Filterbank implementation')
pylab.xlabel('Normalized Frequency')
pylab.ylabel('|H(w)| (no unit)')

if plotAngle:
    pylab.subplot(2,1,2)
    if plotColor:
        pylab.plot(w[npoints/2:], scipy.angle(d[npoints/2:,:]))
    else:
        pylab.plot(w[npoints/2:], scipy.angle(d[npoints/2:,:]), c = 'black')
    pylab.title('Angle of the Frequency Response')

    pylab.gca().set_xlim([0, scipy.pi])

pylab.show()

Esempio n. 52
0
    peakSynth = loudia.PeakSynthesize( frameSize/6, fftSize, windowType )

trajsLocs = []
trajsMags = []
specs = []
specsSynth = []
specsResid = []
specsMagsResid = []

for frame in stream:
    samples = frame
    fft = ffter.process( windower.process( frame ) )[0, :plotSize]
    spec =  loudia.magToDb( abs( fft ) )[0, :plotSize]

    if set(['phase', 'peak_phases']) | all_processes:
        phase =  scipy.angle( fft )

    if set(['peak_mags', 'peak_phases']) | all_processes:
        fft = scipy.reshape(fft, (1, plotSize))

        peakLocs, peakMags, peakPhases =  peaker.process( fft )

        peakiLocs, peakiMags, peakiPhases = peakInterp.process( fft,
                                                               peakLocs,
                                                               peakMags,
                                                               peakPhases )
        
        trajLocs, trajMags = tracker.process( fft,
                                              peakiLocs,
                                              peakiMags )
Esempio n. 53
0
        try :
            if (x.shape[0]==0) or (y.shape[0]== 0) : raise ValueError("Empty signal")
            if x.shape[0]!=y.shape[0] : raise ValueError("The two signals have different length")
        except ValueError, err_msg:
            raise ValueError(err_msg)
            return
        
    
        M=x.shape[0]
                

        #computing the analytic signal and the instantaneous phase
        x_analytic=hilbert(np.hstack(x.values))
        y_analytic=hilbert(np.hstack(y.values))
        
        phx=np.unwrap(scipy.angle(x_analytic))
        phy=np.unwrap(scipy.angle(y_analytic))
    
         
        disc_perc=np.floor(x.shape[0]/10.0)    
        
        phx_s=phx[disc_perc-1:M-disc_perc]
        phy_s=phy[disc_perc-1:M-disc_perc]
        
        ph_nm=(self._n*phx_s-self._m*phy_s)
        psi_nm=np.mod(ph_nm, 2*np.pi)

        gamma2_nm=np.square(np.mean(np.cos(psi_nm))) + np.square(np.mean(np.sin(psi_nm)))
        
        result = dict()
        result['gamma2_nm'] = gamma2_nm
    for datafile_name in filenames: 
        ## Getting 1D data
        (freq, s11_ampli, s11p, s12_ampli, s12p, Nre, Nim, Zre, Zim, eps_r, eps_i, mu_r, mu_i) = \
                np.loadtxt(datafile_name, usecols=range(13), unpack=True)
        if quantity == 'reflection':        znew = s11_ampli
        elif quantity == 'transmission':    znew = s12_ampli
        elif quantity == 'loss':            znew = np.log(1 - s11_ampli**2 - s12_ampli**2)
        elif quantity == 'absNimag':        znew = np.clip(abs(Nim), 0, 10)
            #znew = np.log10(np.clip(abs(Nim), 0, 300 ))
        elif quantity == 'absNre':          
            znew = abs(np.arcsin(np.sin(np.real(Nre*freq*100e-6/c) * np.pi)) / np.pi)
            znew2 = np.clip(abs(Nim), 0, 10)
        elif quantity == 'Nre':             znew = Nre #np.real(Nre*freq*100e-6/c)
        elif quantity == 'eps':             znew = eps_r
        elif quantity == 'epsangle':        znew = np.angle(eps_r + 1j*eps_i)
        elif quantity == 'mu':              znew = mu_r
        else: print 'Error!, select a known quantity to plot!'

        ## Truncate the data ranges
        truncated = np.logical_and(freq>minf, freq<maxf)
        (freq, znew) = map(lambda x: x[truncated], [freq, znew])
        #(znew2) = map(lambda x: x[truncated], [znew2]) ## XXX

        ## Load header
        parameters  = {}
        columns     = []
        with open(datafile_name) as datafile:
            for line in datafile:
                if (line[0:1] in '0123456789') or ('column' in line.lower()): break    # end of parameter list
                key, value = line.replace(',', ' ').split()[-2:]
Esempio n. 55
0
# 4x4 are used

DMDpattern_superpixel, E_superpixel, fidelity_superpixel, efficiency_superpixel = superpixelMethod.superpixelMethod(E_target, resolution)


E_target_lowres = miscDMD.spatial_filter(E_target)
fidelity_superpixel_lowres = abs(miscDMD.inner_product(E_superpixel,E_target_lowres))**2

# Plot the results:

f1 = plt.figure()
a = f1.add_subplot(1,2,1)
plt.imshow(abs(E_target/ scipy.sqrt((abs(E_target)**2).sum())),"gray")
a.set_title('target intensity') 
a = f1.add_subplot(1,2,2)
plt.imshow(scipy.angle(E_target/ scipy.sqrt((abs(E_target)**2).sum())),"gray")
a.set_title('target phase')
 
f2 = plt.figure()
a = f2.add_subplot(1,1,1)
plt.imshow(DMDpattern_superpixel, "gray")
a.set_title('DMD pattern superpixel')

f3 = plt.figure()
a = f3.add_subplot(1,2,1)
plt.imshow(abs(E_superpixel/ scipy.sqrt((abs(E_target_lowres)**2).sum())),"gray")
a.set_title('superpixel intensity') 
a = f3.add_subplot(1,2,2)
plt.imshow(scipy.angle(E_superpixel/ scipy.sqrt((abs(E_target_lowres)**2).sum())),"gray")
a.set_title('superpixel phase')
def nichols_grid(cl_mags=None, cl_phases=None):
    """Nichols chart grid

    Plots a Nichols chart grid on the current axis, or creates a new chart
    if no plot already exists.

    Parameters
    ----------
    cl_mags : array-like (dB), optional
        Array of closed-loop magnitudes defining the iso-gain lines on a
        custom Nichols chart.
    cl_phases : array-like (degrees), optional
        Array of closed-loop phases defining the iso-phase lines on a custom
        Nichols chart. Must be in the range -360 < cl_phases < 0

    Returns
    -------
    None
    """
    # Default chart size
    ol_phase_min = -359.99
    ol_phase_max = 0.0
    ol_mag_min = -40.0
    ol_mag_max = default_ol_mag_max = 50.0

    # Find bounds of the current dataset, if there is one.
    if plt.gcf().gca().has_data():
        ol_phase_min, ol_phase_max, ol_mag_min, ol_mag_max = plt.axis()

    # M-circle magnitudes.
    if cl_mags is None:
        # Default chart magnitudes
        # The key set of magnitudes are always generated, since this
        # guarantees a recognizable Nichols chart grid.
        key_cl_mags = np.array([-40.0, -20.0, -12.0, -6.0, -3.0, -1.0, -0.5, 0.0,
                                     0.25, 0.5, 1.0, 3.0, 6.0, 12.0])
        # Extend the range of magnitudes if necessary. The extended arange
        # will end up empty if no extension is required. Assumes that closed-loop
        # magnitudes are approximately aligned with open-loop magnitudes beyond
        # the value of np.min(key_cl_mags)
        cl_mag_step = -20.0 # dB
        extended_cl_mags = np.arange(np.min(key_cl_mags),
                                     ol_mag_min + cl_mag_step, cl_mag_step)
        cl_mags = np.concatenate((extended_cl_mags, key_cl_mags))

    # N-circle phases (should be in the range -360 to 0)
    if cl_phases is None:
        # Choose a reasonable set of default phases (denser if the open-loop
        # data is restricted to a relatively small range of phases).
        key_cl_phases = np.array([-0.25, -45.0, -90.0, -180.0, -270.0, -325.0, -359.75])
        if np.abs(ol_phase_max - ol_phase_min) < 90.0:
            other_cl_phases = np.arange(-10.0, -360.0, -10.0)
        else:
            other_cl_phases = np.arange(-10.0, -360.0, -20.0)
        cl_phases = np.concatenate((key_cl_phases, other_cl_phases))
    else:
        assert ((-360.0 < np.min(cl_phases)) and (np.max(cl_phases) < 0.0))

    # Find the M-contours
    m = m_circles(cl_mags, phase_min=np.min(cl_phases), phase_max=np.max(cl_phases))
    m_mag = 20*sp.log10(np.abs(m))
    m_phase = sp.mod(sp.degrees(sp.angle(m)), -360.0) # Unwrap

    # Find the N-contours
    n = n_circles(cl_phases, mag_min=np.min(cl_mags), mag_max=np.max(cl_mags))
    n_mag = 20*sp.log10(np.abs(n))
    n_phase = sp.mod(sp.degrees(sp.angle(n)), -360.0) # Unwrap

    # Plot the contours behind other plot elements.
    # The "phase offset" is used to produce copies of the chart that cover
    # the entire range of the plotted data, starting from a base chart computed
    # over the range -360 < phase < 0. Given the range
    # the base chart is computed over, the phase offset should be 0
    # for -360 < ol_phase_min < 0.
    phase_offset_min = 360.0*np.ceil(ol_phase_min/360.0)
    phase_offset_max = 360.0*np.ceil(ol_phase_max/360.0) + 360.0
    phase_offsets = np.arange(phase_offset_min, phase_offset_max, 360.0)

    for phase_offset in phase_offsets:
        # Draw M and N contours
        plt.plot(m_phase + phase_offset, m_mag, color='gray',
                 linestyle='dotted', zorder=0)
        plt.plot(n_phase + phase_offset, n_mag, color='gray',
                 linestyle='dotted', zorder=0)

        # Add magnitude labels
        for x, y, m in zip(m_phase[:][-1] + phase_offset, m_mag[:][-1], cl_mags):
            align = 'right' if m < 0.0 else 'left'
            plt.text(x, y, str(m) + ' dB', size='small', ha=align, color='gray')

    # Fit axes to generated chart
    plt.axis([phase_offset_min - 360.0, phase_offset_max - 360.0,
              np.min(cl_mags), np.max([ol_mag_max, default_ol_mag_max])])
Esempio n. 57
0
    def update_figure(self, i=0):
        cur_cmap = cm.RdGy_r
        self.f1.clf()
        self.init_figure()

        wh = sp.where(abs(self.object.data[0]) > 0.1 * (abs(self.object.data[0]).max()))
        try:
            x1, x2 = min(wh[0]), max(wh[0])
            y1, y2 = min(wh[1]), max(wh[1])
        except (ValueError, IndexError):
            x1, x2 = 0, self.ob_p
            y1, y2 = 0, self.ob_p

        # Plot magnitude of object
        s1 = pylab.subplot(231)
        s1_im = s1.imshow(abs(self.object).data[0][x1:x2, y1:y2], cmap=cm.Greys_r)
        s1.set_title('|object|')
        plt.axis('off')
        pylab.colorbar(s1_im)

        # Plot phase of object
        s2 = pylab.subplot(232)
        s2_im = s2.imshow(sp.angle(self.object.data[0][x1:x2, y1:y2]), cmap=cm.hsv)
        s2.set_title('phase(object)')
        plt.axis('off')
        pylab.colorbar(s2_im)

        # Complex HSV plot of object
        s3 = pylab.subplot(233)
        h = ((angle(self.object).data[0][x1:x2, y1:y2] + np.pi) / (2*np.pi)) % 1.0
        s = np.ones_like(h)
        l = abs(self.object).data[0][x1:x2, y1:y2]
        l-=l.min()
        l/=l.max()
        s3_im = s3.imshow(np.dstack(v_hls_to_rgb(h,l,s)))
        s3.set_title('Complex plot of Object')
        plt.axis('off')

        # Plot probe mode 0
        s4 = pylab.subplot(234)
        s4_im = s4.imshow(abs(self.probe.modes[0].data[0]), cmap=cur_cmap)
        s4.set_title('|probe0|')
        plt.axis('off')
        pylab.colorbar(s4_im)

        if CXP.reconstruction.probe_modes>1:
            s5 = pylab.subplot(235)
            s5_im = s5.imshow(abs(self.probe.modes[1].data[0]), cmap=cur_cmap)
            s5.set_title('|probe1|')
            plt.axis('off')
            pylab.colorbar(s5_im)
        else:
            pass
        if self.ppc:
            s6 = self.f1.add_subplot(236)
            s6_im = s6.scatter(self.positions.data[0], self.positions.data[1], s=10,
                c='b', marker='o', alpha=0.5, edgecolors='none', label='current')
            patches = []
            for m in range(self.positions.total):
                patches.append(Circle((self.positions.initial[0][m], self.positions.initial[1][m]),
                               radius=CXP.reconstruction.ppc_search_radius))
            collection = PatchCollection(patches, color='tomato', alpha=0.2, edgecolors=None)
            s4.add_collection(collection)
            if CXP.measurement.simulate_data:
                s4_im = s4.scatter(self.positions.correct[0], self.positions.correct[1], s=10,
                    c='g', marker='o', alpha=0.5, edgecolors='none', label='correct')
                CXP.log.info('RMS position deviation from correct: [x:{:3.2f},y:{:3.2f}] pixels'.format(
                            sp.sqrt(sp.mean((self.positions.data[0] - self.positions.correct[0])**2.)),
                            sp.sqrt(sp.mean((self.positions.data[1] - self.positions.correct[1])**2.))))
                lines=[]
                for m in range(self.positions.total):
                    lines.append(((self.positions.correct[0][m], self.positions.correct[1][m]),
                                  (self.positions.data[0][m], self.positions.data[1][m])))
                for element in lines:
                    x, y = zip(*element)
                    s4.plot(x, y, 'g-')
            else:
                lines = []
                for m in range(self.positions.total):
                    lines.append(((self.positions.initial[0][m], self.positions.initial[1][m]),
                                  (self.positions.data[0][m], self.positions.data[1][m])))
                for element in lines:
                    x, y = zip(*element)
                    s6.plot(x, y, 'g-')
                CXP.log.info('RMS position deviation from initial: [x:{:3.2f},y:{:3.2f}] pixels'.format(
                            sp.sqrt(sp.mean((self.positions.data[0] - self.positions.initial[0])**2.)),
                            sp.sqrt(sp.mean((self.positions.data[1] - self.positions.initial[1])**2.))))
            s6.legend(prop={'size': 6})
            s6.set_title('Position Correction')
            s6.set_aspect('equal')
            extent = s6.get_window_extent().transformed(self.f1.dpi_scale_trans.inverted())
            pylab.savefig(self._cur_sequence_dir + '/ppc_{:d}.png'.format(self.total_its), bbox_inches=extent.expanded(1.2, 1.2), dpi=100)
            s6.set_aspect('auto')
        else:
            s6 = pylab.subplot(236)
            if CXP.measurement.simulate_data:
                s6_im = s6.imshow(abs(self.input_probe[1].data[0]), cmap = cur_cmap)
                s6.set_title('|input_probe1|')
            else:
                s6_im = s6.imshow(nlog(fftshift(self.det_mod[np.mod(i,self.positions.total)])).data[0], cmap=cur_cmap)
                s6.set_title('Diff Patt: {:d}'.format(i))
            plt.axis('off')
            pylab.colorbar(s6_im)
        pylab.draw()
        pylab.savefig(self._cur_sequence_dir + '/recon_{:d}.png'.format(self.total_its), dpi=60)
Esempio n. 58
0
print r_random_time
print r_sine_time

print "Freq:"
print r_zeros_freq
print r_ones_freq
print r_random_freq
print r_sine_freq

print scipy.allclose(r_zeros_fft, s_zeros_fft)
print scipy.allclose(r_ones_fft, s_ones_fft)
print scipy.allclose(r_random_fft, s_random_fft)
print scipy.allclose(r_sine_fft, s_sine_fft)

r_abs = scipy.absolute(r_sine_fft).T
r_ang = scipy.angle(r_sine_fft).T
r_max = max(r_abs)

s_abs = scipy.absolute(s_sine_fft).T
s_ang = scipy.angle(s_sine_fft).T
s_max = max(s_abs)

import pylab
pylab.subplot(311)
pylab.plot(a_sine.T)

pylab.subplot(312)
pylab.hold(True)
pylab.plot(r_abs, label = 'Loudia')
pylab.plot(s_abs, label = 'Scipy')
pylab.legend()