Ejemplo n.º 1
0
def _qfunc_pure(psi, alpha_vec):
    """
    Calculate the Q-function for a pure state.
    """
    n = np.prod(psi.shape)

    # Gengyan: maximun number to use factorial()
    nmax = 170

    if isinstance(psi, Qobj):
        psi = psi.full().flatten()
    else:
        psi = psi.T

    if n < nmax:
        qvec = abs(
            polyval(
                fliplr([psi / sqrt(factorial(arange(n)))])[0],
                conjugate(alpha_vec)))**2 * exp(-abs(alpha_vec)**2)
    else:
        # Gengyan: for m < nmax, use factorial()
        qvec = polyval(
            fliplr([psi[0:nmax] / sqrt(factorial(arange(nmax)))])[0],
            conjugate(alpha_vec)) * exp(-abs(alpha_vec)**2 / 2)
        # Gengyan: for m >= nmax, use Stirling's approximation
        for m in range(nmax, n):
            qvec += (conjugate(alpha_vec)/sqrt(m))**m*psi[m] * \
                exp((m-abs(alpha_vec)**2)/2)*(2*pi*m)**(-0.25)
        qvec = abs(qvec)**2

    return np.real(qvec) / pi
Ejemplo n.º 2
0
    def func(self, X, V):
        k = self.C.TFdata.k
        v1 = self.C.TFdata.v1
        w1 = self.C.TFdata.w1
        
        if k >=0:
            J_coords = self.F.sysfunc.J_coords
            w = sqrt(k)
        
            q = v1 - (1j/w)*matrixmultiply(self.F.sysfunc.J_coords,v1)
            p = w1 + (1j/w)*matrixmultiply(transpose(self.F.sysfunc.J_coords),w1)
            
            p /= linalg.norm(p)
            q /= linalg.norm(q)

            p = reshape(p,(p.shape[0],))
            q = reshape(q,(q.shape[0],))
            
            direc = conjugate(1/matrixmultiply(transpose(conjugate(p)),q))
            p = direc*p

            l1 = firstlyapunov(X, self.F.sysfunc, w, J_coords=J_coords, p=p, q=q)
            
            return array([l1])
        else:
            return array([1])
Ejemplo n.º 3
0
 def to_minimize_fidelity(theta):
     temp_z_gate = np.matmul(
         sp.linalg.expm(-2 * np.pi * 1j * theta * self.H_zeeman),
         U_ideal)
     temp_m = np.matmul(sp.conjugate(sp.transpose(target)),
                        temp_z_gate)
     return np.real(1. - (sp.trace(
         np.matmul(temp_m, sp.conjugate(sp.transpose(temp_m)))) +
                          np.abs(sp.trace(temp_m))**2.) / 20.)
Ejemplo n.º 4
0
    def process(self, X, V, C):
        """Tolerance for eigenvalues a possible problem when checking for neutral saddles."""
        BifPoint.process(self, X, V, C)
                
        J_coords = C.CorrFunc.jac(X, C.coords)
        eigs, LV, RV = linalg.eig(J_coords,left=1,right=1)
        
        # Check for neutral saddles
        found = False
        for i in range(len(eigs)):
            if abs(imag(eigs[i])) < 1e-5:
                for j in range(i+1,len(eigs)):
                    if C.verbosity >= 2:
                        if abs(eigs[i]) < 1e-5 and abs(eigs[j]) < 1e-5:
                            print 'Fold-Fold point found in Hopf!\n'
                        elif abs(imag(eigs[j])) < 1e-5 and abs(real(eigs[i]) + real(eigs[j])) < 1e-5:
                            print 'Neutral saddle found!\n'
            elif abs(real(eigs[i])) < 1e-5:
                for j in range(i+1, len(eigs)):
                    if abs(real(eigs[j])) < 1e-5 and abs(real(eigs[i]) - real(eigs[j])) < 1e-5:
                        found = True
                        w = abs(imag(eigs[i]))
                        if imag(eigs[i]) > 0:
                            p = conjugate(LV[:,j])/linalg.norm(LV[:,j])
                            q = RV[:,i]/linalg.norm(RV[:,i])
                        else:
                            p = conjugate(LV[:,i])/linalg.norm(LV[:,i])
                            q = RV[:,j]/linalg.norm(RV[:,j])

        if not found:
            del self.found[-1]
            return False

        direc = conjugate(1/matrixmultiply(conjugate(p),q))
        p = direc*p

        # Alternate way to compute 1st lyapunov coefficient (from Kuznetsov [4])
        
        #print (1./(w*w))*real(1j*matrixmultiply(conjugate(p),b1)*matrixmultiply(conjugate(p),b3) + \
        #   w*matrixmultiply(conjugate(p),trilinearform(D,q,q,conjugate(q))))

        self.found[-1].w = w
        self.found[-1].l1 = firstlyapunov(X, C.CorrFunc, w, J_coords=J_coords, p=p, q=q, check=(C.verbosity==2)) 
        self.found[-1].eigs = eigs
        
        self.info(C, -1)
        
        return True
Ejemplo n.º 5
0
def hg_conv(f, g):
	ub = tuple(array(f.shape) + array(g.shape) - 1);
	fh = rfftn(cpad(f,ub));
	gh = rfftn(cpad(g,ub));
	res = ifftshift(irfftn(fh * sp.conjugate(gh)));
	del fh, gh;
	return res;
Ejemplo n.º 6
0
def MakePulseDataRepLPC(pulse,spec,N,rep1,numtype = sp.complex128):
    """ This will make data by assuming the data is an autoregressive process.
        Inputs
            spec - The properly weighted spectrum.
            N - The size of the ar process used to model the filter.
            pulse - The pulse shape.
            rep1 - The number of repeats of the process.
        Outputs
            outdata - A numpy Array with the shape of the """

    lp = len(pulse)
    lenspec = len(spec)
    r1 = scfft.ifft(scfft.ifftshift(spec))
    rp1 = r1[:N]
    rp2 = r1[1:N+1]
    # Use Levinson recursion to find the coefs for the data
    xr1 = sp.linalg.solve_toeplitz(rp1, rp2)
    lpc = sp.r_[sp.ones(1), -xr1]
    # The Gain  term.
    G = sp.sqrt(sp.sum(sp.conjugate(r1[:N+1])*lpc))
    Gvec = sp.r_[G, sp.zeros(N)]
    Npnt = (N+1)*3+lp
    # Create the noise vector and normalize
    xin = sp.random.randn(rep1, Npnt)+1j*sp.random.randn(rep1, Npnt)
    xinsum = sp.tile(sp.sqrt(sp.mean(xin.real**2+xin.imag**2, axis=1))[:, sp.newaxis],(1, Npnt))
    xin = xin/xinsum
    outdata = sp.signal.lfilter(Gvec, lpc, xin, axis=1)
    outpulse = sp.tile(pulse[sp.newaxis], (rep1, 1))
    outdata = outpulse*outdata[:, 2*N:2*N+lp]
    return outdata
