Example #1
1
    def test_init(self):
        import numpy as np
        import math
        import sys

        assert np.intp() == np.intp(0)
        assert np.intp("123") == np.intp(123)
        raises(TypeError, np.intp, None)
        assert np.float64() == np.float64(0)
        assert math.isnan(np.float64(None))
        assert np.bool_() == np.bool_(False)
        assert np.bool_("abc") == np.bool_(True)
        assert np.bool_(None) == np.bool_(False)
        assert np.complex_() == np.complex_(0)
        # raises(TypeError, np.complex_, '1+2j')
        assert math.isnan(np.complex_(None))
        for c in ["i", "I", "l", "L", "q", "Q"]:
            assert np.dtype(c).type().dtype.char == c
        for c in ["l", "q"]:
            assert np.dtype(c).type(sys.maxint) == sys.maxint
        for c in ["L", "Q"]:
            assert np.dtype(c).type(sys.maxint + 42) == sys.maxint + 42
        assert np.float32(np.array([True, False])).dtype == np.float32
        assert type(np.float32(np.array([True]))) is np.ndarray
        assert type(np.float32(1.0)) is np.float32
        a = np.array([True, False])
        assert np.bool_(a) is a
Example #2
0
	def fun(self,t, args):
		"""Maximum likelihood function to be minimized.

		:param numpy_array t: t values.
		:param numpy_array args: first entry contains correlation counts, second the corresponding basis as string.
		:param numpy_array args: PSIs, all possible basis as Jones vectors.

		:return: Function value. See for further information D. F. V. James et al. Phys. Rev. A, 64, 052312 (2001).
		:rtype: numpy float
		"""
		corr_counts=args[0]
		basis=args[1]
		PSI=args[2]
		nbrOfElements=len(basis)

		rho_phys = self.rho_phys(t)

		#Estimate NormFactor
		estNormFactor=[]

		for i in range(len(corr_counts)):
			estNormFactor.append(np.dot(np.dot(np.conj(PSI[i]), rho_phys),PSI[i]))

		NormFactor=np.sum(corr_counts)/np.sum(estNormFactor)

		#Optimize density matrix
		BraRoh_physKet = np.complex_(np.zeros(nbrOfElements))

		for i in range(nbrOfElements):
			rhoket = np.array(np.dot(rho_phys,PSI[i]).flat) #Convert 2d to 1d array with flat
			BraRoh_physKet[i] = np.complex_(np.dot(np.conj(PSI[i]), rhoket))

		return np.real(np.sum((NormFactor*BraRoh_physKet-corr_counts)**2.0/(2.0*NormFactor*BraRoh_physKet)))
def t1_roots(dT12, dT13, V_cm_norm):
    alpha = dT12 * dT13
    beta = dT12 + dT13
    a = np.complex_(-3 * V_cm_norm)
    b = np.complex_(L1 + L2 + L3 - 3 * V_cm_norm * beta)
    c = np.complex_(L1 * beta + dT13 * L2 + dT12 * L3 - 3 * V_cm_norm * alpha)
    d = np.complex_(alpha * L1)

    #Compute roots of polynom at**3 + bt**2 + ct + d = 0

    t1_1 = (np.sqrt((-27*a**2*d + 9*a*b*c - 2*b**3)**2 + 4*(3*a*c - b**2)**3) \
    - 27*a**2*d + 9*a*b*c - 2*b**3)**(1.0/3)/(3*2**(1.0/3)*a) \
    - (2**(1.0/3)*(3*a*c - b**2))/(3*a*(np.sqrt((-27*a**2*d + 9*a*b*c - 2*b**3)**2 \
    + 4*(3*a*c - b**2)**3) - 27*a**2*d + 9*a*b*c - 2*b**3)**(1.0/3)) - b/(3*a)

    t1_2 = -((1 - 1j*np.sqrt(3))*(np.sqrt((-27*a**2*d + 9*a*b*c - 2*b**3)**2 + \
    4*(3*a*c - b**2)**3) - 27*a**2*d + 9*a*b*c - 2*b**3)**(1.0/3))/(6*2**(1.0/3)*a) + \
    ((1 + 1j*np.sqrt(3))*(3*a*c - b**2))/(3*2**(2.0/3)*a* \
    (np.sqrt((-27*a**2*d + 9*a*b*c - 2*b**3)**2 + 4*(3*a*c - b**2)**3) - 27*a**2*d + \
    9*a*b*c - 2*b**3)**(1.0/3)) - b/(3.0*a)

    t1_3 = -((1 + 1j*np.sqrt(3))*(np.sqrt((-27*a**2*d + 9*a*b*c - 2*b**3)**2 + \
    4*(3*a*c - b**2)**3) - 27*a**2*d + 9*a*b*c - 2*b**3)**(1.0/3))/(6*2**(1.0/3)*a) +\
    ((1 - 1j*np.sqrt(3))*(3*a*c - b**2))/(3.0*2**(2.0/3)*a*\
    (np.sqrt((-27*a**2*d + 9*a*b*c - 2*b**3)**2 + 4*(3*a*c - b**2)**3)\
    - 27*a**2*d + 9*a*b*c - 2*b**3)**(1.0/3)) - b/(3.0*a)

    return (t1_1, t1_2, t1_3)
Example #4
0
def cutregion_AgTri(eField,zlow=10.1e-9,zhigh=11.1e-9,xlow=-1e-9,xhigh=90e-9,ylow=-43e-9,yhigh=43e-9):
    x = eField[:,0].astype(float)
    y = eField[:,1].astype(float)
    z = eField[:,2].astype(float)
    Ez = eField[:,3]
    Ey = eField[:,4]
    Ex = eField[:,5]
    xlist = []
    ylist = []
    zlist = []
    Ezlist = []
    Eylist = []
    Exlist = []
    for k in range(len(z)):
        if z[k] < zhigh and z[k] > zlow:
            if x[k] < xhigh and x[k] > xlow:
                if y[k] < yhigh and y[k] > ylow:
                    xlist.append(x[k])
                    ylist.append(y[k])
                    zlist.append(z[k])
                    Ezlist.append(Ez[k])
                    Eylist.append(Ey[k])
                    Exlist.append(Ex[k])

    xlist = np.asarray(xlist)*1e9 #express in nanometers
    ylist = np.asarray(ylist)*1e9
    zlist = np.asarray(zlist)*1e9
    Ezlist = np.complex_(np.asarray(Ezlist))*1e3 #express in millivolts per meter
    Eylist = np.complex_(np.asarray(Eylist))*1e3
    Exlist = np.complex_(np.asarray(Exlist))*1e3
    return xlist,ylist,zlist,Ezlist,Eylist,Exlist
Example #5
0
 def test_init(self):
     import numpy as np
     import math
     import sys
     assert np.intp() == np.intp(0)
     assert np.intp('123') == np.intp(123)
     raises(TypeError, np.intp, None)
     assert np.float64() == np.float64(0)
     assert math.isnan(np.float64(None))
     assert np.bool_() == np.bool_(False)
     assert np.bool_('abc') == np.bool_(True)
     assert np.bool_(None) == np.bool_(False)
     assert np.complex_() == np.complex_(0)
     #raises(TypeError, np.complex_, '1+2j')
     assert math.isnan(np.complex_(None))
     for c in ['i', 'I', 'l', 'L', 'q', 'Q']:
         assert np.dtype(c).type().dtype.char == c
     for c in ['l', 'q']:
         assert np.dtype(c).type(sys.maxint) == sys.maxint
     for c in ['L', 'Q']:
         assert np.dtype(c).type(sys.maxint + 42) == sys.maxint + 42
     assert np.float32(np.array([True, False])).dtype == np.float32
     assert type(np.float32(np.array([True]))) is np.ndarray
     assert type(np.float32(1.0)) is np.float32
     a = np.array([True, False])
     assert np.bool_(a) is a