Ejemplo n.º 7
0
def autocorrelation_1d(x):
    """Estimate the normalized autocorrelation function of a 1-D series

	Args:
		x: The series as a 1-D numpy array.

	Returns:
		array: The autocorrelation function of the time series.
	
	Taken from: https://github.com/dfm/emcee/blob/master/emcee/autocorr.py
	"""
    x = scipy.atleast_1d(x)
    if len(x.shape) != 1:
        raise ValueError("invalid dimensions for 1D autocorrelation function")

    def next_pow_two(n):
        """Returns the next power of two greater than or equal to `n`"""
        i = 1
        while i < n:
            i = i << 1
        return i

    n = next_pow_two(len(x))

    # Compute the FFT and then (from that) the auto-correlation function
    f = fft.fft(x - scipy.mean(x), n=2 * n)
    acf = fft.ifft(f * scipy.conjugate(f))[:len(x)].real

    acf /= acf[0]
    return acf
Ejemplo n.º 8
0
def task2(rx_sample_time, rx_signal, tx_envelope, pltfig=False):
    rx_quad_demod = quadrature_demodulation(rx_signal, rx_sample_time)
    rx_filtered = matched_filter(rx_quad_demod,
                                 sp.conjugate(sp.flipud(tx_envelope)))
    if pltfig:
        plot_sqr_magn(rx_filtered, rx_sample_time)
    return rx_filtered  # workarround due to lack of time
Ejemplo n.º 9
0
def MakePulseDataRepLPC(pulse, spec, N, rep1, numtype=sp.complex128):
    """ This will make data by assuming the data is an autoregressive process.
        Inputs
            spec - The properly weighted spectrum.
            N - The size of the ar process used to model the filter.
            pulse - The pulse shape.
            rep1 - The number of repeats of the process.
        Outputs
            outdata - A numpy Array with the shape of the """

    lp = len(pulse)
    r1 = scfft.ifft(scfft.ifftshift(spec))
    rp1 = r1[:N]
    rp2 = r1[1:N + 1]
    # Use Levinson recursion to find the coefs for the data
    xr1 = sp.linalg.solve_toeplitz(rp1, rp2)
    lpc = sp.r_[sp.ones(1), -xr1]
    # The Gain  term.
    G = sp.sqrt(sp.sum(sp.conjugate(r1[:N + 1]) * lpc))
    Gvec = sp.r_[G, sp.zeros(N)]
    Npnt = (N + 1) * 3 + lp
    # Create the noise vector and normalize
    xin = sp.random.randn(rep1, Npnt) + 1j * sp.random.randn(rep1, Npnt)
    xinsum = sp.tile(
        sp.sqrt(sp.sum(xin.real**2 + xin.imag**2, axis=1))[:, sp.newaxis],
        (1, Npnt))
    xin = xin / xinsum / sp.sqrt(2.)
    outdata = sp.signal.lfilter(Gvec, lpc, xin, axis=1)
    outpulse = sp.tile(pulse[sp.newaxis], (rep1, 1))
    outdata = outpulse * outdata[:, N:N + lp]
    return outdata
Ejemplo n.º 10
0
 def _cross_correlate(self, reference_image):
     # FFT of the projection spectra
     f_ref_xproj = fft(reference_image.proj_x)
     f_ref_yproj = fft(reference_image.proj_y)
     f_check_xproj = fft(self.proj_x)
     f_check_yproj = fft(self.proj_y)
     # cross correlate in and look for the maximium correlation
     f_ref_xproj_conj = conjugate(f_ref_xproj)
     f_ref_yproj_conj = conjugate(f_ref_yproj)
     complex_sum_x = f_ref_xproj_conj * f_check_xproj
     complex_sum_y = f_ref_yproj_conj * f_check_yproj
     phi_ref_check_m_x = ifft(complex_sum_x)
     phi_ref_check_m_y = ifft(complex_sum_y)
     z_x = max(phi_ref_check_m_x)
     z_pos_x = np.where(phi_ref_check_m_x == z_x)
     z_y = max(phi_ref_check_m_y)
     z_pos_y = np.where(phi_ref_check_m_y == z_y)
     return z_pos_x, z_pos_y, phi_ref_check_m_x, phi_ref_check_m_y
Ejemplo n.º 11
0
def makeCovmat(lagsDatasum,lagsNoisesum,pulses_s,Nlags):
    
    axvec=sp.roll(sp.arange(lagsDatasum.ndim),1)
    # Get the covariance matrix
    R=sp.transpose(lagsDatasum/sp.sqrt(2.*pulses_s),axes=axvec)
    Rw=sp.transpose(lagsNoisesum/sp.sqrt(2.*pulses_s),axes=axvec)
    l=sp.arange(Nlags)
    T1,T2=sp.meshgrid(l,l)
    R0=R[sp.zeros_like(T1)]
    Rw0=Rw[sp.zeros_like(T1)]
    Td=sp.absolute(T1-T2)
    Tl = T1>T2
    R12 =R[Td]
    R12[Tl]=sp.conjugate(R12[Tl])
    Rw12 =Rw[Td]
    Rw12[Tl]=sp.conjugate(Rw12[Tl])
    Ctt=R0*R12+R[T1]*sp.conjugate(R[T2])+Rw0*Rw12+Rw[T1]*sp.conjugate(Rw[T2])
    avecback=sp.roll(sp.arange(Ctt.ndim),-2)
    Cttout = sp.transpose(Ctt,avecback)
    return Cttout
Ejemplo n.º 12
0
def makeCovmat(lagsDatasum,lagsNoisesum,pulses_s,Nlags):

    axvec=sp.roll(sp.arange(lagsDatasum.ndim),1)
    # Get the covariance matrix
    R=sp.transpose(lagsDatasum/sp.sqrt(2.*pulses_s),axes=axvec)
    Rw=sp.transpose(lagsNoisesum/sp.sqrt(2.*pulses_s),axes=axvec)
    l=sp.arange(Nlags)
    T1,T2=sp.meshgrid(l,l)
    R0=R[sp.zeros_like(T1)]
    Rw0=Rw[sp.zeros_like(T1)]
    Td=sp.absolute(T1-T2)
    Tl = T1>T2
    R12 =R[Td]
    R12[Tl]=sp.conjugate(R12[Tl])
    Rw12 =Rw[Td]
    Rw12[Tl]=sp.conjugate(Rw12[Tl])
    Ctt=R0*R12+R[T1]*sp.conjugate(R[T2])+Rw0*Rw12+Rw[T1]*sp.conjugate(Rw[T2])
    avecback=sp.roll(sp.arange(Ctt.ndim),-2)
    Cttout = sp.transpose(Ctt,avecback)
    return Cttout