def fourier_coeffs(fun, modes, period, print_statements=False):
    output = np.zeros(2 * modes + 1, dtype=np.complex_)

    # speeds things up when a coefficient is, for all intents and purposes,
    # purely imaginary or real
    def truncate(n):
        if abs(np.real(output[modes + n])) < 1.0e-14:
            output[modes + n] = 1j * np.imag(output[modes + n])
        if abs(np.imag(output[modes + n])) < 1.0e-14:
            output[modes + n] = np.real(output[modes + n])

    # prints info about the progress of the computation; useful for FS that take
    # a long time to compute
    def progress(n):
        print('mode ' + str(n) + ' of ' + str(modes))
        print('c(' + str(-n) + ') = ' + str(output[modes - n]) + ', c(' +
              str(n) + ') = ' + str(output[modes + n]))

    output[modes] = cmp.complex_quad(fun, 0.5 * period) / period
    truncate(0)
    if print_statements:
        print('computing FS for ' + str(fun))
        print('mode 0 of ' + str(modes))
        print('c(0) = ' + str(output[modes]))

    # take sampling of points to determind if function is approx. real-valued
    # if so, computation can be expedited via symmetry
    sample = [
        fun(1.01 * x)
        for x in frange(-0.5 * period, 0.5 * period, 0.05 * period)
    ]

    if sum(abs(np.imag(sample))) < 0.01 * sum(abs(np.real(sample))):
        for k in range(1, modes + 1):
            output[modes - k] = cmp.complex_quad(
                lambda x: fun(x) * np.
                exp(np.complex_(
                    (-2j * k * np.pi / period) * x)), 0.5 * period) / period
            truncate(-k)
            output[modes + k] = np.conj(output[modes - k])
            if print_statements: progress(k)
    else:
        for k in range(1, modes + 1):
            output[modes - k] = cmp.complex_quad(
                lambda x: fun(x) * np.
                exp(np.complex_(
                    (-2j * k * np.pi / period) * x)), 0.5 * period) / period
            output[modes + k] = cmp.complex_quad(
                lambda x: fun(x) * np.exp(
                    np.complex_(
                        (2j * k * np.pi / period) * x)), 0.5 * period) / period
            truncate(-k)
            truncate(k)
            if print_statements: progress(k)

    return output
Example #7
0
def torch_spec_to_numpy_complex(Wave):
    """
    :param Wave:
    :param hop:
    :return: You Better Split ME [..., x]
    """
    Real = Wave[..., 0].cpu().numpy()
    Imag = Wave[..., 1].cpu().numpy()
    Combine = np.complex_(Real) + 1.0j * np.complex_(Imag)
    return Combine
Example #8
0
def fourier_coeffs(fun, modes):
    cosines = np.zeros(modes+1, dtype=np.float_)
    sines = np.zeros(modes+1, dtype=np.float)
    output = np.zeros(2*modes + 1, dtype=np.complex_)
    output[modes], err = integrate.quad(lambda x: fun(x), -1*cmath.pi/2, cmath.pi/2)
    output[modes] /= cmath.pi
    for k in range(1, modes+1):
        cosines[k], err = integrate.quad(lambda x: (fun(x) * np.cos(2*k*x)), -1*cmath.pi/2, cmath.pi/2)
        sines[k], err = integrate.quad(lambda x: (fun(x) * np.sin(2*k*x)), -1*cmath.pi/2, cmath.pi/2)
        output[modes-k] = (np.complex_(cosines[k]) + 1j * np.complex_(sines[k])) / cmath.pi
        output[modes+k] = (np.complex_(cosines[k]) - 1j * np.complex_(sines[k])) / cmath.pi
    return output
Example #9
0
def fmr_kittel(h, m, n, unit='mT'):
    #m is the saturation magnetization in A/m
    #demag. factors, keeping in mind that n[2] is the applied field direction
    mu0 = np.pi * 4.0e-7
    gamma = (2.0023 * 1.6021766e-19 /
             (2 * 9.109383e-31)) / (np.pi * 2.0e9)  #GHz/T
    if unit == 'Oe':
        h_conv = np.complex_(1e-4 * h / mu0)  #from Oe to A/m
    elif unit == 'mT':
        h_conv = np.complex_(1e-3 * h / mu0)  #from mT to A/m
    else:
        raise RuntimeError('Unit not yet supported')
    kittel_freq = mu0 * gamma * np.real(
        np.sqrt((h_conv + (n[0] - n[2]) * m) * (h_conv + (n[1] - n[2]) * m)))
    return kittel_freq
    def test_against_cmath(self):
        import cmath, sys

        points = [-1 - 1j, -1 + 1j, +1 - 1j, +1 + 1j]
        name_map = {
            'arcsin': 'asin',
            'arccos': 'acos',
            'arctan': 'atan',
            'arcsinh': 'asinh',
            'arccosh': 'acosh',
            'arctanh': 'atanh'
        }
        atol = 4 * np.finfo(np.complex).eps
        for func in self.funcs:
            fname = func.__name__.split('.')[-1]
            cname = name_map.get(fname, fname)
            try:
                cfunc = getattr(cmath, cname)
            except AttributeError:
                continue
            for p in points:
                a = complex(func(np.complex_(p)))
                b = cfunc(p)
                assert_(
                    abs(a - b) < atol,
                    "%s %s: %s; cmath: %s" % (fname, p, a, b))
Example #11
0
def _frequency_analysis(geo, hess, project=True):
    """ Froms the mass-weighted Hessian and diagonalizes it to obtain
        the normal coordinates and harmonic vibrational frequencies.

        :param geo: cartesian or z-matrix geometry
        :type geo: tuple
        :param hess: Hessian correpsonding to the geometry
        :type hess: tuple(tuple(float))
        :param project: project out rotations and translations of Hessian
        :type project: bool
        :rtype: tuple(tuple(float))
    """

    mw_hess = mass_weighted_hessian(geo, hess, project=project)
    # print(mw_hess)
    fcs, mw_norm_coos = numpy.linalg.eigh(mw_hess)

    conv = qcc.conversion_factor("hartree", "wavenumber")
    freqs = numpy.sqrt(numpy.complex_(fcs)) * conv
    freqs_im = numpy.imag(freqs)
    freqs_re = numpy.real(freqs)

    mw_vec = mass_weighting_vector(geo)
    norm_coos = mw_norm_coos
    norm_coos = _normalize_columns(mw_vec * mw_norm_coos)

    return norm_coos, freqs_re, freqs_im
Example #12
0
    def test_gamma(self, gamma):
        """Test if :math:`\Gamma_i, {i=1,...,16}` matrices are properly defined.

		:param array GAMMA: Gamma matrices.

		Test for:

			:math:`\mathrm{Tr}(\Gamma_i\Gamma_j)= \delta_{i,j}`

		:return: True if equation fullfilled for all gamma matrices, False otherwise.
		:rtype: bool
		"""

        #initialize empty test matrix
        test_matrix = np.complex_(np.zeros((16, 16)))

        for i in range(len(gamma)):
            for j in range(len(gamma)):
                test_matrix[i, j] = np.trace(np.dot(gamma[i], gamma[j]))

        diag_matrix = np.diag(np.ones(16))

        test_result = np.einsum('ij,ij', test_matrix - diag_matrix,
                                test_matrix - diag_matrix) - 16

        if np.abs(test_result) < 10**-6:
            return True
        else:
            False
Example #13
0
	def test_gamma(self,gamma):
		"""Test if :math:`\Gamma_i, {i=1,...,16}` matrices are properly defined.

		:param array GAMMA: Gamma matrices.

		Test for:

			:math:`\mathrm{Tr}(\Gamma_i\Gamma_j)= \delta_{i,j}`

		:return: True if equation fullfilled for all gamma matrices, False otherwise.
		:rtype: bool
		"""

		#initialize empty test matrix
		test_matrix = np.complex_(np.zeros((16,16)))

		for i in range(len(gamma)):
			for j in range(len(gamma)):
				test_matrix[i,j] = np.trace(np.dot(gamma[i], gamma[j]))

		diag_matrix = np.diag(np.ones(16))


		test_result = np.einsum('ij,ij',test_matrix - diag_matrix, test_matrix - diag_matrix)-16

		if np.abs(test_result) < 10**-6:
			return True
		else:
			False