Ejemplo n.º 13
0
	def grad(self, A, B, q):
		#Compute relative transformation
		pr = norm(q.x)
		
		if(pr >= A.radius + B.radius ):
			return array([0., 0., 0., 0.])
		
		#Load shape parameters
		fa  = A.pft
		fb  = B.pft
		da  = A.pdft
		db  = B.pdft
		ea 	= A.energy
		eb 	= B.energy
		
		#Estimate cutoff threshold
		cutoff = self.__get_cutoff(A, B)
		
		#Compute coordinate coefficients
		m   = 2.j * pi / (2. * self.SHAPE_R + 1) * pr
		phi = atan2(q.x[1], q.x[0])
		
		#Set up initial sums
		s_0	 = real(fa[0][0] * fb[0][0])
		s_x  = 0.
		s_y  = 0.
		s_ta = 0.
		s_tb = 0.
		
		for r in range(1, self.R):
		
			#Compute theta terms
			dtheta = 2. * pi / len(fa[r])
			theta  = arange(len(fa[r])) * dtheta
		
			#Construct multiplier / v
			mult = exp((m * r) * cos(theta + phi)) * r * dtheta
			u 	 = pds.shift(conjugate(fb[r]), q.theta) * mult
			v 	 = fa[r] * u
			
			#Check for early out
			s_0  += sum(real(v))
			if(s_0 + min(ea[r], eb[r]) <= cutoff):
				return array([0.,0.,0.,0.])
				
			#Sum up gradient vectors
			v     = real(1.j * v)
			s_x  -= sum(v * sin(theta + phi) )
			s_y  -= sum(v * cos(theta + phi) )
			s_t  += sum(real(da[r] * u))
		
		if(s_0 <= cutoff):
			return array([0., 0., 0., 0.])
		return array([s_x, s_y, s_ta, s_tb, s_0])
Ejemplo n.º 14
0
def _qfunc_pure(psi, alpha_mat):
    """
    Calculate the Q-function for a pure state.
    """
    n = np.prod(psi.shape)
    if isinstance(psi, Qobj):
        psi = psi.full().flatten()
    else:
        psi = psi.T

    qmat = abs(polyval(fliplr([psi / sqrt(factorial(arange(n)))])[0],
                       conjugate(alpha_mat))) ** 2

    return real(qmat) * exp(-abs(alpha_mat) ** 2) / pi
Ejemplo n.º 15
0
def levinsonSymmetricConstrainA1(A, y, ncoeffs=scipy.inf):
    ncoeffs = min(ncoeffs, A.shape[1])

    eps = A[0, 0]

    ref = scipy.zeros(ncoeffs - 1)

    x = scipy.zeros(ncoeffs)
    x[0] = 1

    for i in range(1, ncoeffs):
        gamma = A[0, i] + scipy.dot(A[0, 1:i], x[1:i])

        ref[i - 1] = -gamma / eps

        eps *= (1 - ref[i - 1] * scipy.conjugate(ref[i - 1]))

        temp = scipy.conjugate(scipy.flipud(x[:i + 1]))

        x[:i + 1] += ref[i - 1] * temp
        x[i] = ref[i - 1]

    return (x, scipy.sqrt(eps))
Ejemplo n.º 16
0
def subspace_angles(A, B):
    """
    Return the principle angles and vectors between two subspaces. 

    See Bjorck and Golub, "Numerical Methods for Computing Between Linear 
           Subspaces" _Mathematics_of_Computation_, 27(123), 1973, pp. 579-594
    Or, for a more understandable exposition, Golub and Van Loan, 
           _Matrix_Computations_ (3rd ed.) pp. 603-604
    """
    A, B = scipy.asarray(A), scipy.asarray(B)
    if A.shape[0] != B.shape[0]:
        raise ValueError('Input subspaces must live in the same dimensional '\
                'space.')

    # Get orthogonal bases for our two subspaces.
    QA, QB = scipy.linalg.orth(A), scipy.linalg.orth(B)

    M = scipy.matrixmultiply(scipy.transpose(scipy.conjugate(QA)), QB)
    Y, C, Zh = scipy.linalg.svd(M)

    U = scipy.matrixmultiply(QA, Y)
    V = scipy.matrixmultiply(QB, scipy.transpose(scipy.conjugate(Zh)))
    return scipy.arccos(C), U, V
Ejemplo n.º 17
0
def _qfunc_pure(psi, alpha_mat):
    """
    Calculate the Q-function for a pure state.
    """
    n = prod(psi.shape)
    if isinstance(psi, Qobj):
        psi = array(psi.trans().full())[0,:]
    else:
        psi = psi.T

    qmat1 = abs(polyval(fliplr([psi/sqrt(factorial(arange(0, n)))])[0], conjugate(alpha_mat))) ** 2;
    qmat1 = real(qmat1) * exp(-abs(alpha_mat)**2) / pi;

    return qmat1
Ejemplo n.º 18
0
def levinsonSymmetricConstrainA1(A, y, ncoeffs = scipy.inf):
    ncoeffs = min(ncoeffs, A.shape[1])
    
    eps = A[0,0]

    ref = scipy.zeros( ncoeffs - 1 )
    
    x = scipy.zeros( ncoeffs )
    x[0] = 1
    
    for i in range(1, ncoeffs):
        gamma = A[0, i] + scipy.dot(A[0, 1:i], x[1:i])

        ref[i-1] = - gamma / eps

        eps *= (1 - ref[i-1]*scipy.conjugate(ref[i-1]))
        
        temp = scipy.conjugate(scipy.flipud(x[:i+1]))
        
        x[:i+1] += ref[i-1] * temp
        x[i] = ref[i-1]
        
    return (x, scipy.sqrt(eps))
Ejemplo n.º 19
0
def _qfunc_pure(psi, alpha_mat):
    """
    Calculate the Q-function for a pure state.
    """
    n = prod(psi.shape)
    if isinstance(psi, Qobj):
        psi = array(psi.trans().full())[0, :]
    else:
        psi = psi.T

    qmat1 = abs(
        polyval(
            fliplr([psi / sqrt(factorial(arange(0, n)))])[0],
            conjugate(alpha_mat)))**2
    qmat1 = real(qmat1) * exp(-abs(alpha_mat)**2) / pi

    return qmat1
Ejemplo n.º 20
0
def RK4(t_tot, N, Ham, psi):
    dt = t_tot / N  #N is number of steps
    t = sp.linspace(0, t_tot, N + 1)
    y = [psi]
    for i in range(len(t) - 1):
        k1 = dt * TDSE_T(Ham, t[i], y[len(y) - 1])
        k2 = dt * TDSE_T(Ham, t[i] + 0.5 * dt, y[len(y) - 1] + k1 / 2)
        k3 = dt * TDSE_T(Ham, t[i] + 0.5 * dt, y[len(y) - 1] + k2 / 2)
        k4 = dt * TDSE_T(Ham, t[i] + dt, y[len(y) - 1] + k3)
        ynew = y[len(y) - 1] + (k1 + 2 * k2 + 2 * k3 + k4) / 6
        y.append(ynew)
    chi = []
    for i in range(len(y)):
        inneri = sp.matmul(sp.conjugate(psi), y[i])
        inner = abs(inneri)**2
        chi.append(inner)
    return t, chi
Ejemplo n.º 21
0
def firstlyapunov(X, F, w, J_coords=None, V=None, W=None, p=None, q=None, check=False):
	if J_coords is None:
		J_coords = F.jac(X, F.coords)
	
	if p is None:
		alpha = bilinearform(transpose(J_coords),V[:,0],V[:,1]) - \
				1j*w*matrixmultiply(V[:,0],V[:,1])
		beta = -1*bilinearform(transpose(J_coords),V[:,0],V[:,0]) + \
				1j*w*matrixmultiply(V[:,0],V[:,0])
		q = alpha*V[:,0] + beta*V[:,1]
		
		alpha = bilinearform(J_coords,W[:,0],W[:,1]) + \
				1j*w*matrixmultiply(W[:,0],W[:,1])
		beta = -1*bilinearform(J_coords,W[:,0],W[:,0]) - \
				1j*w*matrixmultiply(W[:,0],W[:,0])
		p = alpha*W[:,0] + beta*W[:,1]
		
		p /= linalg.norm(p)
		q /= linalg.norm(q)
		
		direc = conjugate(1/matrixmultiply(conjugate(p),q))
		p = direc*p
	
	if check:
		print 'Checking...'
		print '  |q| = %f' % linalg.norm(q)
		temp = matrixmultiply(conjugate(p),q)
		print '  |<p,q> - 1| = ', abs(temp-1) 	
		print '  |Aq - iwq| = %f' % linalg.norm(matrixmultiply(J_coords,q) - 1j*w*q)
		print '  |A*p + iwp| = %f\n' % linalg.norm(matrixmultiply(transpose(J_coords),p) + 1j*w*p)
	
	# Compute first lyapunov coefficient
	B = F.hess(X, F.coords, F.coords)
	D = hess3(F, X, F.coords)
	b1 = array([bilinearform(B[i,:,:], q, q) for i in range(B.shape[0])])
	b2 = array([bilinearform(B[i,:,:], conjugate(q), linalg.solve(2*1j*w*eye(F.m) - J_coords, b1)) \
			for i in range(B.shape[0])])
	b3 = array([bilinearform(B[i,:,:], q, conjugate(q)) for i in range(B.shape[0])])
	b4 = array([bilinearform(B[i,:,:], q, linalg.solve(J_coords, b3)) for i in range(B.shape[0])])
	temp = array([trilinearform(D[i,:,:,:],q,q,conjugate(q)) for i in range(D.shape[0])]) + b2 - 2*b4

	l1 = 0.5*real(matrixmultiply(conjugate(p), temp))
	
	return l1
Ejemplo n.º 22
0
def f_osc(qw, E_X, a_2D, E_p = 25.0):
    """Formula for the oscilator strength per unit area [nm^-2] at k_par = 0.

    Based on Eq. (2) Andreani and Bassani, PRB 41, 7536 (1990)

    Keyword argumets:
        qw -> quantum well object. Class defined in binding.py
        E_X -> Exciton binding energy.
        a_2D -> Exciton radial extension (aka lambda parameter)
        E_p -> Kane parameter (dipole |S> |X> matrix element)
    """

    E_tr = (qw.Elec.E - qw.Hole.E) + E_X

    # Overlapp matrix element
    I_cv = spi.trapz(sp.conjugate(qw.Elec.wf)*qw.Hole.wf, qw.grid)

    F_QW_sq = 2.0/(sp.pi * a_2D**2)

    return E_p/E_tr * I_cv.real**2 * F_QW_sq
Ejemplo n.º 23
0
    def norm(self, component=None, summed=False):
        r"""Calculate the :math:`L^2` norm :math:`\langle\Psi|\Psi\rangle` of the wavepacket :math:`\Psi`.

        :param component: The index :math:`i` of the component :math:`\Phi_i` whose norm is calculated.
                          The default value is ``None`` which means to compute the norms of all :math:`N` components.
        :type component: int or ``None``.
        :param summed: Whether to sum up the norms :math:`\langle\Phi_i|\Phi_i\rangle` of the
                       individual components :math:`\Phi_i`.
        :type summed: Boolean, default is ``False``.
        :type summed: Boolean, default is ``False``.
        :return: The norm of :math:`\Psi` or the norm of :math:`\Phi_i` or a list with the :math:`N`
                 norms of all components. Depending on the values of ``component`` and ``summed``.
        """
        if component is not None:
            result = norm(self._coefficients[component])
        else:
            result = [ norm(item) for item in self._coefficients ]

            if summed is True:
                result = reduce(lambda x,y: x+conjugate(y)*y, result, 0.0)
                result = sqrt(result)

        return result
Ejemplo n.º 24
0
def H(m, out=None):
    """Matrix conjugate transpose (adjoint).
    
    This is just a shortcut for performing this operation on normal ndarrays.
    
    Parameters
    ----------
    m : ndarray
        The input matrix.
    out : ndarray
        A matrix to hold the final result (dimensions must be correct). May be None.
        May also be the same object as m.

    Returns
    -------
    out : ndarray
        The result.    
    """
    if out is None:
        return m.T.conj()
    else:
        out = sp.conjugate(m.T, out)
        return out
Ejemplo n.º 25
0
def H(m, out=None):
    """Matrix conjugate transpose (adjoint).
    
    This is just a shortcut for performing this operation on normal ndarrays.
    
    Parameters
    ----------
    m : ndarray
        The input matrix.
    out : ndarray
        A matrix to hold the final result (dimensions must be correct). May be None.
        May also be the same object as m.

    Returns
    -------
    out : ndarray
        The result.    
    """
    if out is None:
        return m.T.conj()
    else:
        out = sp.conjugate(m.T, out)
        return out