Example #14
0
    def test_against_cmath(self):
        import cmath, sys

        # cmath.asinh is broken in some versions of Python, see
        # http://bugs.python.org/issue1381
        broken_cmath_asinh = False
        if sys.version_info < (2, 6):
            broken_cmath_asinh = True

        points = [-1 - 1j, -1 + 1j, +1 - 1j, +1 + 1j]
        name_map = {
            "arcsin": "asin",
            "arccos": "acos",
            "arctan": "atan",
            "arcsinh": "asinh",
            "arccosh": "acosh",
            "arctanh": "atanh",
        }
        atol = 4 * np.finfo(np.complex).eps
        for func in self.funcs:
            fname = func.__name__.split(".")[-1]
            cname = name_map.get(fname, fname)
            try:
                cfunc = getattr(cmath, cname)
            except AttributeError:
                continue
            for p in points:
                a = complex(func(np.complex_(p)))
                b = cfunc(p)

                if cname == "asinh" and broken_cmath_asinh:
                    continue

                assert_(abs(a - b) < atol, "%s %s: %s; cmath: %s" % (fname, p, a, b))
Example #15
0
def fft_deriv ( var ):
    #on_error, 2
                 
    n = numpy.size(var)

    F = old_div(numpy.fft.fft(var),n)  #different definition between IDL - python
                 
    imag = numpy.complex(0.0, 1.0)
    imag = numpy.complex_(imag)

    F[0] = 0.0
          
                
    if (n % 2) == 0 :
      # even number
        for i in range (1, old_div(n,2)) :
          a = imag*2.0*numpy.pi*numpy.float(i)/numpy.float(n)
          F[i] = F[i] * a         # positive frequencies
          F[n-i] = - F[n-i] * a   # negative frequencies
           
        F[old_div(n,2)] = F[old_div(n,2)] * (imag*numpy.pi)
    else:
      # odd number
        for i in range (1, old_div((n-1),2)+1) :
          a = imag*2.0*numpy.pi*numpy.float(i)/numpy.float(n)
          F[i] = F[i] * a
          F[n-i] = - F[n-i] * a 
        
    

    result = numpy.fft.ifft(F)*n  #different definition between IDL - python
    
      
    return result 