Ejemplo n.º 26
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
Ejemplo n.º 27
0
def firstlyapunov(X,
                  F,
                  w,
                  J_coords=None,
                  V=None,
                  W=None,
                  p=None,
                  q=None,
                  check=False):
    if J_coords is None:
        J_coords = F.jac(X, F.coords)

    if p is None:
        alpha = bilinearform(transpose(J_coords),V[:,0],V[:,1]) - \
          1j*w*matrixmultiply(V[:,0],V[:,1])
        beta = -1*bilinearform(transpose(J_coords),V[:,0],V[:,0]) + \
          1j*w*matrixmultiply(V[:,0],V[:,0])
        q = alpha * V[:, 0] + beta * V[:, 1]

        alpha = bilinearform(J_coords,W[:,0],W[:,1]) + \
          1j*w*matrixmultiply(W[:,0],W[:,1])
        beta = -1*bilinearform(J_coords,W[:,0],W[:,0]) - \
          1j*w*matrixmultiply(W[:,0],W[:,0])
        p = alpha * W[:, 0] + beta * W[:, 1]

        p /= linalg.norm(p)
        q /= linalg.norm(q)

        direc = conjugate(1 / matrixmultiply(conjugate(p), q))
        p = direc * p

    if check:
        print 'Checking...'
        print '  |q| = %f' % linalg.norm(q)
        temp = matrixmultiply(conjugate(p), q)
        print '  |<p,q> - 1| = ', abs(temp - 1)
        print '  |Aq - iwq| = %f' % linalg.norm(
            matrixmultiply(J_coords, q) - 1j * w * q)
        print '  |A*p + iwp| = %f\n' % linalg.norm(
            matrixmultiply(transpose(J_coords), p) + 1j * w * p)

    # Compute first lyapunov coefficient
    B = F.hess(X, F.coords, F.coords)
    D = hess3(F, X, F.coords)
    b1 = array([bilinearform(B[i, :, :], q, q) for i in range(B.shape[0])])
    b2 = array([bilinearform(B[i,:,:], conjugate(q), linalg.solve(2*1j*w*eye(F.m) - J_coords, b1)) \
      for i in range(B.shape[0])])
    b3 = array(
        [bilinearform(B[i, :, :], q, conjugate(q)) for i in range(B.shape[0])])
    b4 = array([
        bilinearform(B[i, :, :], q, linalg.solve(J_coords, b3))
        for i in range(B.shape[0])
    ])
    temp = array([
        trilinearform(D[i, :, :, :], q, q, conjugate(q))
        for i in range(D.shape[0])
    ]) + b2 - 2 * b4

    l1 = 0.5 * real(matrixmultiply(conjugate(p), temp))

    return l1
Ejemplo n.º 28
0
    def measure_shift(self, checkimage):
        """Generate a check image and measure its offset from the reference
        This is done using the same settings as the reference image.

        Parameters
        ----------
        checkimage : str
            Image filename to compare to reference image

        Returns
        -------
        solution_n_x : float
            The shift required, in X, to recentre the checkimage into the reference frame
        solution_n_y : float
            The shift required, in Y, to recentre the checkimage into the reference frame

        Raises
        ------
        None
        """
        self.checkimage = checkimage
        h = fits.open(self.checkimage)
        self.check_image_section = h[self.image_ext].data[:, self.prescan_width:-self.overscan_width]
        self.check_data = self.check_image_section[self.boarder:self.dimy - self.boarder,
                                                   self.boarder:self.dimx - self.boarder]

        # adjust image if requested - same as reference
        if self.subtract_bkg:
            self.check_bkgmap = self.__generate_bkg_map(self.check_data, self.ntiles,
                                                        self.tilesizex, self.tilesizey)
            self.check_data = self.check_data - self.check_bkgmap
        if self.normalise:
            self.check_data = self.check_data / self.texp
        self.check_xproj = np.sum(self.check_data, axis=0)
        self.check_yproj = np.sum(self.check_data, axis=1)
        # FFT of the projection spectra
        f_ref_xproj_n = fft(self.ref_xproj)
        f_ref_yproj_n = fft(self.ref_yproj)
        f_check_xproj_n = fft(self.check_xproj)
        f_check_yproj_n = fft(self.check_yproj)
        # cross correlate in and look for the maximium correlation
        f_ref_xproj_conj_n = conjugate(f_ref_xproj_n)
        f_ref_yproj_conj_n = conjugate(f_ref_yproj_n)
        complex_sum_x_n = f_ref_xproj_conj_n * f_check_xproj_n
        complex_sum_y_n = f_ref_yproj_conj_n * f_check_yproj_n
        phi_ref_check_m_x_n = ifft(complex_sum_x_n)
        phi_ref_check_m_y_n = ifft(complex_sum_y_n)
        z_x_n = max(phi_ref_check_m_x_n)
        z_pos_x_n = np.where(phi_ref_check_m_x_n == z_x_n)
        z_y_n = max(phi_ref_check_m_y_n)
        z_pos_y_n = np.where(phi_ref_check_m_y_n == z_y_n)
        # turn the location of the maximum into shift in pixels
        # quadratically interpolate over the 3 pixels surrounding
        # the peak in the CCF. This gives sub pixel resolution.
        tst_y = np.empty(3)
        tst_x = np.empty(3)
        # X
        if z_pos_x_n[0][0] <= len(phi_ref_check_m_x_n) / 2:
            lra_x = [z_pos_x_n[0][0] - 1, z_pos_x_n[0][0], z_pos_x_n[0][0] + 1]
            tst_x[0] = phi_ref_check_m_x_n[lra_x[0]].real
            tst_x[1] = phi_ref_check_m_x_n[lra_x[1]].real
            tst_x[2] = phi_ref_check_m_x_n[lra_x[2]].real
            coeffs_n_x = polyfit(lra_x, tst_x, 2)
            self.solution_n_x = -(-coeffs_n_x[1] / (2 * coeffs_n_x[0]))
        elif z_pos_x_n[0][0] > len(phi_ref_check_m_x_n) / 2 and z_pos_x_n[0][0] != len(phi_ref_check_m_x_n) - 1:
            lra_x = [z_pos_x_n[0][0] - 1, z_pos_x_n[0][0], z_pos_x_n[0][0] + 1]
            tst_x[0] = phi_ref_check_m_x_n[lra_x[0]].real
            tst_x[1] = phi_ref_check_m_x_n[lra_x[1]].real
            tst_x[2] = phi_ref_check_m_x_n[lra_x[2]].real
            coeffs_n_x = polyfit(lra_x, tst_x, 2)
            self.solution_n_x = len(phi_ref_check_m_x_n) + (coeffs_n_x[1] / (2 * coeffs_n_x[0]))
        elif z_pos_x_n[0][0] == len(phi_ref_check_m_x_n) - 1:
            lra_x = [-1, 0, 1]
            tst_x[0] = phi_ref_check_m_x_n[-2].real
            tst_x[1] = phi_ref_check_m_x_n[-1].real
            tst_x[2] = phi_ref_check_m_x_n[0].real
            coeffs_n_x = polyfit(lra_x, tst_x, 2)
            self.solution_n_x = 1 + (coeffs_n_x[1] / (2 * coeffs_n_x[0]))
        else: #if z_pos_x_n[0][0] == 0:
            lra_x = [1, 0, -1]
            tst_x[0] = phi_ref_check_m_x_n[-1].real
            tst_x[1] = phi_ref_check_m_x_n[0].real
            tst_x[2] = phi_ref_check_m_x_n[1].real
            coeffs_n_x = polyfit(lra_x, tst_x, 2)
            self.solution_n_x = -coeffs_n_x[1] / (2 * coeffs_n_x[0])
        print("X: {0:.2f}".format(self.solution_n_x))
        # Y
        if z_pos_y_n[0][0] <= len(phi_ref_check_m_y_n)/2:
            lra_y = [z_pos_y_n[0][0] - 1, z_pos_y_n[0][0], z_pos_y_n[0][0] + 1]
            tst_y[0] = phi_ref_check_m_y_n[lra_y[0]].real
            tst_y[1] = phi_ref_check_m_y_n[lra_y[1]].real
            tst_y[2] = phi_ref_check_m_y_n[lra_y[2]].real
            coeffs_n_y = polyfit(lra_y, tst_y, 2)
            self.solution_n_y = -(-coeffs_n_y[1]/(2*coeffs_n_y[0]))
        if z_pos_y_n[0][0] > len(phi_ref_check_m_y_n) / 2 and z_pos_y_n[0][0] != len(phi_ref_check_m_y_n) - 1:
            lra_y = [z_pos_y_n[0][0]-1, z_pos_y_n[0][0], z_pos_y_n[0][0]+1]
            tst_y[0] = phi_ref_check_m_y_n[lra_y[0]].real
            tst_y[1] = phi_ref_check_m_y_n[lra_y[1]].real
            tst_y[2] = phi_ref_check_m_y_n[lra_y[2]].real
            coeffs_n_y = polyfit(lra_y, tst_y, 2)
            self.solution_n_y = len(phi_ref_check_m_y_n) + (coeffs_n_y[1] / (2 * coeffs_n_y[0]))
        if z_pos_y_n[0][0] == len(phi_ref_check_m_y_n) - 1:
            lra_y = [-1, 0, 1]
            tst_y[0] = phi_ref_check_m_y_n[-2].real
            tst_y[1] = phi_ref_check_m_y_n[-1].real
            tst_y[2] = phi_ref_check_m_y_n[0].real
            coeffs_n_y = polyfit(lra_y, tst_y, 2)
            self.solution_n_y = 1 + (coeffs_n_y[1] / (2 * coeffs_n_y[0]))
        else: #if z_pos_y_n[0][0] == 0:
            lra_y = [1, 0, -1]
            tst_y[0] = phi_ref_check_m_y_n[-1].real
            tst_y[1] = phi_ref_check_m_y_n[0].real
            tst_y[2] = phi_ref_check_m_y_n[1].real
            coeffs_n_y = polyfit(lra_y, tst_y, 2)
            self.solution_n_y = -coeffs_n_y[1] / (2 * coeffs_n_y[0])
        print("Y: {0:.2f}".format(self.solution_n_y))
        return self.solution_n_x, self.solution_n_y
Ejemplo n.º 29
0
    def evaluate_basis_at(self, grid, component, prefactor=False):
        r"""Evaluate the basis functions :math:`\phi_k` recursively at the given nodes :math:`\gamma`.

        :param grid: The grid :math:`\Gamma` containing the nodes :math:`\gamma`.
        :type grid: A class having a :py:meth:`get_nodes(...)` method.
        :param component: The index :math:`i` of a single component :math:`\Phi_i` to evaluate.
        :param prefactor: Whether to include a factor of :math:`\frac{1}{\sqrt{\det(Q)}}`.
        :type prefactor: Boolean, default is ``False``.
        :return: A two-dimensional ndarray :math:`H` of shape :math:`(|\mathfrak{K}_i|, |\Gamma|)` where
                 the entry :math:`H[\mu(k), i]` is the value of :math:`\phi_k(\gamma_i)`.
        """
        D = self._dimension

        bas = self._basis_shapes[component]
        bs = self._basis_sizes[component]

        # The grid
        grid = self._grid_wrap(grid)
        nodes = grid.get_nodes()
        nn = grid.get_number_nodes(overall=True)

        # Allocate the storage array
        phi = zeros((bs, nn), dtype=complexfloating)

        # Precompute some constants
        Pi = self.get_parameters(component=component)
        q, p, Q, P, S = Pi

        Qinv = inv(Q)
        Qbar = conjugate(Q)
        QQ = dot(Qinv, Qbar)

        # Compute the ground state phi_0 via direct evaluation
        mu0 = bas[tuple(D * [0])]
        phi[mu0, :] = self._evaluate_phi0(component, nodes, prefactor=False)

        # Compute all higher order states phi_k via recursion
        for d in range(D):
            # Iterator for all valid index vectors k
            indices = bas.get_node_iterator(mode="chain", direction=d)

            for k in indices:
                # Current index vector
                ki = vstack(k)

                # Access predecessors
                phim = zeros((D, nn), dtype=complexfloating)

                for j, kpj in bas.get_neighbours(k, selection="backward"):
                    mukpj = bas[kpj]
                    phim[j, :] = phi[mukpj, :]

                # Compute 3-term recursion
                p1 = (nodes - q) * phi[bas[k], :]
                p2 = sqrt(ki) * phim

                t1 = sqrt(2.0 / self._eps**2) * dot(Qinv[d, :], p1)
                t2 = dot(QQ[d, :], p2)

                # Find multi-index where to store the result
                kped = bas.get_neighbours(k, selection="forward", direction=d)

                # Did we find this k?
                if len(kped) > 0:
                    kped = kped[0]

                    # Store computed value
                    phi[bas[kped[1]], :] = (t1 - t2) / sqrt(ki[d] + 1.0)

        if prefactor is True:
            phi = phi / self._get_sqrt(component)(det(Q))

        return phi
Ejemplo n.º 30
0
#!/home/paulk/software/bin/python
from __future__ import division
from sys import argv,exit,stderr
import scipy
import scipy.linalg as SLA

# generate random values for X and Y
X = scipy.transpose(scipy.mat(scipy.random.random((5,5))))
Y = scipy.transpose(scipy.mat(scipy.random.random(5)))

print "X = \n",X
print
print "Y = \n",Y
print
print "-----------------------------------------"
# use least squares to get B, the regression parameters
A = SLA.lstsq(X,Y)