Example #16
0
def crea_pupila(npix, r, aberrations=None, work=False):
    P = np.zeros((npix, npix), dtype=np.complex_)
    rp = r * npix
    y, x = np.mgrid[-npix // 2:npix // 2, -npix // 2:npix // 2]
    rho2 = x * x + y * y
    mask = rho2 < rp**2
    P[:] = np.complex_(mask)
    if aberrations:
        phi = np.arctan2(y, x)
        rho = np.sqrt(rho2)
        rhomax = rho[mask].max()
        rho[:] = mask * rho / rhomax  # Radi normalitzat!
        W = np.zeros((npix, npix), dtype=np.float_)
        for coeff_num in aberrations:
            indexs = osa_indexs[coeff_num]
            coeff = aberrations[coeff_num]
            W[:] += coeff * zernike_p(rho, phi, *indexs)
        P[:] *= np.exp(1j * k * W)

    #P[:] = np.fft.fftshift(P)
    if work:
        rho = np.sqrt(rho2)
        phi = np.arctan2(y, x)
        #rho[:] = np.fft.fftshift(rho)
        #phi[:] = np.fft.fftshift(phi)
        return P, rho, phi
    else:
        return P
Example #17
0
 def __new__(cls, x=0):
     if isinstance(x, afnumpy.ndarray):
         return x.astype(cls)
     elif isinstance(x, numbers.Number):
         return numpy.complex_(x)
     else:
         return afnumpy.array(x).astype(cls)
Example #18
0
    def test_against_cmath(self):
        import cmath, sys

        # cmath.asinh is broken in some versions of Python, see
        # http://bugs.python.org/issue1381
        broken_cmath_asinh = False
        if sys.version_info < (2, 6):
            broken_cmath_asinh = True

        points = [-1 - 1j, -1 + 1j, +1 - 1j, +1 + 1j]
        name_map = {
            'arcsin': 'asin',
            'arccos': 'acos',
            'arctan': 'atan',
            'arcsinh': 'asinh',
            'arccosh': 'acosh',
            'arctanh': 'atanh'
        }
        atol = 4 * np.finfo(np.complex).eps
        for func in self.funcs:
            fname = func.__name__.split('.')[-1]
            cname = name_map.get(fname, fname)
            try:
                cfunc = getattr(cmath, cname)
            except AttributeError:
                continue
            for p in points:
                a = complex(func(np.complex_(p)))
                b = cfunc(p)

                if cname == 'asinh' and broken_cmath_asinh:
                    continue

                assert abs(a -
                           b) < atol, "%s %s: %s; cmath: %s" % (fname, p, a, b)
def Z(w):  # Impedences
    Z = np.matrix(np.complex_(np.zeros((2, 2))))
    for i in range(0, 2):
        for j in range(0, 2):
            Z[i, j] = (K[i, j] - w**2 * M[i, j] + complex(0, w * C[i, j])
                       )  #+ complex(0,w_w*C[i,j]
    return Z
def halo_transform(image):

    na=image.shape[0]
    nb=image.shape[1]
    ko= 5.336
    delta = (2.*np.sqrt(-2.*np.log(.75)))/ko

    x=np.arange(nb)
    y=np.arange(na)
    x,y=np.meshgrid(x,y)
    if (nb % 2) == 0:
        x=(1.*x - (nb)/2.)/nb
        shiftx = (nb)/2.
    else:
       x= (1.*x - (nb-1)/2.)/nb 
       shiftx=(nb-1.)/2.+1

    if (na % 2) == 0:
        y=(1.*y-(na/2.))/na
        shifty=(na)/2.
    else:
        y= (1.*y - (na-1)/2.)/ na
        shifty=(na-1.)/2.+1

    #--------------Spectral Logarithm--------------------
    M=int(np.log(nb)/delta)
    a2= np.zeros(M)
    a2[0]=np.log(nb)

    for i in range(M-1):
        a2[i+1]=a2[i]-delta

    a2=np.exp(a2)
    tab_k = 1. / (a2)
    wt= np.complex_(np.zeros(((na,nb,M))))


    a= ko*a2

    imageFT= np.fft.fft2(image)
    #imageFT=np.fft.fftshift(image)
    imageFT= np.roll(imageFT,int( shiftx), axis=1)
    imageFT= np.roll(imageFT,int(shifty), axis=0)

    for j in range(M):
        uv = 0

        uv=np.exp(-0.5*((abs(a[j]*np.sqrt(x**2.+y**2.))**2.  - abs(ko))**2.))

        uv = uv * a[j]

        W1FT=imageFT*(uv)
        W1F2=np.roll(W1FT,int(shiftx), axis =1)
        W1F2=np.roll(W1F2,int(shifty),axis=0)
       #W1F2=np.fft.ifftshift(W1FT)
        W1=np.fft.ifft2(W1F2)
        wt[:,:,j]=wt[:,:,j]+ W1

    return wt, tab_k
Example #21
0
 def test_params_to_array_inconsistent_types(self):
     """
     Tests if an assertion error is raised when parameters of different
     types are passed in
     """
     guess_params_adj = self.guess_params
     guess_params_adj[-1] = np.complex_(guess_params_adj[-1])
     self.assertRaises(AssertionError, self.affine_obj.params_to_array,
                       guess_params_adj)
Example #22
0
 def test_params_to_array_inconsistent_types(self):
     """
     Tests if an assertion error is raised when parameters of different
     types are passed in
     """
     guess_params_adj = self.guess_params
     guess_params_adj[-1] = np.complex_(guess_params_adj[-1])
     self.assertRaises(AssertionError, self.affine_obj.params_to_array,
                       guess_params_adj)
Example #23
0
def fourier_coeffs(fun, modes, period):
    cosines = np.zeros(modes + 1, dtype=np.float_)
    sines = np.zeros(modes + 1, dtype=np.float)
    output = np.zeros(2 * modes + 1, dtype=np.complex_)
    output[modes], err = integrate.quad(lambda x: fun(x), -1 * L / 2, L / 2)
    output[modes] /= period
    for k in range(1, modes + 1):
        cosines[k], err = integrate.quad(
            lambda x: (fun(x) * np.cos((2 * k * cmath.pi / period) * x)),
            -1 * period / 2, period / 2)
        sines[k], err = integrate.quad(
            lambda x: (fun(x) * np.sin((2 * k * cmath.pi / period) * x)),
            -1 * period / 2, period / 2)
        output[modes - k] = (np.complex_(cosines[k]) +
                             1j * np.complex_(sines[k])) / period
        output[modes + k] = (np.complex_(cosines[k]) -
                             1j * np.complex_(sines[k])) / period
    return output
Example #24
0
    def imdct(self, y, i):
        """imdct: inverse mdct
            y(np.array) -> mdct signal
            i -> index frame size
        """
        # frame size
        L = self.sizes[i]
        # signal size
        N = y.size
        # Number of frequency channels
        K = L / 2
        # Number of frames
        P = N / K

        # Reshape y
        tmp = y.reshape(P, K)
        y = np.zeros((P, L))
        y[:, :K] = tmp

        # Pre-twidle
        y = np.complex_(y)
        y *= np.tile(
            np.exp(1j * 2. * np.pi * np.arange(L) * (L / 2 + 1) / 2. / L),
            (P, 1))

        # IFFT
        x = np.fft.ifft(y)

        # Post-twidle
        x *= np.tile(
            np.exp((1. / 2.) * 1j * 2 * np.pi *
                   (np.arange(L) + ((L / 2 + 1) / 2.)) / L), (P, 1))

        # Windowing
        win = self.window(np.arange(L))
        winL = np.copy(win)
        winL[:L / 4] = 0
        winL[L / 4:L / 2] = 1
        winR = np.copy(win)
        winR[L / 2:3 * L / 4] = 1
        winR[3 * L / 4:] = 0
        x[0, :] *= winL
        x[1:-1, :] *= np.tile(win, (P - 2, 1))
        x[-1, :] *= winR

        # Real part & scaling
        x = np.sqrt(2. / K) * L * x.real

        # Overlap and add
        b = np.repeat(np.arange(P), L)
        a = np.tile(np.arange(L), P) + b * K
        x = sparse.coo_matrix((x.ravel(), (b, a)),
                              shape=(P, N + K)).sum(axis=0).A1

        # Cut edges
        return x[K / 2:-K / 2]
Example #25
0
 def scat_l(coefs
            ):  # scattering cross_section for left polarized light, eq. 42
     summa = np.complex_(0)
     for n in range(1, len(coefs) + 1):
         a, b, c, d = coefs[n - 1]
         summa += (2 * n + 1) * (np.abs(a)**2 + np.abs(b)**2 +
                                 np.abs(c)**2 + np.abs(d)**2 + 1j *
                                 (np.conj(a) * c - a * np.conj(c) +
                                  b * np.conj(d) - np.conj(b) * d))
     return 2 * np.pi * (1 / (k_hat**2)) * summa
Example #26
0
 def test_opt_gen_pred_coef_complex(self):
     """
     Tests if complex values are return properly
     """
     # DOC: Need to make sure that the arrays are also np.complex
     guess_params = [np.complex_(el) for el in self.guess_params]
     params = self.affine_obj.params_to_array(guess_params)
     arrays_gpc = self.affine_obj.opt_gen_pred_coef(*params)
     for array in arrays_gpc:
         self.assertEqual(array.dtype, np.complex_)
Example #27
0
 def test_opt_gen_pred_coef_complex(self):
     """
     Tests if complex values are return properly
     """
     # DOC: Need to make sure that the arrays are also np.complex
     guess_params = [np.complex_(el) for el in self.guess_params]
     params = self.affine_obj.params_to_array(guess_params)
     arrays_gpc = self.affine_obj.opt_gen_pred_coef(*params)
     for array in arrays_gpc:
         self.assertEqual(array.dtype, np.complex_)
Example #28
0
 def frequencies(self):
     hartree2j = (4.3597438e-18)
     bohr2m = (5.29177208e-11)
     amu2kg = (1.66054e-27)
     c = (2.99792458e10)
     evalues_si = [(val * hartree2j / bohr2m / bohr2m / amu2kg)
                   for val in self.evalues]
     vfreq_hz = [
         1 / (2 * pi) * np.sqrt(np.complex_(val)) for val in evalues_si
     ]
     vfreq = [(val / c) for val in vfreq_hz]
     return (vfreq)
Example #29
0
def what_is_complex():
    '''
    - "np.complex_" is an alias for np.complex128 on my operating system
    - My system also has np.complex64 and np.complex256, but not np.complex192
    - I don't understand complex numbers so don't worry about it
    '''
    print(np.complex_ is np.complex64)  # False
    print(np.complex_ is np.complex128)  # True
    #print(np.complex_ is np.complex192) # AttributeError
    print(np.complex_ is np.complex256)  # False
    cpx = np.complex_(3j)
    print(type(cpx))  # <class 'numpy.complex128'>
Example #30
0
    def solve_fwd(self):

        Z = np.complex_(np.zeros(self.shape))
        Z[0] = self.uv0

        E_in = np.zeros(self.shape)  # Energy flux in

        T = (self.Tx + 1j * self.Ty) / self.rho
        om = self.r + 1j * self.f

        for ii in np.arange(1, len(self.t) - 1):
            perc = 100 * ii / float(len(self.t) - 1)
            sys.stdout.write('\rSolving: %2d%%' % perc)
            dt = self.t[ii + 1] - self.t[ii]
            dTi_dt = (T[ii + 1] - T[ii]) / dt
            dZi_dt = -om * Z[ii] - dTi_dt / (om * self.mld[ii])
            Z[ii + 1] = Z[ii] + dt * dZi_dt
            E_in[ii] = - np.real(self.rho *Z[ii].conj() * \
                            dTi_dt/om)

            if np.isnan(Z[ii + 1]).any():
                dbyn = input('Blowup. Debug (1/0)?: ')
                if dbyn:
                    pdb.set_trace()
                else:
                    raise ValueError('Blowup (check damping parameter..)')
        sys.stdout.write('\rDone.')

        # IO currents
        self.ui = Z.real
        self.vi = Z.imag

        # Ekman transport
        if om.ndim > 1:  # (Index object for multiplication)
            idx_obj = [slice(None)] + [None for i in xrange(om.ndim)]
        else:
            idx_obj = slice(None)

        ET = T / (self.mld[idx_obj] * om)
        self.ue = ET.real
        self.ve = ET.imag

        # Total
        self.u = self.ui + self.ue
        self.v = self.vi + self.ve

        # Near-inertial energy flux wind -> mixed layer
        self.E_in = E_in

        # Energy flux mixed layer -> dissipation
        self.E_out = self.r * Z * Z.conj() * self.rho * self.mld[idx_obj]
Example #31
0
    def imdct(self,y,i):
        """imdct: inverse mdct
            y(np.array) -> mdct signal
            i -> index frame size
        """
        # frame size
        L = self.sizes[i]
        # signal size
        N = y.size
        # Number of frequency channels
        K = L/2
        # Number of frames
        P = N/K

        # Reshape y
        tmp = y.reshape(P,K)
        y = np.zeros( (P,L) )
        y[:,:K] = tmp

        # Pre-twidle
        y = np.complex_(y)
        y *= np.tile(np.exp(1j*2.*np.pi*np.arange(L)*(L/2+1)/2./L), (P,1))

        # IFFT
        x = np.fft.ifft(y);

        # Post-twidle
        x *= np.tile(np.exp((1./2.)*1j*2*np.pi*(np.arange(L)+((L/2+1)/2.))/L),(P,1));

        # Windowing
        win = self.window(np.arange(L))
        winL = np.copy(win)
        winL[:L/4] = 0
        winL[L/4:L/2] = 1
        winR = np.copy(win)
        winR[L/2:3*L/4] = 1
        winR[3*L/4:] = 0
        x[0,:] *= winL
        x[1:-1,:] *= np.tile(win,(P-2,1))
        x[-1,:] *= winR

        # Real part & scaling
        x = np.sqrt(2./K)*L*x.real

        # Overlap and add
        b = np.repeat(np.arange(P),L)
        a = np.tile(np.arange(L),P) + b*K
        x = sparse.coo_matrix((x.ravel(),(b,a)),shape=(P,N+K)).sum(axis=0).A1

        # Cut edges
        return x[K/2:-K/2]
Example #32
0
def calcfreq(evalues):
    hartree2j = 4.3597438e-18
    bohr2m = 5.29177210903e-11
    #amu2kg = 1.66054e-27
    amu2kg = 1.66053906660e-27
    #speed of light in cm/s
    c = 2.99792458e10
    pi = np.pi
    evalues_si = [
        val * hartree2j / bohr2m / bohr2m / amu2kg for val in evalues
    ]
    vfreq_hz = [1 / (2 * pi) * np.sqrt(np.complex_(val)) for val in evalues_si]
    vfreq = [val / c for val in vfreq_hz]
    return vfreq
Example #33
0
    def fun(self, t, args):
        """Maximum likelihood function to be minimized.

		:param numpy_array t: t values.
		:param numpy_array args: first entry contains correlation counts, second the corresponding basis as string.
		:param numpy_array args: PSIs, all possible basis as Jones vectors.

		:return: Function value. See for further information D. F. V. James et al. Phys. Rev. A, 64, 052312 (2001).
		:rtype: numpy float
		"""
        corr_counts = args[0]
        basis = args[1]
        PSI = args[2]
        nbrOfElements = len(basis)

        rho_phys = self.rho_phys(t)

        #Estimate NormFactor
        estNormFactor = []

        for i in range(len(corr_counts)):
            estNormFactor.append(
                np.dot(np.dot(np.conj(PSI[i]), rho_phys), PSI[i]))

        NormFactor = np.sum(corr_counts) / np.sum(estNormFactor)

        #Optimize density matrix
        BraRoh_physKet = np.complex_(np.zeros(nbrOfElements))

        for i in range(nbrOfElements):
            rhoket = np.array(np.dot(
                rho_phys, PSI[i]).flat)  #Convert 2d to 1d array with flat
            BraRoh_physKet[i] = np.complex_(np.dot(np.conj(PSI[i]), rhoket))

        return np.real(
            np.sum((NormFactor * BraRoh_physKet - corr_counts)**2.0 /
                   (2.0 * NormFactor * BraRoh_physKet)))
Example #34
0
def test_series_roundtrip():
    ser = pd.Series({
        'an_int': np.int_(1),
        'a_float': np.float_(2.5),
        'a_nan': np.nan,
        'a_minus_inf': -np.inf,
        'an_inf': np.inf,
        'a_str': np.str_('foo'),
        'a_unicode': np.unicode_('bar'),
        'date': np.datetime64('2014-01-01'),
        'complex': np.complex_(1 - 2j),
        # TODO: the following dtypes are not currently supported.
        # 'object': np.object_({'a': 'b'}),
    })
    decoded_ser = roundtrip(ser)
    assert_series_equal(decoded_ser, ser)
Example #35
0
    def construct_b_matrix(self, PSI, GAMMA):
        """Construct B matrix as in D. F. V. James et al. Phys. Rev. A, 64, 052312 (2001).

		:param array PSI: :math:`\psi_\\nu` vector with :math:`\\nu=1,...,16`, computed in __init__
		:param array GAMMA: :math:`\Gamma` matrices, computed in __init__

		:return: :math:`B_{\\nu,\mu} = \\langle \psi_\\nu \\rvert  \Gamma_\mu  \\lvert \psi_\\nu \\rangle`
		:rtype: numpy array
		"""

        B = np.complex_(np.zeros((16, 16)))

        for i in range(16):
            for j in range(16):
                B[i, j] = np.dot(np.conj(PSI[i]), np.dot(GAMMA[j], PSI[i]))
        return B
Example #36
0
def _frequency_analysis(geo, hess, project=True):
    """ harmonic frequency analysis
    """
    mw_hess = mass_weighted_hessian(geo, hess, project=project)
    # print(mw_hess)
    fcs, mw_norm_coos = numpy.linalg.eigh(mw_hess)

    conv = qcc.conversion_factor("hartree", "wavenumber")
    freqs = numpy.sqrt(numpy.complex_(fcs)) * conv
    freqs_im = numpy.imag(freqs)
    freqs_re = numpy.real(freqs)

    mw_vec = mass_weighting_vector(geo)
    norm_coos = mw_norm_coos
    norm_coos = _normalize_columns(mw_vec * mw_norm_coos)
    return norm_coos, freqs_re, freqs_im
Example #37
0
	def construct_b_matrix(self, PSI, GAMMA):
		"""Construct B matrix as in D. F. V. James et al. Phys. Rev. A, 64, 052312 (2001).

		:param array PSI: :math:`\psi_\\nu` vector with :math:`\\nu=1,...,16`, computed in __init__
		:param array GAMMA: :math:`\Gamma` matrices, computed in __init__

		:return: :math:`B_{\\nu,\mu} = \\langle \psi_\\nu \\rvert  \Gamma_\mu  \\lvert \psi_\\nu \\rangle`
		:rtype: numpy array
		"""

		B = np.complex_(np.zeros((16,16)))

		for i in range(16):
			for j in range(16):
				B[i,j] = np.dot(np.conj(PSI[i]) , np.dot(GAMMA[j], PSI[i]))
		return B
Example #38
0
def test_dataframe_roundtrip():
    df = pd.DataFrame({
        'an_int': np.int_([1, 2, 3]),
        'a_float': np.float_([2.5, 3.5, 4.5]),
        'a_nan': np.array([np.nan] * 3),
        'a_minus_inf': np.array([-np.inf] * 3),
        'an_inf': np.array([np.inf] * 3),
        'a_str': np.str_('foo'),
        'a_unicode': np.unicode_('bar'),
        'date': np.array([np.datetime64('2014-01-01')] * 3),
        'complex': np.complex_([1 - 2j, 2 - 1.2j, 3 - 1.3j]),
        # TODO: the following dtypes are not currently supported.
        # 'object': np.object_([{'a': 'b'}]*3),
    })
    decoded_df = roundtrip(df)
    assert_frame_equal(decoded_df, df)
Example #39
0
	def from_csv(cls, csv, delimiter="\t"):
		'''Constructs class instance from the given csv table. Is used in testing mode. Method is able to construct only 2d space. Is supposed to read tables produced by 'to_csv' method
		
			csv string: path to csv table
			delimiter string: csv table delimiter
			
			Return Grid: class instance
		'''		
		def _converter(l):
			a = l.strip().split(delimiter)
			a = [x.replace("|", "+") + "j" for x in a]
			return delimiter.join(a);
			
		array = np.genfromtxt((_converter(x) for x in open(csv)), dtype=str, delimiter=delimiter)
		array = np.complex_(array)
		encoding_table = [dict([(x,x) for x in range(array.shape[0])]), dict([(x,x) for x in range(array.shape[1])])]
		return cls(array, encoding_table);
Example #40
0
def besselj(n, z):
    """Bessel function of first kind of order n at kr.
    Wraps scipy.special.jn(n, z).

    Parameters
    ----------
    n : array_like
       Order
    z: array_like
       Argument

    Returns
    -------
    J : array_like
       Values of Bessel function of order n at position z
    """
    return scy.jv(n, _np.complex_(z))
Example #41
0
 def test_generic_roundtrip(self):
     if self.should_skip:
         return self.skip('numpy is not importable')
     values = [
         np.int_(1),
         np.int32(-2),
         np.float_(2.5), np.nan, -np.inf, np.inf,
         np.datetime64('2014-01-01'),
         np.str_('foo'),
         np.unicode_('bar'),
         np.object_({'a': 'b'}),
         np.complex_(1 - 2j)
     ]
     for value in values:
         decoded = self.roundtrip(value)
         assert_equal(decoded, value)
         self.assertTrue(isinstance(decoded, type(value)))
Example #42
0
 def test_dataframe_roundtrip(self):
     if self.should_skip:
         return self.skip('pandas is not importable')
     df = pd.DataFrame({
         'an_int': np.int_([1, 2, 3]),
         'a_float': np.float_([2.5, 3.5, 4.5]),
         'a_nan': np.array([np.nan] * 3),
         'a_minus_inf': np.array([-np.inf] * 3),
         'an_inf': np.array([np.inf] * 3),
         'a_str': np.str_('foo'),
         'a_unicode': np.unicode_('bar'),
         'date': np.array([np.datetime64('2014-01-01')] * 3),
         'complex': np.complex_([1 - 2j, 2 - 1.2j, 3 - 1.3j]),
         # TODO: the following dtypes are not currently supported.
         # 'object': np.object_([{'a': 'b'}]*3),
     })
     decoded_df = self.roundtrip(df)
     assert_frame_equal(decoded_df, df)
Example #43
0
    def test_against_cmath(self):
        import cmath, sys

        points = [-1-1j, -1+1j, +1-1j, +1+1j]
        name_map = {'arcsin': 'asin', 'arccos': 'acos', 'arctan': 'atan',
                    'arcsinh': 'asinh', 'arccosh': 'acosh', 'arctanh': 'atanh'}
        atol = 4*np.finfo(np.complex).eps
        for func in self.funcs:
            fname = func.__name__.split('.')[-1]
            cname = name_map.get(fname, fname)
            try:
                cfunc = getattr(cmath, cname)
            except AttributeError:
                continue
            for p in points:
                a = complex(func(np.complex_(p)))
                b = cfunc(p)
                assert_(abs(a - b) < atol, "%s %s: %s; cmath: %s"%(fname, p, a, b))
Example #44
0
 def test_generic_roundtrip(self):
     values = [
         np.int_(1),
         np.int32(-2),
         np.float_(2.5),
         np.nan,
         -np.inf,
         np.inf,
         np.datetime64('2014-01-01'),
         np.str_('foo'),
         np.unicode_('bar'),
         np.object_({'a': 'b'}),
         np.complex_(1 - 2j)
     ]
     for value in values:
         decoded = self.roundtrip(value)
         assert_equal(decoded, value)
         self.assertTrue(isinstance(decoded, type(value)))
Example #45
0
 def test_series_roundtrip(self):
     if self.should_skip:
         return self.skip('pandas is not importable')
     ser = pd.Series({
         'an_int': np.int_(1),
         'a_float': np.float_(2.5),
         'a_nan': np.nan,
         'a_minus_inf': -np.inf,
         'an_inf': np.inf,
         'a_str': np.str_('foo'),
         'a_unicode': np.unicode_('bar'),
         'date': np.datetime64('2014-01-01'),
         'complex': np.complex_(1 - 2j),
         # TODO: the following dtypes are not currently supported.
         # 'object': np.object_({'a': 'b'}),
     })
     decoded_ser = self.roundtrip(ser)
     assert_series_equal(decoded_ser, ser)
Example #46
0
def frequencies(mol, H):
  
  mol = mol.copy()
  mol.to_angstrom()

  # 3. build mass-weighted Hessian matrix
  natom = mol.natom
  m     = np.repeat(mol.masses, 3) ** -0.5
  M     = np.broadcast_to(m, (3*natom, 3*natom)).T
  tH    = M.T * H * M

  # 4. compute eigenvalues and eigenvectors of the mass-weighted Hessian matrix
  k, tQ  = np.linalg.eigh(tH)

  # 5. un-mass-weight the normal coordinates
  Q = M * tQ

  # 6. get wavenumbers from a.u. force constants
  hartree2J = 4.3597443e-18
  amu2kg = 1.6605389e-27
  bohr2m = 5.2917721e-11
  c = 29979245800.0 # speed of light in cm/s
  v = np.sqrt(np.complex_(k)) * np.sqrt(hartree2J/(amu2kg*bohr2m*bohr2m))/(c*2*np.pi)

  ret = ''
  fmt = '{:2s}' + '{: >15.10f}'*6 + '\n'
  for A in range(3*natom):
    if np.isreal(v[A]):
      ret += '{:d}\n{: >7.2f}  cm^-1\n'.format(natom, np.absolute(v[A]))
    else:
      ret += '{:d}\n{: >7.2f}i cm^-1\n'.format(natom, np.absolute(v[A]))
    for B in range(natom):
      label      = mol.labels[B]
      x ,  y,  z = mol.geom[B]
      dx, dy, dz = Q[3*B:3*B+3, A]
      ret += fmt.format(label, x, y, z, dx, dy, dz)
    ret += '\n'

  # 7. save the normal modes to a file
  outfile = open('modes.xyz', 'w+')
  outfile.write(ret)
  outfile.close()

  return v, Q
Example #47
0
	def rho_phys(self, t):
		"""Positive semidefinite matrix based on t values.

		:param numpy_array t: tvalues

		:return: A positive semidefinite matrix which is an estimation of the actual density matrix.
		:rtype: numpy matrix
		"""
		T = np.complex_(np.matrix([
						[t[0], 				0, 				0, 				0],
						[t[4]+1j*t[5], 		t[1], 			0, 				0],
						[t[10]+1j*t[11], 	t[6]+1j*t[7], 	t[2], 			0],
						[t[14]+1j*t[15], 	t[12]+1j*t[13], t[8]+1j*t[9], 	t[3]]
						]))

		TdagT = np.dot(T.conj().T , T)
		norm = np.trace(TdagT)

		return TdagT/norm
Example #48
0
 def test_generic_roundtrip(self):
     if self.should_skip:
         return self.skip("numpy is not importable")
     values = [
         np.int_(1),
         np.int32(-2),
         np.float_(2.5),
         np.nan,
         -np.inf,
         np.inf,
         np.datetime64("2014-01-01"),
         np.str_("foo"),
         np.unicode_("bar"),
         np.object_({"a": "b"}),
         np.complex_(1 - 2j),
     ]
     for value in values:
         decoded = self.roundtrip(value)
         assert_equal(decoded, value)
         self.assertTrue(isinstance(decoded, type(value)))
Example #49
0
def atrou(data, scale):
    '''
    '''
    kernel_val = np.array([1./16, 1./8., 1./16., 1./8., 1./4., 1./8., 1./16., 1./8, 1./16])
    result=np.complex_(np.zeros((data.shape[0],data.shape[1],scale)))
    tempo = data
    
    for i in range(scale):
        n=int(2*(2**i)+1)
        kernel = np.zeros(n*n)
        dx = (n-1)/2.
        lc = (n**2 - n)/2.
        indice = np.array([0, dx, 2*dx, lc, lc+dx, lc+2*dx, 2*lc, 2*lc+dx, 2*(lc+dx)] )
        for j in range(indice.shape[0]):
            kernel[indice[j]] = kernel_val[j]
        kernel=kernel.reshape(n,n)
        conv=scipy.signal.convolve2d(tempo, kernel, mode='same')
        result[:,:, i]=tempo - conv
        tempo = conv

    return result
Example #50
0
	def fidelity_max(self,rho):
		"""Compute the maximal fidelity of rho to a maximally entangled state.

		:param numpy_array rho: Density matrix

		:return: The maximal fidelity of rho :math:`(\\rho)` to a maximally entangled state.
			:math:`F(\\rho)=\\frac{1+\lambda_1+\lambda_2-\mathrm{sgn}(\mathrm{det(R)})\lambda_3}{4}`, where

			:math:`R_{i,j}=\mathrm{Tr}(\sigma_i \otimes \sigma_j)`, with
			:math:`\sigma_i, {i=1,2,3}` the Pauli matrices and
			:math:`\lambda_i, {i=1,2,3}` the ordered singular values of R.

			Note, the maximally entangled state is not computed.
			Algorithm from: http://dx.doi.org/10.1103/PhysRevA.66.022307
		:rtype: complex
		"""

		R = np.complex_(np.zeros((3,3)))

		for i in range(3):
			for j in range(3):
				element = np.dot(rho , np.kron(self.PAULI[i] , self.PAULI[j]))
				#Trace of element
				R[i,j]  = np.trace(element)

		a, b = np.linalg.eig(R)

		SgnDetR = np.sign(np.linalg.det(R))

		#Singular Value of matrix are the square roots of the eigenvalus of A^* A, where A^* is the conjugate transpose of A.
		eigValues, eigVecors = np.linalg.eig(np.dot(R.conj().T, R))
		lmbda = np.sort(np.sqrt(eigValues))

		#The fidelity is:
		f = (1+lmbda[2] + lmbda[1] - SgnDetR*lmbda[0])/4.0

		return f
Example #51
0
	def __init__(self, basis):
		"""Intialize the DensityMatrix class.
		The following vectors and matrices are initiad:
		:math:`\psi_\\nu` 16 basis vectors spanning qubit space and
		:math:`M, B, \Gamma`, and Pauli matrices are initiated.

		Args:
			basis
				An array of basis elements in which the measurement is performed.

		Returns:
			No return.

		Raises:
			ValueError
				If Gamma matrices are not defined properly.

		Example:

			.. code-block:: python

				basis =  ["HH","HV","VV","VH","HD","HR","VD","VR","DH","DV","DD","DR","RH","RV","RD","RR"]
		"""
		self.basis = basis

		self.H = np.array([1,0])
		self.V = np.array([0,1])
		self.R = 1/np.sqrt(2)*(self.H - 1j*self.V)
		self.L = 1/np.sqrt(2)*(self.H + 1j*self.V)
		self.D = 1/np.sqrt(2)*(self.H +    self.V)
		self.A = 1/np.sqrt(2)*(self.H -    self.V)

		#Generate psi_nu's and gamma's
		self.PSI = []
		self.GAMMA = []

		#Fill PSI
		for basis_element in self.basis:
			basis_branch1 = self.basis_str_to_object(basis_element[0])
			basis_branch2 = self.basis_str_to_object(basis_element[1])
			self.PSI.append(np.hstack(np.outer(basis_branch1,basis_branch2)))

		#Fill Gamma
		gam1  = (1/2.)*np.array([[0,1,0,0]  ,[1,0,0,0]  ,[0,0,0,1]  ,[0,0,1,0]])
		gam2  = (1/2.)*np.array([[0,-1j,0,0],[1j,0,0,0] ,[0,0,0,-1j],[0,0,1j,0]])
		gam3  = (1/2.)*np.array([[1,0,0,0]  ,[0,-1,0,0] ,[0,0,1,0]  ,[0,0,0,-1]])
		gam4  = (1/2.)*np.array([[0,0,1,0]  ,[0,0,0,1]  ,[1,0,0,0]  ,[0,1,0,0]])
		gam5  = (1/2.)*np.array([[0,0,0,1]  ,[0,0,1,0]  ,[0,1,0,0]  ,[1,0,0,0]])
		gam6  = (1/2.)*np.array([[0,0,0,-1j],[0,0,1j,0] ,[0,-1j,0,0],[1j,0,0,0]])
		gam7  = (1/2.)*np.array([[0,0,1,0]  ,[0,0,0,-1] ,[1,0,0,0]  ,[0,-1,0,0]])
		gam8  = (1/2.)*np.array([[0,0,-1j,0],[0,0,0,-1j],[1j,0,0,0] ,[0,1j,0,0]])
		gam9  = (1/2.)*np.array([[0,0,0,-1j],[0,0,-1j,0],[0,1j,0,0] ,[1j,0,0,0]])
		gam10 = (1/2.)*np.array([[0,0,0,-1] ,[0,0,1,0]  ,[0,1,0,0]  ,[-1,0,0,0]])
		gam11 = (1/2.)*np.array([[0,0,-1j,0],[0,0,0,1j] ,[1j,0,0,0] ,[0,-1j,0,0]])
		gam12 = (1/2.)*np.array([[1,0,0,0]  ,[0,1,0,0]  ,[0,0,-1,0] ,[0,0,0,-1]])
		gam13 = (1/2.)*np.array([[0,1,0,0]  ,[1,0,0,0]  ,[0,0,0,-1] ,[0,0,-1,0]])
		gam14 = (1/2.)*np.array([[0,-1j,0,0],[1j,0,0,0] ,[0,0,0,1j] ,[0,0,-1j,0]])
		gam15 = (1/2.)*np.array([[1,0,0,0]  ,[0,-1,0,0] ,[0,0,-1,0] ,[0,0,0,1]])
		gam16 = (1/2.)*np.array([[1,0,0,0]  ,[0,1,0,0]  ,[0,0,1,0]  ,[0,0,0,1]])

		self.GAMMA = np.array([gam1,gam2,gam3,gam4,gam5,gam6,gam7,gam8,gam9,gam10,gam11,gam12,gam13,gam14,gam15,gam16])

		sig_1 = np.complex_(np.array([[0, 1],
						  			[1, 0]]))
		sig_2 = np.complex_(np.array([[0,-1j],
						  			[1j,0]]))
		sig_3 = np.complex_(np.array([[1, 0],
						  			[0,-1]]))
		#Defining the Pauli matrices
		self.PAULI = np.array([sig_1, sig_2, sig_3])

		#Test orthogonalty of self.GAMMA
		if self.test_gamma(self.GAMMA) == False:
			raise ValueError("Gamma matrices not defined properly")
		#Construct B matrix and its inverse
		self.B = self.construct_b_matrix(PSI = self.PSI, GAMMA = self.GAMMA)
		self.B_inv = np.linalg.inv(self.B)

		#Construct M matrix
		self.M = np.einsum('ji,jkl->ikl',self.B_inv, self.GAMMA)

		#Trace of M
		self.TrM = np.einsum('...ii',self.M)
Example #52
0
    def mdct(self,s,i,urange=None):
        """ mdct
            s (np.array) -> the signal vector to be decomposed
            i (int) -> index the size of the atoms
            Output -> the solution array for this size
        """
        L = self.sizes[i]
        # Size of the signal
        N = s.size
        # Number of frequency channels
        K = int(L/2)
        # Number of frames
        P = int(N/K)
        
        # the range of frames to be proceeded
        (framemin,framemax) = urange if urange else (0,P)
        framerange = framemax - framemin

        # Test length
        if N % K != 0:
            raise Exception("Input length must be a multiple of the half of the window size")

        if P < 2:
            raise Exception("Signal too short")

        # Pad egdes with zeros
        x = np.hstack( (np.zeros(K/2), s, np.zeros(K/2)) )

        # Framing
        fidx = K *np.arange(framemin,framemax)
        fidx = np.tile(fidx,(L,1)).transpose() # tile array to dimension P*L
        sidx = np.arange(L)
        sidx = np.tile(sidx,(framerange,1))
        x = x[fidx+sidx]

        # Windowing
        win = self.window(np.arange(L))
        winL = np.copy(win)
        winL[0:L/4] = 0
        winL[L/4:L/2] = 1
        winR = np.copy(win)
        winR[L/2:3*L/4] = 1
        winR[3*L/4:] = 0
        x[0,:] *= winL
        if(framerange > 2):
            x[1:-1,:] *= np.tile(win,(framerange-2,1))
        x[-1,:] *= winR

        # Pre-twidle
        x = np.complex_(x)
        x *= np.tile(np.exp(-1j*np.pi*np.arange(L)/L), (framerange,1) )
        
        # FFT
        y = np.fft.fft(x)

        # Post-twidle
        y = y[:,:L/2]
        y *= np.tile(np.exp(-1j*np.pi*(L/2+1)*np.arange(1/2.,(L+1)/2.)/L),(framerange,1))

        # Real part & scaling
        return np.sqrt(2./K)*y.ravel().real
Example #53
0
from ....table import QTable, SerializedColumn
from ....extern.six.moves import StringIO

try:
    from ..yaml import load, load_all, dump
    HAS_YAML = True
except ImportError:
    HAS_YAML = False

pytestmark = pytest.mark.skipif('not HAS_YAML')


@pytest.mark.parametrize('c', [np.bool(True), np.uint8(8), np.int16(4),
                               np.int32(1), np.int64(3), np.int64(2**63 - 1),
                               np.float(2.0), np.float64(),
                               np.complex(3, 4), np.complex_(3 + 4j),
                               np.complex64(3 + 4j),
                               np.complex128(1. - 2**-52 + 1j * (1. - 2**-52))])
def test_numpy_types(c):
    cy = load(dump(c))
    assert c == cy


@pytest.mark.parametrize('c', [u.m, u.m / u.s, u.hPa, u.dimensionless_unscaled])
def test_unit(c):
    cy = load(dump(c))
    if isinstance(c, u.CompositeUnit):
        assert c == cy
    else:
        assert c is cy
def halo_inverse(wt, tab_k, multiscales=False):

    '''
    multiscales allows reconstruction when wavelets have features that
    are not necisacrliy at their original scales
    '''

#----------------definitions----------------#

    ko=5.336
    na=wt.shape[0]
    nb=wt.shape[1]
 
    a=ko/tab_k
    imagetot=np.complex_(np.zeros((na,nb)))


#--------------Coords---------------------------##

    x = np.arange( nb , dtype=float )
    y = np.arange( na , dtype=float )
    x , y = np.meshgrid( x, y )
    if (nb % 2) == 0:
        x = ( 1.*x - (nb)/2. )/ nb 
        shiftx = (nb)/2.
    else:
        x = (1.*x - (nb-1)/2.)/ nb
        shiftx = (nb-1.)/2.+1

    if (na % 2) == 0:
        y = (1.*y-(na/2.))/na
        shifty = (na)/2.
    else:
        y = (1.*y - (na-1)/2.)/ na
        shifty = (na-1.)/2+1

#---------------------transform----------------------#

    
        
    for h in range(tab_k.shape[0]):
        uv = 0
        if scale=True:
            for i in range(tab_k.shape[0]):
                uv = np.exp ( -0.5 * ( abs ( a[i] * np.sqrt ( x**2. + y**2. ) )- ko)**2.)
                uv = uv / a[i]

                imageFT = np.roll((np.fft.fft2(wt[:,:,h])),int(shiftx), axis=1)
                imageFT = np.roll(imageFT, int(shifty), axis=0)
                imageFT = imageFT*uv
        
                imageFT = np.roll(imageFT ,int(shiftx), axis=1)
                imageFT = np.roll(imageFT, int(shifty), axis=0)
                image = np.fft.ifft2(imageFT)            

                imagetot = imagetot+image 


        else:
            uv = np.exp ( -0.5 * ( abs ( a[h] * np.sqrt ( x**2. + y**2. ) )- ko)**2.)
            uv = uv / a[h]


            imageFT = np.roll((np.fft.fft2(wt[:,:,h])),int(shiftx), axis=1)
            imageFT = np.roll(imageFT, int(shifty), axis=0)
            imageFT = imageFT*uv
            
            imageFT = np.roll(imageFT ,int(shiftx), axis=1)
            imageFT = np.roll(imageFT, int(shifty), axis=0)
            
            image = np.fft.ifft2(imageFT)
            
            imagetot = imagetot+image 
def fan_inverse(wt, tab_k): 
#intend to add option for scale so image can be reconstructed at certain scales
    '''
    Performs the inverse fan wavelet transform on a set of wavelets wt
    scale tab_k. Returns an image of size wt.shape[0] , wt.shape[1]
    '''


    ko= 5.336
    delta = (2.*np.sqrt(-2.*np.log(.75)))/ko
    na = float(wt.shape[0])
    nb = float(wt.shape[1])

    M = tab_k.shape[0]
    interval = [tab_k[0],tab_k[M-1]]  #Default if no interval input#

#------------------------------------------------------------------

    x= np.arange(nb)
    y= np.arange(na)
    x,y = np.meshgrid(x,y)
    if (nb % 2) == 0:
        x = (1.*x - (nb)/2.)/nb
        shiftx = (nb)/2.
    else:
       x = (1.*x - (nb-1)/2.)/nb
       shiftx = (nb-1.)/2.+1

    if (na % 2) == 0:
        y = (1.*y-(na/2.))/na
        shifty = (na)/2.
    else:
        y= (1.*y - (na-1)/2.)/ na
        shifty= (na-1.)/2+1

#----------------------------------------------------------------
    Cphi = 0.114517

    a = ko/(tab_k)

    delta_a = np.exp(delta)

    N = int((2*np.pi)/delta)

    imagetot = np.complex_(np.zeros((na,nb)))
    
    phi = np.zeros((na,nb))
    arrange = np.arange(tab_k.shape[0])

    o = interval[0]
    l = interval[1]
    int1 = np.where((tab_k >= o) & (tab_k <= l))
    int1 = arrange[int1]
    count = int1.shape[0]

   #for h in range(int1[0], int1[count-1]): was originally so scale option could be used
    for h in range(tab_k.shape[0]):
        for i in range(N):
            uv=0
            t=float(delta*i)
            #for j in range(int1[0], int1[count-1]+1): for scale option
            uv=np.exp(-0.5*( (a[h]*x - ko*np.cos(t))**2. + (a[h]*y - ko*np.sin(t))**2.))
            uv = uv / a[h]**2.
        

            imageFT=np.roll((np.fft.fft2(wt[:,:,h])),int(shiftx), axis=1)
            imageFT=np.roll(imageFT, int(shifty), axis=0)
            imageFT=imageFT*uv

            imageFT=np.roll(imageFT ,int(shiftx), axis=1)
            imageFT=np.roll(imageFT, int(shifty), axis=0)

            ampli=abs(imageFT)
            phi=np.arctan2(imageFT.imag,imageFT.real)
            




            imageFT= ampli*np.cos(phi) + 1.j*ampli*np.sin(phi)
            j=0
            image=np.fft.ifft2(imageFT)

            da=a[0]*((delta_a-1.)/(delta_a**(h+1.)))

            imagetot=imagetot+image * delta * da /Cphi
    h_rec=imagetot.real*.95
    return h_rec
Example #56
0
from ....time import Time
from ....table import QTable, SerializedColumn

try:
    from ..yaml import load, load_all, dump
    HAS_YAML = True
except ImportError:
    HAS_YAML = False

pytestmark = pytest.mark.skipif('not HAS_YAML')


@pytest.mark.parametrize('c', [True, np.uint8(8), np.int16(4),
                               np.int32(1), np.int64(3), np.int64(2**63 - 1),
                               2.0, np.float64(),
                               3+4j, np.complex_(3 + 4j),
                               np.complex64(3 + 4j),
                               np.complex128(1. - 2**-52 + 1j * (1. - 2**-52))])
def test_numpy_types(c):
    cy = load(dump(c))
    assert c == cy


@pytest.mark.parametrize('c', [u.m, u.m / u.s, u.hPa, u.dimensionless_unscaled])
def test_unit(c):
    cy = load(dump(c))
    if isinstance(c, u.CompositeUnit):
        assert c == cy
    else:
        assert c is cy
Example #57
0
 def __new__(cls, x=0):
     if isinstance(x, afnumpy.ndarray):
         return x.astype(cls)
     else:
         return numpy.complex_(x)