print "scipy.lstsq: A = \n",A[0]
print
print "hermetian: A = \n",SLA.inv(scipy.conjugate(scipy.transpose(X))*X)*scipy.conjugate(scipy.transpose(X))*Y
print
print "non-hermetian: A = \n",SLA.inv(scipy.transpose(X)*X)*scipy.transpose(X)*Y
print
Ejemplo n.º 31
0
    def slim_recursion(self, grid, component, prefactor=False):
        r"""Evaluate the Hagedorn wavepacket :math:`\Psi` at the given nodes :math:`\gamma`.
        This routine is a slim version compared to the full basis evaluation. At every moment
        we store only the data we really need to compute the next step until we hit the highest
        order basis functions.

        :param grid: The grid :math:`\Gamma` containing the nodes :math:`\gamma`.
        :type grid: A class having a :py:meth:`get_nodes(...)` method.
        :param component: The index :math:`i` of a single component :math:`\Phi_i` to evaluate.
        :param prefactor: Whether to include a factor of :math:`\frac{1}{\sqrt{\det(Q)}}`.
        :type prefactor: Boolean, default is ``False``.
        :return: A list of arrays or a single array containing the values of the :math:`\Phi_i`
                 at the nodes :math:`\gamma`.

        Note that this function does not include the global phase :math:`\exp(\frac{i S}{\varepsilon^2})`.
        """
        D = self._dimension

        # Precompute some constants
        Pi = self.get_parameters(component=component)
        q, p, Q, P, S = Pi

        Qinv = inv(Q)
        Qbar = conjugate(Q)
        QQ = dot(Qinv, Qbar)

        # The basis shape
        bas = self._basis_shapes[component]
        Z = tuple(D * [0])

        # Book keeping
        todo = []
        newtodo = [Z]
        olddelete = []
        delete = []
        tmp = {}

        # The grid nodes
        grid = self._grid_wrap(grid)
        nn = grid.get_number_nodes(overall=True)
        nodes = grid.get_nodes()

        # Evaluate phi0
        tmp[Z] = self._evaluate_phi0(component, nodes, prefactor=False)
        psi = self._coefficients[component][bas[Z], 0] * tmp[Z]

        # Iterate for higher order states
        while len(newtodo) != 0:
            # Delete results that never will be used again
            for d in olddelete:
                del tmp[d]

            # Exchange queues
            todo = newtodo
            newtodo = []
            olddelete = delete
            delete = []

            # Compute new results
            for k in todo:
                # Center stencil at node k
                ki = vstack(k)

                # Access predecessors
                phim = zeros((D, nn), dtype=complexfloating)
                for j, kpj in bas.get_neighbours(k, selection="backward"):
                    phim[j, :] = tmp[kpj]

                # Compute the neighbours
                for d, n in bas.get_neighbours(k, selection="forward"):
                    if n not in tmp.keys():
                        # Compute 3-term recursion
                        p1 = (nodes - q) * tmp[k]
                        p2 = sqrt(ki) * phim

                        t1 = sqrt(2.0 / self._eps**2) * dot(Qinv[d, :], p1)
                        t2 = dot(QQ[d, :], p2)

                        # Store computed value
                        tmp[n] = (t1 - t2) / sqrt(ki[d] + 1.0)
                        # And update the result
                        psi = psi + self._coefficients[component][bas[n],
                                                                  0] * tmp[n]

                        newtodo.append(n)
                delete.append(k)

        if prefactor is True:
            psi = psi / self._get_sqrt(component)(det(Q))

        return psi
Ejemplo n.º 32
0
parcelTimeSeries = scipy.exp(1j *
                             (scipy.asmatrix(scipy.angle(parcelTimeSeries))))

########## Get cPLV needed for flips and weighting

cPLVArray = 1j * scipy.zeros(len(sourceIdentities),
                             dtype=float)  # Initialize as zeros (complex).

for i, identity in enumerate(
        sourceIdentities
):  # Compute cPLV only of parcel source pairs of sources that belong to that parcel. One source belong to only one parcel.
    if sourceIdentities[
            i] >= 0:  # Don't compute negative values. These should be sources not belonging to any parcel.
        cPLVArray[i] = scipy.sum(
            (scipy.asarray(parcelTimeSeries[identity])) *
            scipy.conjugate(scipy.asarray(sourceTimeSeries[i])))

cPLVArray /= timeOutput  # Normalize by samples. For debugging. Output doesn't change even if you don't do this.

########## Get weights and flip. This could be the output.

weights = scipy.zeros(len(sourceIdentities))  # Initialize as zeros

for i, cPLV in enumerate(cPLVArray):
    weights[i] = scipy.real(cPLV)**2 * scipy.sign(
        scipy.real(cPLV))  # Sign is the flip; weight (real part)^2

########## Create weighted inverse operator and normalize the norm of weighted inv op to match original inv op's norm.
weightedInvOp = np.dot(
    scipy.eye(weights.shape[0]) * weights, inverseOperator
)  # Multiply sensor dimension in inverseOperator by weight. This one would be the un-normalized operator.
Ejemplo n.º 33
0
def absq(x):
    return x*sp.conjugate(x)
Ejemplo n.º 34
0
    print "%.3f " % (time.clock() - t_solving), "secondes passed"

    print "V_port = "
    print V_port
    print "I_port = "
    print I_port

    print "==" * 30

    # In[]

    t_cal_gain = time.clock()
    direct = calGain()

    D0 = np.max(direct[1][2]) / scipy.real(
        scipy.sum(scipy.conjugate(V_port) * I_port)) * 2 * pi4

    print "gain obtained"
    print "%.3f " % (time.clock() - t_cal_gain), "secondes passed"

    print "direct = ", D0
    print "gain = ", 10. * np.log10(D0), 'dBi'
    print "==" * 30

    from mpl_toolkits.mplot3d import Axes3D
    import matplotlib.pyplot as plt
    import numpy as np

    ths, phs, aug = direct[1]
    ts, ps = np.meshgrid(ths, phs)
Ejemplo n.º 35
0
    def evaluate_basis_at(self, grid, component, prefactor=False):
        r"""Evaluate the basis functions :math:`\phi_k` recursively at the given nodes :math:`\gamma`.

        :param grid: The grid :math:`\Gamma` containing the nodes :math:`\gamma`.
        :type grid: A class having a :py:meth:`get_nodes(...)` method.
        :param component: The index :math:`i` of a single component :math:`\Phi_i` to evaluate.
        :param prefactor: Whether to include a factor of :math:`\frac{1}{\sqrt{\det(Q)}}`.
        :type prefactor: Boolean, default is ``False``.
        :return: A two-dimensional ndarray :math:`H` of shape :math:`(|\mathfrak{K}_i|, |\Gamma|)` where
                 the entry :math:`H[\mu(k), i]` is the value of :math:`\phi_k(\gamma_i)`.
        """
        D = self._dimension

        bas = self._basis_shapes[component]
        bs = self._basis_sizes[component]

        # The grid
        grid = self._grid_wrap(grid)
        nodes = grid.get_nodes()
        nn = grid.get_number_nodes(overall=True)

        # Allocate the storage array
        phi = zeros((bs, nn), dtype=complexfloating)

        # Precompute some constants
        Pi = self.get_parameters(component=component)
        q, p, Q, P, S = Pi

        Qinv = inv(Q)
        Qbar = conjugate(Q)
        QQ = dot(Qinv, Qbar)

        # Compute the ground state phi_0 via direct evaluation
        mu0 = bas[tuple(D * [0])]
        phi[mu0, :] = self._evaluate_phi0(component, nodes, prefactor=False)

        # Compute all higher order states phi_k via recursion
        for d in range(D):
            # Iterator for all valid index vectors k
            indices = bas.get_node_iterator(mode="chain", direction=d)

            for k in indices:
                # Current index vector
                ki = vstack(k)

                # Access predecessors
                phim = zeros((D, nn), dtype=complexfloating)

                for j, kpj in bas.get_neighbours(k, selection="backward"):
                    mukpj = bas[kpj]
                    phim[j, :] = phi[mukpj, :]

                # Compute 3-term recursion
                p1 = (nodes - q) * phi[bas[k], :]
                p2 = sqrt(ki) * phim

                t1 = sqrt(2.0 / self._eps**2) * dot(Qinv[d, :], p1)
                t2 = dot(QQ[d, :], p2)

                # Find multi-index where to store the result
                kped = bas.get_neighbours(k, selection="forward", direction=d)

                # Did we find this k?
                if len(kped) > 0:
                    kped = kped[0]

                    # Store computed value
                    phi[bas[kped[1]], :] = (t1 - t2) / sqrt(ki[d] + 1.0)

        if prefactor is True:
            phi = phi / self._get_sqrt(component)(det(Q))

        return phi
Ejemplo n.º 36
0
    def slim_recursion(self, grid, component, prefactor=False):
        r"""Evaluate the Hagedorn wavepacket :math:`\Psi` at the given nodes :math:`\gamma`.
        This routine is a slim version compared to the full basis evaluation. At every moment
        we store only the data we really need to compute the next step until we hit the highest
        order basis functions.

        :param grid: The grid :math:`\Gamma` containing the nodes :math:`\gamma`.
        :type grid: A class having a :py:meth:`get_nodes(...)` method.
        :param component: The index :math:`i` of a single component :math:`\Phi_i` to evaluate.
        :param prefactor: Whether to include a factor of :math:`\frac{1}{\sqrt{\det(Q)}}`.
        :type prefactor: Boolean, default is ``False``.
        :return: A list of arrays or a single array containing the values of the :math:`\Phi_i`
                 at the nodes :math:`\gamma`.

        Note that this function does not include the global phase :math:`\exp(\frac{i S}{\varepsilon^2})`.
        """
        D = self._dimension

        # Precompute some constants
        Pi = self.get_parameters(component=component)
        q, p, Q, P, S = Pi

        Qinv = inv(Q)
        Qbar = conjugate(Q)
        QQ = dot(Qinv, Qbar)

        # The basis shape
        bas = self._basis_shapes[component]
        Z = tuple(D * [0])

        # Book keeping
        todo = []
        newtodo = [Z]
        olddelete = []
        delete = []
        tmp = {}

        # The grid nodes
        grid = self._grid_wrap(grid)
        nn = grid.get_number_nodes(overall=True)
        nodes = grid.get_nodes()

        # Evaluate phi0
        tmp[Z] = self._evaluate_phi0(component, nodes, prefactor=False)
        psi = self._coefficients[component][bas[Z], 0] * tmp[Z]

        # Iterate for higher order states
        while len(newtodo) != 0:
            # Delete results that never will be used again
            for d in olddelete:
                del tmp[d]

            # Exchange queues
            todo = newtodo
            newtodo = []
            olddelete = delete
            delete = []

            # Compute new results
            for k in todo:
                # Center stencil at node k
                ki = vstack(k)

                # Access predecessors
                phim = zeros((D, nn), dtype=complexfloating)
                for j, kpj in bas.get_neighbours(k, selection="backward"):
                    phim[j, :] = tmp[kpj]

                # Compute the neighbours
                for d, n in bas.get_neighbours(k, selection="forward"):
                    if n not in tmp.keys():
                        # Compute 3-term recursion
                        p1 = (nodes - q) * tmp[k]
                        p2 = sqrt(ki) * phim

                        t1 = sqrt(2.0 / self._eps**2) * dot(Qinv[d, :], p1)
                        t2 = dot(QQ[d, :], p2)

                        # Store computed value
                        tmp[n] = (t1 - t2) / sqrt(ki[d] + 1.0)
                        # And update the result
                        psi = psi + self._coefficients[component][bas[n], 0] * tmp[n]

                        newtodo.append(n)
                delete.append(k)

        if prefactor is True:
            psi = psi / self._get_sqrt(component)(det(Q))

        return psi
Ejemplo n.º 37
0
def genRadiationPattern2(ths_phs):
    try:
        #        print ths_phs
        RPs = [0 for _ in ths_phs]
        # 定义一个辅助空间保存各个单元的因子,其作用是利用向量乘积的办法计算远处的电场
        rr = 100.0
        # 对方向角度中的集合进行迭代
        brs = np.zeros([len(ths_phs), 3])
        for iid, th_ph in enumerate(ths_phs):

            th0, ph0 = th_ph  # 俯仰角和方位角
            # 根据俯仰角和方位角计算三个向量
            try:
                th0, ph0 = th_ph  # 俯仰角和方位角
                # 根据俯仰角和方位角计算三个向量
                if th0 >= 0 and th0 <= scipy.pi:
                    br = np.array([
                        scipy.sin(th0) * scipy.cos(ph0),
                        scipy.sin(th0) * scipy.sin(ph0),
                        scipy.cos(th0)
                    ]) * rr  # 1.j*k向量
                elif th0 < 0 and th0 >= -scipy.pi:
                    th0 = -th0
                    ph0 = ph0 + scipy.pi
                    br = np.array([
                        scipy.sin(th0) * scipy.cos(ph0),
                        scipy.sin(th0) * scipy.sin(ph0),
                        scipy.cos(th0)
                    ]) * rr  # 1.j*k向量
                elif th0 > scipy.pi and th0 <= scipy.pi * 2.0:
                    th0 = th0 - scipy.pi
                    ph0 = ph0 + scipy.pi
                    br = np.array([
                        scipy.sin(th0) * scipy.cos(ph0),
                        scipy.sin(th0) * scipy.sin(ph0),
                        scipy.cos(th0)
                    ]) * rr  # 1.j*k向量
            except Exception as e:
                print e
                raise
            brs[iid] = br
        EEs = scipy.array([calE_total(br_cell) for br_cell in brs])
        HHs = scipy.array([calH_total(br_cell) for br_cell in brs])
        WWs = scipy.array([
            scipy.real(scipy.cross(EE, scipy.conjugate(HH)))
            for EE, HH in zip(EEs, HHs)
        ]) * 0.5
        RPs = scipy.array(
            [rr * np.dot(WW, br_cell) for WW, br_cell in zip(WWs, brs)])
        #    for br in brs:
        #        # 计算电场
        #        EE = calE_total(br)
        #        # 计算磁场
        #        HH = calH_total(br)
        #        # 计算坡印廷矢量
        #        WW = scipy.real(scipy.cross(EE,scipy.conjugate(HH)))*0.5
        #        # 计算功率密度
        #        UU = rr*np.dot(WW,br)
        #        # 保存,并返回
        #        RPs[iid] = UU

        return RPs
    except Exception as e:
        print e
        print ths_phs
        print np.shape(brs)
        print br
        raise
Ejemplo n.º 38
0
Archivo: QM.py Proyecto: Embreus/NHQM
 def integrand(x):
     return sp.conjugate( f(x) ) * f(x) * weight(x);