Ejemplo n.º 1
0
def generate_dolph_chebyshev(lobe_fraction, tolerance):
    def cheb(m, x):
        if np.abs(x) <= 1:
            return np.cos(m * np.arccos(x))
        else:
            return np.cosh(m * np.arccosh(np.abs(x))).real

    w = int((1 / np.pi) * (1 / lobe_fraction) * np.arccosh(1 / tolerance))

    if w % 2 == 0:
        w -= 1

    beta = np.cosh(np.arccosh(1 / tolerance) / float(w - 1))

    print("lobe_fraction = {0}, tolerance = {1}, w = {2}, beta = {3}".format(lobe_fraction, tolerance, w, beta))

    x = np.empty(w, dtype=np.complex128)

    for i in xrange(w):
        x[i] = cheb(w - 1, beta * np.cos(np.pi * i / w)) * tolerance

    x = fft(x, n=w)
    x = fftshift(x)
    x = np.real(x)

    return {"x": x, "w": w}
Ejemplo n.º 2
0
def AF_zeros(a, M, R, dist_type, nbar=False, alpha=0):
    r"""
    This function gives array-factor zeros corresponding to different
    types of array distributions. Unless you know what you are doing exactly,
    do not use this function directly. Instead, user can use the function :func:`dist`.
    
    :param a:        separation between the elements along the x-axis in wavelengths
    :param M:        number of elements along the x-axis
    :param R:        side-lobe ratio in linear scale
    :param dist_type:type of the distribution, e.g., 'Dolph-Chebyshev', 'Riblet', etc.
    :param nbar:     transition index for dilation
    :param alpha:    Taylor's asymptotic tapering parameter
    
    :rtype:          U0, a Numpy array of size (*,1)
    """
    k = 2 * np.pi  # (angular) wave-number, which is 2*pi when lambda = 1
    m = np.ceil((M - 2) / 2)
    n = np.arange(1, 1 + m, 1)  # number of zeros for symmetric array-factors
    na = np.arange(1, M, 1)  # number of zeros for 'asymmetric' array-factors
    
    if(dist_type == "Dolph-Chebyshev"):  # Dolph zeros
        c = np.cosh(np.arccosh(R) / (M - 1))
        print c
        U0 = (2 / (a * k)) * np.arccos((np.cos(np.pi * (2 * n - 1) / (2 * M - 2))) / c)        
    elif(dist_type == "Riblet"):  # Riblet zeros
        c1 = np.cosh(np.arccosh(R) / m)
        c = np.sqrt((1 + c1) / (2 + (c1 - 1) * np.cos(k * a / 2) ** 2))
        alph = c * np.cos(k * a / 2)
        xi = (1 / c) * np.sqrt(((1 + alph ** 2) / 2) + ((1 - alph ** 2) / 2) * 
                               np.cos(((2 * n - 1) * np.pi) / (2 * m)))
        U0 = (2 / (a * k)) * np.arccos(xi)
    elif(dist_type == "Duhamel-b"):  # Duhamel bi-directional end-fire array zeros
        if(a < 0.5): c = np.cosh(np.arccosh(R) / (M - 1)) / np.sin((k * a) / 2)
        else: c = np.cosh(np.arccosh(R) / (M - 1))
        U0 = (2 / (a * k)) * np.arcsin((np.cos(np.pi * (2 * n - 1) / (2 * M - 2))) / c)
    elif(dist_type == "Duhamel-u"):  # Duhamel uni-directional end-fire array zeros
        Lamb = np.cosh(np.arccosh(R) / (M - 1))
        xi = (2 / a) * (0.5 * np.pi - (np.arctan(np.tan(k * a / 2) * ((Lamb + 1) / (Lamb - 1)))))
        c = 1 / (np.sin((xi - k) * a / 2))
        U0 = -(xi / k) + (2 / (a * k)) * np.arcsin((
                            np.cos(np.pi * (2 * na - 1) / (2 * M - 2))) / c)
    elif(dist_type == "McNamara-s"):  # McNamara-Zolotarev sum-pattern zeros
        U0 = "Yet to be done"
    elif(dist_type == "McNamara-d"):  # McNamara-Zolotarev difference-pattern zeros
        if(a < 0.5): c = 1 / np.sin((k * a) / 2)
        else: c = 1
        m1 = Zol.z_m_frm_R(M - 1, R)
        xn = Zol.z_Zolotarev_poly(N=M - 1, m=m1)[1][m + 1:]
        U0 = (2 / (a * k)) * np.arcsin(xn / c)
    if(nbar):  # Taylor's Dilation procedure
        if((dist_type == "Dolph-Chebyshev") or (dist_type == "Riblet") or (dist_type == "McNamara-s")):
            n_gen = np.arange(nbar, 1 + m, 1)  # indices of the generic zeros
            U0_gen = (n_gen + alpha / 2) * (1 / (M * a))  # generic sum zeros
        elif(dist_type == "McNamara-d"):
            n_gen = np.arange(nbar, 1 + m, 1)  # indices of the generic zeros
            U0_gen = (n_gen + (alpha + 1) / 2) * (1 / (M * a))  # generic difference zeros
        sigma = U0_gen[0] / U0[nbar - 1]  # Dilation factor
        U0 = np.hstack((sigma * U0[0:nbar - 1], U0_gen))  # Dilated zeros
    U0 = np.reshape(U0, (len(U0), -1))
    return U0
Ejemplo n.º 3
0
	def genCheby(self):
		# find order first
		n = np.ceil((np.arccosh(np.sqrt(self.sat-1)/self.epsilon))/(np.arccosh(self.ws/self.w1)));

		#find coefficients
		beta = np.sinh(np.arctanh(1/np.sqrt(1+self.epsilon**2))/n)

		cbk = [1];
		for i in range(1,len(str(n))+1):
			cbk.append(2*np.sin(((2*i-1)*np.pi)/(2*n)));

		ck = np.ones(len(str(n))+1);

		for i in range(1,len(cbk)):
			if (i == 1):
				ck[i] = cbk[i]/beta;
			else: 
				ck[i] = (cbk[i]*cbk[i-1])/(ck[i-1]*(beta**2+np.sin((i-1)*np.pi/n)**2));

		if (self.firsty == "l"):
			for i in range(1, len(str(n))+1):
				if (i%2 == 1):
					tmp = "L" + str(i)
					self.components.append(Component(tmp, "inductor", self.zin*ck[i]/self.w1));
				elif (i%2 == 0):
					tmp = "C" + str(i)
					self.components.append(Component(tmp, "capacitor", ck[i]/(self.w1*self.zin)));
		elif (self.firsty == "c"):
			for i in range(1, len(str(n))+1):
				if (i%2 == 1):
					tmp = "C" + str(i)
					self.components.append(Component(tmp, "capacitor", ck[i]/(self.w1*self.zin)));
				elif (i%2 == 0):
					tmp = "L" + str(i)
					self.components.append(Component(tmp, "inductor", self.zin*ck[i]/self.w1));
Ejemplo n.º 4
0
 def geodesic(self, P1, P2, theta):
     if np.ndim(P1)==1:
          arg =np.array([np.arccosh(2*P1[0]*P2[0]-np.inner(P1, P2))])
     else:
         arg = np.arccosh(2*P1[:,0]*P2[:,0]-np.einsum('ij...,ij...->i...',P1, P2))
         arg = arg[:, np.newaxis,...]
     return ((1-theta)*sinhc((1-theta)*arg)*P1 + theta*sinhc(theta*arg)*P2)/sinhc(arg)
Ejemplo n.º 5
0
 def test_arccosh(self):
     q = [1, 2, 3, 4, 6] * self.ureg.dimensionless
     x = np.ones((1,1))  * self.ureg.rad
     self.assertEqual(
         np.arccosh(q),
         np.arccosh(q.magnitude * self.ureg.rad)
     )
Ejemplo n.º 6
0
    def test_arccosh(self):
        import math
        from numpy import arccosh

        for v in [1.0, 1.1, 2]:
            assert math.acosh(v) == arccosh(v)
        for v in [-1.0, 0, 0.99]:
            assert math.isnan(arccosh(v))
Ejemplo n.º 7
0
def localized(T, a, xi):
    '''
    total transmission distribution for 1D localized system;
    effective localization length also fit parameter (in units
    of L)
    '''
    return (a * np.sqrt(np.arccosh(T**(-1./2.))) / (T**(3./2.) * (1.-T)**(1./4.)) \
        * np.exp(-0.5 * xi * np.arccosh(T**(-1./2.))**2.)).real
Ejemplo n.º 8
0
Archivo: windows.py Proyecto: 87/scipy
def chebwin(M, at, sym=True):
    """Return a Dolph-Chebyshev window.

    Parameters
    ----------
    M : int
        Number of points in the output window. If zero or less, an empty
        array is returned.
    at : float
        Attenuation (in dB).
    sym : bool, optional
        When True, generates a symmetric window, for use in filter design.
        When False, generates a periodic window, for use in spectral analysis.

    Returns
    -------
    w : ndarray
        The window, with the maximum value always normalized to 1

    """
    if M < 1:
        return np.array([])
    if M == 1:
        return np.ones(1, 'd')

    odd = M % 2
    if not sym and not odd:
        M = M + 1

    # compute the parameter beta
    order = M - 1.0
    beta = np.cosh(1.0 / order * np.arccosh(10 ** (np.abs(at) / 20.)))
    k = np.r_[0:M] * 1.0
    x = beta * np.cos(np.pi * k / M)
    # Find the window's DFT coefficients
    # Use analytic definition of Chebyshev polynomial instead of expansion
    # from scipy.special. Using the expansion in scipy.special leads to errors.
    p = np.zeros(x.shape)
    p[x > 1] = np.cosh(order * np.arccosh(x[x > 1]))
    p[x < -1] = (1 - 2 * (order % 2)) * np.cosh(order * np.arccosh(-x[x < -1]))
    p[np.abs(x) <= 1] = np.cos(order * np.arccos(x[np.abs(x) <= 1]))

    # Appropriate IDFT and filling up
    # depending on even/odd M
    if M % 2:
        w = np.real(fft(p))
        n = (M + 1) / 2
        w = w[:n] / w[0]
        w = np.concatenate((w[n - 1:0:-1], w))
    else:
        p = p * np.exp(1.j * np.pi / M * np.r_[0:M])
        w = np.real(fft(p))
        n = M / 2 + 1
        w = w / w[1]
        w = np.concatenate((w[n - 1:0:-1], w[1:n]))
    if not sym and not odd:
        w = w[:-1]
    return w
Ejemplo n.º 9
0
def acosh(x):
    """
    Inverse hyperbolic cosine
    """
    if isinstance(x, UncertainFunction):
        mcpts = np.arccosh(x._mcpts)
        return UncertainFunction(mcpts)
    else:
        return np.arccosh(x)
Ejemplo n.º 10
0
def test_arccosh():
    # Domain for arccosh starts at 1
    a = afnumpy.random.random((2,3))+1
    b = numpy.array(a)
    fassert(afnumpy.arccosh(a), numpy.arccosh(b))
    c = afnumpy.random.random((2,3))
    d = numpy.array(a)
    fassert(afnumpy.arccosh(a, out=c), numpy.arccosh(b, out=d))
    fassert(c, d)
Ejemplo n.º 11
0
    def test_der_arccosh():
        x = np.linspace(1.2, 5, 5)
        h = 1e-8
        der1 = np.arccosh(bicomplex(x + h * 1j, 0)).imag1 / h
        np.testing.assert_allclose(der1, 1. / np.sqrt(x**2 - 1))

        h = (_default_base_step(x, scale=2.5) + 1) - 1
        der2 = np.arccosh(bicomplex(x + h * 1j, h)).imag12 / h**2
        true_der2 = -x / (x**2-1)**(3. / 2)
        np.testing.assert_allclose(der2, true_der2, atol=1e-5)
Ejemplo n.º 12
0
def localized_log(T, a, xi):
    '''
    total transmission distribution for 1D localized system;
    distribution for lnT ( P(lnT) = T * P(T); prefactor ln(10), which can
    be considered as contained in amplitude a
    effective localization length also fit parameter (in units
    of L)
    '''
    return (a * T * np.sqrt(np.arccosh(T**(-1./2.))) / (T**(3./2.) * (1.-T)**(1./4.)) \
        * np.exp(-0.5 * xi * np.arccosh(T**(-1./2.))**2.)).real
Ejemplo n.º 13
0
def arccosh(x, out=None):
    """
    Raises a ValueError if input cannot be rescaled to a dimensionless
    quantity.
    """
    if not isinstance(x, Quantity):
        return np.arccosh(x, out)

    return Quantity(
        np.arccosh(x.rescale(dimensionless).magnitude, out),
        dimensionless,
        copy=False
    )
Ejemplo n.º 14
0
def chebwin(M, at, sym=1):
    """Dolph-Chebyshev window.

    INPUTS:

      M : int
        Window size
      at : float
        Attenuation (in dB)
      sym : bool
        Generates symmetric window if True.

    """
    if M < 1:
        return array([])
    if M == 1:
        return ones(1,'d')

    odd = M % 2
    if not sym and not odd:
        M = M+1

    # compute the parameter beta
    order = M - 1.0
    beta = cosh(1.0/order * arccosh(10**(abs(at)/20.)))
    k = r_[0:M]*1.0
    x = beta*cos(pi*k/M)
    #find the window's DFT coefficients
    # Use analytic definition of Chebyshev polynomial instead of expansion
    # from scipy.special. Using the expansion in scipy.special leads to errors.
    p = zeros(x.shape)
    p[x > 1] = cosh(order * arccosh(x[x > 1]))
    p[x < -1] = (1 - 2*(order%2)) * cosh(order * arccosh(-x[x < -1]))
    p[np.abs(x) <=1 ] = cos(order * arccos(x[np.abs(x) <= 1]))

    # Appropriate IDFT and filling up
    # depending on even/odd M
    if M % 2:
        w = real(fft(p))
        n = (M + 1) / 2
        w = w[:n] / w[0]
        w = concatenate((w[n - 1:0:-1], w))
    else:
        p = p * exp(1.j*pi / M * r_[0:M])
        w = real(fft(p))
        n = M / 2 + 1
        w = w / w[1]
        w = concatenate((w[n - 1:0:-1], w[1:n]))
    if not sym and not odd:
        w = w[:-1]
    return w
Ejemplo n.º 15
0
def chebwin(M, at, sym=1):
    """Dolph-Chebyshev window.

    INPUTS:

      M : int
        Window size
      at : float
        Attenuation (in dB)
      sym : bool
        Generates symmetric window if True.

    """
    if M < 1:
        return array([])
    if M == 1:
        return ones(1,'d')

    odd = M % 2
    if not sym and not odd:
        M = M+1

    # compute the parameter beta
    beta = cosh(1.0/(M-1.0)*arccosh(10**(at/20.)))
    k = r_[0:M]*1.0
    x = beta*cos(pi*k/M)
    #find the window's DFT coefficients
    p = zeros(x.shape) * 1.0
    for i in range(len(x)):
        if x[i] < 1:
            p[i] = cos((M - 1) * arccos(x[i]))
        else:
            p[i] = cosh((M - 1) * arccosh(x[i]))

    # Appropriate IDFT and filling up
    # depending on even/odd M
    if M % 2:
        w = real(fft(p));
        n = (M + 1) / 2;
        w = w[:n] / w[0];
        w = concatenate((w[n - 1:0:-1], w))
    else:
        p = p * exp(1.j*pi / M * r_[0:M])
        w = real(fft(p));
        n = M / 2 + 1;
        w = w / w[1];
        w = concatenate((w[n - 1:0:-1], w[1:n]));
    if not sym and not odd:
        w = w[:-1]
    return w
Ejemplo n.º 16
0
def ising_v(dtau, U, L=32, polar=0.5):
    """initialize the vector V of Ising fields

    .. math:: V = \\lambda (\\sigma_1, \\sigma_2, \\cdots, \\sigma_L)

    where the vector entries :math:`\\sigma_n=\\pm 1` are randomized subject
    to a threshold given by polar. And

    .. math:: \\cosh(\\lambda) = \\exp(\\Delta \\tau \\frac{U}{2})

    Parameters
    ----------
    dtau : float
        time spacing :math::`\\Delta\\Tau`
    U : float
        local Coulomb repulsion
    L : integer
        length of the array
    polar : float :math:`\\in (0, 1)`
        polarization threshold, probability of :math:`\\sigma_n=+ 1`

    Returns
    -------
    out : single dimension ndarray
    """
    lam = np.arccosh(np.exp(dtau*U/2))
    vis = np.ones(L)
    rand = np.random.rand(L)
    vis[rand > polar] = -1
    return vis*lam
Ejemplo n.º 17
0
def FS_Chebyshev(N, R, x_min, x_max, x_num, plot_far=False, dB_limit= -40):
    """Function to evaluate Fourier series coefficients of Chebyshev far-field
       pattern"""
       
    c = np.cosh(np.arccosh(R) / (N))
    c = str(c)     
           
    if(N % 2 == 0):
        m_start = int(-N / 2)
        m_stop = int(N / 2)
        N = str(N)       
        fun_str_re = 'special.eval_chebyt(' + N + ',' + c + '*np.cos(x/2))'
        m_index, zm = FS(fun_str_re, m_start=m_start, m_stop=m_stop, err_lim=1e-5)        
    else:
        m_start = -N # make this (2*P+1) ... and take fourier for only half period
        m_stop = N
        N = str(N)
        fun_str_re = 'special.eval_chebyt(' + N + ',' + c + '*np.cos(x))'
        m_index, zm = FS(fun_str_re, m_start=m_start, m_stop=m_stop, err_lim=1e-5)
        
    if(plot_far):
        x, AF = IFS(zm, 2 * np.pi, m_start, m_stop, x_min, x_max, x_num)        
        AF = 20 * np.log10(abs(AF))
        AF = pl.cutoff(AF, dB_limit)
        plt.plot(x * (180 / np.pi), AF); plt.axis('tight'); plt.grid(True)        
        plt.title('Far-field Pattern')
        plt.xlabel(r'$\phi$')
        plt.ylabel('AF')
        plt.show()        
                     
    return m_index, zm
Ejemplo n.º 18
0
def elliptic_hamiltonian(u,v, opts):
    
    '''
    
    Returns arrays of values for the first elliptic invariant (Hamiltonian) for a system with NL magnetic potential
    
    '''
    #beta = 0.6539
    #beta =  fixed['beta']
    #beta = 6.1246858201346921
    beta = opts.betae
    
    
    t = opts.t 
    
    c = opts.c
    #c = opts.c * np.sqrt(beta)
    
    f2u = u * np.sqrt(u**2 -1.) * np.arccosh(u)
    g2v = v * np.sqrt(1. - v**2) * (-np.pi/2 + np.arccos(v))
    
    elliptic = (f2u + g2v) / (u**2 - v**2)
    kfac = -1.*t*c*c
    
    return kfac*elliptic
Ejemplo n.º 19
0
    def compute_potential(self, xHat, yHat):
        """Compute the general potential for elliptic element with strength t"""
        
        quadratic = 0.5 * (xHat**2 + yHat**2)
        
        #compute default prefactors
        elliptic = 0.
        kfac = 1.
        
        #only recompute if t > 0
        if self._t != 0.:
            xN = xHat / self._c
            yN = yHat / self._c

            # Elliptic coordinates
            u = ( np.sqrt((xN + 1.)**2 + yN**2) +
                  np.sqrt((xN - 1.)**2 + yN**2) )/2.
            v = ( np.sqrt((xN + 1.)**2 + yN**2) -
                  np.sqrt((xN - 1.)**2 + yN**2) )/2.

            f2u = u * np.sqrt(u**2 - 1.) * np.arccosh(u)
            g2v = v * np.sqrt(1. - v**2) * (-np.pi/2 + np.arccos(v))

            kfac = -1.*self._t * self._c**2
            elliptic = (f2u + g2v) / (u**2 - v**2)

        potential = quadratic + kfac * elliptic
        
        return potential
Ejemplo n.º 20
0
def taylor_win(n, nbar=4, sll=-30):
    """
    http://www.dsprelated.com/showcode/6.php

    from http://mathforum.org/kb/message.jspa?messageID=925929:

    A Taylor window is very similar to Chebychev weights. While Chebychev
    weights provide the tighest beamwidth for a given side-lobe level, taylor
    weights provide the least taper loss for a given sidelobe level.

    'Antenna Theory: Analysis and Design' by Constantine Balanis, 2nd
    edition, 1997, pp. 358-368, or 'Modern Antenna Design' by Thomas
    Milligan, 1985, pp.141-148.
    """
    def calculate_fm(m, sp2, a, nbar):
        n = numpy.arange(1, nbar)
        p = numpy.hstack([numpy.arange(1, m, dtype='f8'),
                          numpy.arange(m+1, nbar, dtype='f8')])
        num = numpy.prod((1 - (m**2/sp2) / (a**2 + (n - 0.5)**2)))
        den = numpy.prod(1.0 - m**2 / p**2)
        fm = ((-1)**(m + 1) * num) / (2.0 * den)
        return fm
    a = numpy.arccosh(10.0**(-sll/20.0))/numpy.pi
    sp2 = nbar**2 / (a**2 + (nbar - 0.5)**2)
    w = numpy.ones(n)
    fm = numpy.zeros(nbar)
    summation = 0
    k = numpy.arange(n)
    xi = (k - 0.5 * n + 0.5) / n
    for m in range(1, nbar):
        fm[m] = calculate_fm(m, sp2, a, nbar)
        summation = fm[m] * numpy.cos(2.0 * numpy.pi * m * xi) + summation
    w += 2.0 * summation
    return w
Ejemplo n.º 21
0
    def pinv(self, v):
        # first transform coordinates in inner elliptic coordinates
        # with (-a, 0) (a,0)
        v_in = dot(self.__rotmat.T, v - self.__centrum) / self.__a

        # m1 = cosh(mu), n1 = cos(nu)
        # solve for
        # v[0] = m1* n1
        # v[1]**2 = (m1**2 -1)(1 - n1**2)
        a = dot(v_in, v_in) + 1.
        m1 = sqrt(a /2. + sqrt(a**2 - 4 * v_in[0]**2) / 2.)

        # 1 <= m1, only rounding errors could say something else
        if abs(m1)  < 1.:
            mu = 0.
            m1 = 1.
        else:
            mu = arccosh(m1)

        n1 = v_in[0] / m1
        nu = acos(n1)

        # one has to consider that acos gives only values for the upper half
        if v_in[1] < 0. and abs(v_in[1]) > finfo(float).eps:
            nu = 2. * pi - nu

        return array([mu, nu])
Ejemplo n.º 22
0
    def computeInvariant(self, xHat, pxHat, yHat, pyHat):
        """Compute the 2nd invariant for the integrable elliptic potential"""

        xN = xHat / self.ellipticC
        yN = yHat / self.ellipticC

        # Elliptic coordinates
        u = (np.sqrt((xN + 1)**2 + yN**2) +\
                 np.sqrt((xN - 1)**2 + yN**2))/2.
        v = (np.sqrt((xN + 1)**2 + yN**2) -\
                 np.sqrt((xN - 1)**2 + yN**2))/2.

        # Elaborate x^2 + y^2
        f1u = self.ellipticC**2 * u**2 * (u**2 - 1)
        g1v = self.ellipticC**2 * v**2 * (1 - v**2)

        f2u = u * np.sqrt(u**2 - 1.) * np.arccosh(u)
        g2v = v * np.sqrt(1. - v**2) * (-np.pi/2 + np.arccos(v))

        kfac = self.ellipticT * self.ellipticC**2

        invariant = (x*py - y*px)**2 + self.ellipticC**2*(px**2) +\
            (2*self.ellipticC**2 ) * ((0.5*f1u - kfac*f2u)*v**2 \
            + (0.5 * g1v + kfac * g2v) * u**2 ) /(u**2 - v**2)

        return invariant
Ejemplo n.º 23
0
    def computeHamiltonian(self, xHat, pxHat, yHat, pyHat):
        """Compute the Hamiltonian (1st invariant) for the integrable elliptic potential"""

        quadratic = 0.5 * (pxHat**2 + pyHat**2) #+ 0.5 * (xHat**2 + yHat**2)

        elliptic = 0.
        kfac = 1.
        if self.ellipticT != 0.:
            xN = xHat / self.ellipticC
            yN = yHat / self.ellipticC

            # Elliptic coordinates
            u = ( np.sqrt((xN + 1.)**2 + yN**2) +
                  np.sqrt((xN - 1.)**2 + yN**2) )/2.
            v = ( np.sqrt((xN + 1.)**2 + yN**2) -
                  np.sqrt((xN - 1.)**2 + yN**2) )/2.

            f2u = u * np.sqrt(u**2 - 1.) * np.arccosh(u)
            g2v = v * np.sqrt(1. - v**2) * (-np.pi/2 + np.arccos(v))

            kfac = self.ellipticT * self.ellipticC**2
            elliptic = (f2u + g2v) / (u**2 - v**2)

        hamiltonian = quadratic + self.computePotential(xHat, yHat)
        return hamiltonian
Ejemplo n.º 24
0
def taylor(nsamples, S_L=43):
    xi = np.linspace(-0.5, 0.5, nsamples)
    A = 1.0/np.pi*np.arccosh(10**(S_L*1.0/20))
    n_bar = int(2*A**2+0.5)+1
    sigma_p = n_bar/np.sqrt(A**2+(n_bar-0.5)**2)

    #Compute F_m
    m = np.arange(1,n_bar)
    n = np.arange(1,n_bar)
    F_m = np.zeros(n_bar-1)
    for i in m:
        num = 1
        den = 1
        for j in n:
            num = num*\
            (-1)**(i+1)*(1-i**2*1.0/sigma_p**2/(\
                            A**2+(j-0.5)**2))
            if i!=j:
                den = den*(1-i**2*1.0/j**2)

        F_m[i-1] = num/den

    w = np.ones(nsamples)
    for i in m:
        w += F_m[i-1]*np.cos(2*np.pi*i*xi)

    w = w/w.max()
    return(w)
Ejemplo n.º 25
0
    def t_from_z(self, z):
        """
        Compute the age of the Universe from redshift.  This is based on Enzo's
        CosmologyComputeTimeFromRedshift.C, but altered to use physical units.  
        Similar to hubble_time, but using an analytical function.

        Parameters
        ----------
        z : float
            Redshift.

        Examples
        --------

        >>> co = Cosmology()
        >>> print co.t_from_z(0.).in_units("Gyr")

        See Also
        --------

        hubble_time
        
        """
        omega_curvature = 1.0 - self.omega_matter - self.omega_lambda
 
        # 1) For a flat universe with omega_matter = 1, things are easy.
 
        if ((self.omega_matter == 1.0) and (self.omega_lambda == 0.0)):
            t0 = 2.0/3.0/np.power(1+z, 1.5)
 
        # 2) For omega_matter < 1 and omega_lambda == 0 see
        #    Peebles 1993, eq. 13-3, 13-10.
 
        if ((self.omega_matter < 1) and (self.omega_lambda == 0)):
            eta = np.arccosh(1 + 
                             2*(1-self.omega_matter)/self.omega_matter/(1+z))
            t0 = self.omega_matter/ \
              (2*np.power(1.0-self.omega_matter, 1.5))*\
              (np.sinh(eta) - eta)
 
        # 3) For omega_matter > 1 and omega_lambda == 0, use sin/cos.
 
        if ((self.omega_matter > 1) and (self.omega_lambda == 0)):
            eta = np.arccos(1 - 2*(1-self.omega_matter)/self.omega_matter/(1+z))
            t0 = self.omega_matter/(2*np.power(1.0-self.omega_matter, 1.5))*\
                (eta - np.sin(eta))
 
        # 4) For flat universe, with non-zero omega_lambda, see eq. 13-20.
 
        if ((np.fabs(omega_curvature) < 1.0e-3) and (self.omega_lambda != 0)):
            t0 = 2.0/3.0/np.sqrt(1-self.omega_matter)*\
                np.arcsinh(np.sqrt((1-self.omega_matter)/self.omega_matter)/ \
                               np.power(1+z, 1.5))
  
        # Now convert from Time * H0 to time.
  
        my_time = t0 / self.hubble_constant
    
        return my_time.in_cgs()
Ejemplo n.º 26
0
def _pyabel_direct_integral(f, r, correction, int_func=simpson_rule_wrong):
    """
    Calculation of the integral  used in Abel transform
    (both direct and inverse).
             ∞
            ⌠
            ⎮      f(r)
            ⎮ ────────────── dr
            ⎮    ___________
            ⎮   ╱  2   2
            ⎮ ╲╱  y - r
            ⌡
            y
    Returns:
    --------
    np.array: of the same shape as f with the integral evaluated at r

    """
    if correction not in [0, 1]:
        raise ValueError

    if is_uniform_sampling(r):
        int_opts = {'dx': abs(r[1] - r[0])}
    else:
        int_opts = {'x': r}

    N0 = f.shape[0]
    N1 = f.shape[1]
    out = np.zeros(f.shape)
    R, Y = np.meshgrid(r, r, indexing='ij')
    # the following 2 lines can be better written
    i_vect = np.arange(len(r), dtype=int)
    II, JJ = np.meshgrid(i_vect, i_vect, indexing='ij')
    mask = (II < JJ)

    I_sqrt = np.zeros(R.shape)
    I_sqrt[mask] = np.sqrt((Y**2 - R**2)[mask])

    I_isqrt = np.zeros(R.shape)
    I_isqrt[mask] = 1./I_sqrt[mask]

    for i, row in enumerate(f):  # loop over rows (z)
        P = row[None, :] * I_isqrt  # set up the integral
        out[i, :] = int_func(P, axis=1, **int_opts)  # take the integral
    """
    Compute the correction
    Pre-calculated analytical integration of the cell with the singular value
    Assuming a piecewise linear behaviour of the data
    c0*acosh(r1/y) - c_r*y*acosh(r1/y) + c_r*sqrt(r1**2 - y**2)
    """
    if correction == 1:
        # computing forward derivative of the data
        f_r = (f[:, 1:] - f[:, :N1-1])/np.diff(r)[None, :]

        for i, row in enumerate(f):  # loop over rows (z)
            out[i, :-1] += I_sqrt[II+1 == JJ]*f_r[i] \
                    + np.arccosh(r[1:]/r[:-1])*(row[:-1] - f_r[i]*r[:-1])

    return out
Ejemplo n.º 27
0
def findTOF(r0, r, p, mu=Earth.mu):
    """Finds the Time of Flight between two position vectors (Algorithm 11)
    
    Finds the time of flight bewteen two position vectors in the IJK frame.  
    For reference, see Algorithm 11 in Vallado (Fourth Edition), Section 2.8
    (pg 126)
    
    Parameters
    ----------
    r0: numpy.matrix (3x1)
        Initial position vector (km)
    r: numpy.matrix (3x1)
        Second position vector (km)
    p: double
        Semi-parameter (km)
    mu: double, optional, default=3.986004415E5 (Earth.mu in solarsys.py)
        Gravitational parameter (km^3/s^2)
        
    Returns
    -------
    TOF: double
        Time of flight (seconds)
    """

    r0_mag = np.linalg.norm(r0)
    r_mag = np.linalg.norm(r)
    
    cosdv = np.dot(r0.T, r)/(r0_mag*r_mag)
    del_anom = np.arccos(cosdv)
    k = r0_mag*r_mag*(1.0 - cosdv)
    l = r0_mag + r_mag
    m = r0_mag*r_mag*(1.0 + cosdv)
    
    a = m*k*p/((2.0*m - l*l)*p*p + 2.0*k*l*p - k*k)
    f = 1.0 - (r_mag/p)*(1.0 - cosdv)
    g = r0_mag*r_mag*np.sin(del_anom)/(np.sqrt(mu*p))
    
    if a > 0.0:
        if a==np.inf:
            c = np.sqrt(r0_mag**2 + r_mag**2 - 2.0*r0_mag*r_mag*cosdv)
            s = (r0_mag + r_mag + c)*0.5
            TOF = (2.0/3.0)*np.sqrt(0.5*s**3/mu)*(1.0 - ((s - c)/s)**1.5)
            return TOF
        else:
            f_dot = np.sqrt(mu/p)*np.tan(0.5*del_anom)*((1.0 - cosdv)/p - 
                1.0/r0_mag - 1/r_mag)
            cosde = 1.0 - (r0_mag/a)*(1.0 - f)
            sinde = (-r0_mag*r_mag*f_dot)/(np.sqrt(mu*a))
            del_E = np.arccos(cosde)
            TOF = g + np.sqrt(a**3/mu)*(del_E - sinde)
            return TOF
    elif a < 0.0:
        coshdh = 1.0 + (f - 1.0)*(r0_mag/a)
        del_H = np.arccosh(coshdh)
        TOF = g + np.sqrt((-a)**3/mu)*(np.sinh(del_H) - del_H)
        return TOF
    else:
        TOF = None
        return TOF
def guess_q12_vals(angles, epsilon):
    """Generates an initial guess of qp and qm for the rootfinder.

    :param angles:  A 3D numpy.array, where angles[0] is a 2D array with
                    costheta values and angles[1] is a 2D array with phi values
    :param epsilon: A positive real number parametrizing the strength of the
                    weak measurement.
    :returns:       A 3D numpy.array "guess", where guess[0] is a 2D array
                    holding the q1 values and guess[1] is a 2D array holding
                    the q2 values.

    """
    return np.where(angles[0] == 1, np.zeros(angles.shape),
                    np.array([
                    cos(angles[1])*arccosh(1/angles[0])/epsilon,
                    sin(angles[1])*arccosh(1/angles[0])/epsilon
                    ]))
Ejemplo n.º 29
0
def _jl_approx_lowz(l, z):
    
    nu = l + 0.5
    nutanha = (nu * nu - z * z)**0.5
    arg = nutanha - nu * np.arccosh(nu / z)
    
    return (np.exp(arg) * (1 + 1.0 / (8 * nutanha) - 5.0 * nu**2 / (24 * nutanha**3)
                           + 9.0 / (128 * nutanha**2) - 231.0 * nu**2 / (576 * nutanha**4))
            / (2 * (z * nutanha)**0.5))
Ejemplo n.º 30
0
def acosh(x):
    # a' = vu'
    # v' = au'
    a = x.coeffs
    u, v = zeros(len(a), dtype=a.dtype), zeros(len(a), dtype=a.dtype)
    u, v = zeros(len(a), dtype=a.dtype), zeros(len(a), dtype=a.dtype)
    u[0], v[0] = numpy.arccosh(a[0]), numpy.sqrt(a[0]**2 - 1)
    multi('aeqvu', u, 1.0, a, v, 'ueqva', v, 1.0, u, a)
    return x.__class__(u, x.coeffs.dtype)
Ejemplo n.º 31
0
 def integrateCircular(self,lower,upper,method=None,**kwargs):
     """
     NFW Has an analytic form for the spherical integral - if the lower 
     is not 0 or or if the keyword 'numerical' is True, this function will
     fall back to FunctionModel1D.integrateCircular 
     """        
     if method is not None or np.any(lower!=0):
         return FunctionModel1D.integrate(self,lower,upper,method,**kwargs)
     
     x = upper/self.rc
     xterm = None
     
     if x > 1:
         Cinv = np.arccos(1/x)
     elif x < 1:
         Cinv = np.arccosh(1/x)
     else:
         xterm = 1-np.log(2)
     
     if xterm is None:
         xterm = Cinv*np.abs(x*x - 1)**-0.5 + np.log(x/2)
             
     return self.sig0*xterm
def np_distance(x, y):
    """
    The distance between two vectors
    :param x: shape (1, ndims)
    :param y: shape (1,ndims)
    :return: a scalar hyperbolic distance
    """
    # assert np.round(norm_square, 5) == 0.16
    denom1 = 1 - np.square(np.linalg.norm(x))
    print denom1
    # assert np.round(denom1, 5) == 0.91
    if len(y.shape) > 1:
        norm_square = np.square(np.linalg.norm(x - y, axis=1))
        denom2 = 1 - np.square(np.linalg.norm(y, axis=1))
    else:
        norm_square = np.square(np.linalg.norm(x - y, axis=0))
        denom2 = 1 - np.square(np.linalg.norm(y, axis=0))
    print norm_square
    print denom2
    # assert np.round(denom2, 5) == 0.75
    arg = 1.0 + 2.0 * norm_square / (denom1 * denom2)
    print arg
    return np.float32(np.arccosh(arg))
Ejemplo n.º 33
0
    def computePotential(self, xHat, yHat):
        quadratic = 0.5 * (xHat**2 + yHat**2)

        elliptic = 0.
        kfac = 1.
        if self.ellipticT != 0.:
            xN = xHat / self.ellipticC
            yN = yHat / self.ellipticC

            # Elliptic coordinates
            u = ( np.sqrt((xN + 1.)**2 + yN**2) +
                  np.sqrt((xN - 1.)**2 + yN**2) )/2.
            v = ( np.sqrt((xN + 1.)**2 + yN**2) -
                  np.sqrt((xN - 1.)**2 + yN**2) )/2.

            f2u = u * np.sqrt(u**2 - 1.) * np.arccosh(u)
            g2v = v * np.sqrt(1. - v**2) * (-np.pi/2 + np.arccos(v))

            kfac = self.ellipticT * self.ellipticC**2
            elliptic = (f2u + g2v) / (u**2 - v**2)

        potential = quadratic + kfac * elliptic
        return potential
Ejemplo n.º 34
0
def elliptic_hamiltonian(u,v, opts):

    '''

    Returns arrays of values for the first elliptic invariant (Hamiltonian) for a system with NL magnetic potential

    '''
    #beta = 0.6539
    beta =  fixed['beta']
    beta = 6.1246858201346921

    t = opts.t
    #
    c = opts.c / np.sqrt(beta)
    #c = opts.c * np.sqrt(beta)

    f2u = u * np.sqrt(u**2 -1.) * np.arccosh(u)
    g2v = v * np.sqrt(1. - v**2) * (-np.pi/2 + np.arccos(v))

    elliptic = (f2u + g2v) / (u**2 - v**2)
    kfac = -1*t*c*c

    return kfac*elliptic
Ejemplo n.º 35
0
    def computeHamiltonian(self, xHat, pxHat, yHat, pyHat):
        """Compute the Hamiltonian (1st invariant) for the integrable elliptic potential"""

        quadratic = 0.5 * (pxHat**2 + pyHat**2) + 0.5 * (xHat**2 + yHat**2)

        xN = xHat / self.ellipticC
        yN = yHat / self.ellipticC

        # Elliptic coordinates
        u = ( np.sqrt((xN + 1.)**2 + yN**2) +
                  np.sqrt((xN - 1.)**2 + yN**2) )/2.
        v = ( np.sqrt((xN + 1.)**2 + yN**2) -
                  np.sqrt((xN - 1.)**2 + yN**2) )/2.

        f2u = u * np.sqrt(u**2 - 1.) * np.arccosh(u)
        g2v = v * np.sqrt(1. - v**2) * (-np.pi/2 + np.arccos(v))

        kfac = self.ellipticT * self.ellipticC**2
        elliptic = (f2u + g2v) / (u**2 - v**2)
        elliptic *= kfac

        hamiltonian = quadratic + elliptic
        return hamiltonian
Ejemplo n.º 36
0
def arccosh(x1):
    """
    Trigonometric inverse hyperbolic cosine, element-wise.

    For full documentation refer to :obj:`numpy.arccosh`.

    Limitations
    -----------
    Input array is supported as :obj:`dpnp.ndarray`.
    Input array data types are limited by supported DPNP :ref:`Data types`.

    See Also
    --------
    :obj:`dpnp.cosh` : Hyperbolic cosine, element-wise.
    :obj:`dpnp.arcsinh` : Inverse hyperbolic sine element-wise.
    :obj:`dpnp.sinh` : Hyperbolic sine, element-wise.
    :obj:`dpnp.arctanh` : Inverse hyperbolic tangent element-wise.
    :obj:`dpnp.tanh` : Compute hyperbolic tangent element-wise.

    Examples
    --------
    >>> import numpy
    >>> import dpnp as np
    >>> x = np.array([numpy.e, 10.0])
    >>> out = np.arccosh(x)
    >>> [i for i in out]
    [1.65745445, 2.99322285]

    """

    if (use_origin_backend(x1)):
        return numpy.arccosh(x1)

    if not isinstance(x1, dparray):
        raise TypeError(f"DPNP arccosh(): Unsupported x1={type(x1)}")

    return dpnp_arccosh(x1)
Ejemplo n.º 37
0
def taylor_win(n, sll):
    """
    http://www.dsprelated.com/showcode/6.php

    from http://mathforum.org/kb/message.jspa?messageID=925929:

    A Taylor window is very similar to Chebychev weights. While Chebychev
    weights provide the tighest beamwidth for a given side-lobe level, taylor
    weights provide the least taper loss for a given sidelobe level.

    'Antenna Theory: Analysis and Design' by Constantine Balanis, 2nd
    edition, 1997, pp. 358-368, or 'Modern Antenna Design' by Thomas
    Milligan, 1985, pp.141-148.
    """
    def calculate_fm(m, sp2, a, nbar):
        n = np.arange(1, nbar)
        p = np.hstack([np.arange(1, m), np.arange(m + 1, nbar)])
        num = np.prod((1 - (m**2 / sp2) / (a**2 + (n - 0.5)**2)))
        den = np.prod(1 - m**2 / p**2)
        return ((-1)**(m + 1) * num) / (2 * den)

    nbar = int(np.ceil(2.0 * (acosh(10**(-sll / 20.0)) / pi)**2 + 0.5))
    n *= 2
    a = np.arccosh(10**(-sll / 20)) / pi
    sp2 = nbar**2 / (a**2 + (nbar - 0.5)**2)
    w = np.ones(n)
    fm = np.zeros(nbar)
    summation = 0
    k = np.arange(n)
    xi = (k - 0.5 * n + 0.5) / n
    for m in range(1, nbar):
        fm[m] = calculate_fm(m, sp2, a, nbar)
        summation += fm[m] * np.cos(2 * pi * m * xi)
    w += w * summation
    w /= w.max()
    w = w[n // 2:]
    return w
Ejemplo n.º 38
0
        def surf_den_fn(a):

            # Convert single floats into arrays
            if not hasattr(a, '__len__'):
                a = np.array([
                    a,
                ])

            rf = a / r_vir

            C_inv = np.empty(rf.shape)
            above_rf = a > r_vir / c
            below_rf = np.invert(above_rf)
            C_inv[above_rf] = np.arccos(1. / c / rf[above_rf])
            C_inv[below_rf] = np.arccosh(1. / c / rf[below_rf])

            result = ((c**2. * g_c / (2. * np.pi)) * m_vir / r_vir**2. *
                      (1. - np.abs(c**2. * rf**2. - 1.)**-0.5 * C_inv) /
                      (c**2. * rf**2. - 1.))

            if len(result) == 1:
                return result[0]

            return result
Ejemplo n.º 39
0
    def __adjust_number__(self, preNum, compNum):

        self.numberUV[0] = np.maximum(preNum[0], compNum[0])
        self.numberUV[1] = np.maximum(
            preNum[1], compNum[1]) if self.depart_flag else self.numberUV[0]

        self.oddU = (np.mod(self.numberUV[0], 2) == 1)
        self.oddV = (np.mod(self.numberUV[1], 2) == 1)

        degree = self.omega * 180 / np.pi
        for zmc in np.array([0, 1], dtype=int):
            if preNum[zmc] > compNum[zmc]:
                self.interval[zmc] = 51 * self.lobeF / (degree[zmc] *
                                                        self.numberUV[zmc])
            else:
                degree[zmc] = 51 * self.lobeF / (self.interval[zmc] *
                                                 self.numberUV[zmc])

        self.omega = degree * np.pi / 180.

        self.x0 = np.cosh(np.arccosh(self.R0) / (self.numberUV - 1))
        direct = 2 * self.R0 * self.R0 / (
            1 + (self.R0 * self.R0 - 1) * degree / 51)
        self.direct = np.pi * direct[0] * direct[1]
Ejemplo n.º 40
0
def eshelby(nu_m, s):
    I1 = (2.*s/(s**2.-1.)**1.5)*(s*(s**2.-1.)**.5-np.arccosh(s))
    Q = 3./(8.*(1-nu_m))
    R = (1.-2.*nu_m)/(8.*(1.-nu_m))
    T = Q*(4.-3.*I1)/(3*(s**2.-1.))
    I3 = 4.-2.*I1
    S = np.zeros((6,6))
    S[0,0] = Q + R*I1 + 0.75*T
    S[1,1] = S[0,0]
    S[2,2] = 4./3.*Q + R*I3 + 2.*s**2.*T
    S[0,1] = Q/3. - R*I1 + 4.*T/3.
    S[1,0] = S[0,1]
    S[0,2] = -R*I1 - s**2*T
    S[1,2] = S[0,2]
    S[2,0] = -R*I3 - T
    S[2,1] = S[2,0]
    S[5,5] = Q/3 + R*I1 + T/4
    S[3,3] = 2*R - I1*R/2 - (1+s**2)*T/2
    S[4,4] = S[3,3]
    #rotate S to x-direction
    Q1 = qij_y(np.pi/2)
    R1 = R_sigma(Q1)
    S1 = np.dot(R1,np.dot(S,R1.T))
    return S1
Ejemplo n.º 41
0
def main():
    np.random.seed(50)
    name = "drug_net.txt"
    #name = "Internet_hyperbolic_map/AS_ARK200906_topology.txt"
    r1, t1 = study(name)
    r2, t2 = study(name, theta_init=t1)
    print t1[:5]
    print t2[:5]
    graphe = nx.read_weighted_edgelist("drug_net.txt")
    graphe = nx.convert_node_labels_to_integers(graphe)
    degree = graphe.degree()
    tdiff = math.pi - np.abs(math.pi - np.abs(t1 - t2 + np.mean(t2 - t1)))
    from numpy import cosh, sinh, cos, arccosh
    distances = arccosh(cosh(r1) * cosh(r2) - sinh(r1) * sinh(r2) * cos(tdiff))
    print distances
    degres = [1, 2, 3, 4, 5, 6]

    diffavg = [
        np.average([tdiff[node] for node in degree if degree[node] == deg])
        for deg in degres
    ]
    #plt.plot(range(len(tdiff)),tdiff,degree.values(),'o')
    plt.plot(np.arange(len(graphe)), distances, 'o')
    plt.show()
Ejemplo n.º 42
0
def eccentric2true(e, E):
    '''ELLPTICAL ORBITS
	From known eccentricity and eccentric anomaly, determine true anomaly
	Inputs:
		e (eccentricity)
		E (eccentric anomaly in radians)
	Outputs:
		theta (true anomaly in radians)
	'''
    if e == 0:  # circle (e=0)
        theta = "Undefined since it is a circle. Use argument of latitude (u) or true longitude (l) instead."
        print(theta)
    elif e < 1:  # ellipse
        print("Ellipse")
        theta = np.arccos((np.cos(E) - e) / (1 - e * np.cosh(E)))
    elif e > 1:  # hyperbola
        print("Hyperbola")
        F = E  # F is hyperbolic eccentric anomaly
        theta = np.arccosh((np.cosh(F) - e) / (1 - e * np.cosh(F)))
    else:  # parabola (e=1)
        theta = "For parabola, true anomaly (radians) cannot be found from eccentric anomaly (E). Use findea(v, r, gamma) instead."
        print(theta)

    return theta
Ejemplo n.º 43
0
def test_unary_intrin():
    test_funcs = [
        (tvm.tir.exp10, lambda x: np.power(10, x)),
        (tvm.tir.log2, lambda x: np.log2(x)),
        (tvm.tir.log10, lambda x: np.log10(x)),
        (tvm.tir.sinh, lambda x: np.sinh(x)),
        (tvm.tir.cosh, lambda x: np.cosh(x)),
        (tvm.tir.log1p, lambda x: np.log1p(x)),
        (tvm.tir.asin, lambda x: np.arcsin(x)),
        (tvm.tir.acos, lambda x: np.arccos(x)),
        (tvm.tir.atan, lambda x: np.arctan(x)),
        (tvm.tir.asinh, lambda x: np.arcsinh(x)),
        (tvm.tir.acosh, lambda x: np.arccosh(x)),
        (tvm.tir.atanh, lambda x: np.arctanh(x)),
    ]

    def run_test(tvm_intrin, np_func):
        m = te.var("m", )
        A = te.placeholder((m, ), name='A')
        B = te.compute((m, ), lambda *i: tvm_intrin(A(*i)), name='B')
        s = te.create_schedule(B.op)
        f = tvm.build(s, [A, B], "llvm")
        ctx = tvm.cpu(0)
        n = 10
        a = tvm.nd.array(
            np.random.uniform(0.1, 0.5, size=n).astype(A.dtype), ctx)
        b = tvm.nd.array( \
            np.random.uniform(size=n).astype(A.dtype), ctx)
        f(a, b)
        tvm.testing.assert_allclose(b.asnumpy(),
                                    np_func(a.asnumpy()),
                                    atol=1e-5,
                                    rtol=1e-5)

    for func in test_funcs:
        run_test(*func)
Ejemplo n.º 44
0
def get_weighting_potential(x, y, D, S, is_planar=True):
    """ Planar sensor:
        From Nuclear Instruments and Methods in Physics Research A 535 (2004)
        554-557, with correction from wbar = pi*w/2/D to wbar = pi*w/D with:

        x [um] is the offset from the middle of the electrode
        y [um] the position in the sensor
        D [um] the sensor thickness
        S [um] the eletrode width

        3D sensor:
        Weighting potential for two cylinders with:
        S [um] is the radius
        D [um] distance between columns
    """

    # Wheighting potential for one pixel
    if is_planar:
        xbar = np.pi * x / D
        ybar = np.pi * (y - D) / D
        wbar = np.pi * S / D
        return -1. / np.pi * (np.arctan(np.tan(ybar / 2) * np.tanh((xbar + wbar / 2.) / 2.)) -
                              np.arctan(np.tan(ybar / 2) * np.tanh((xbar - wbar / 2.) / 2.)))
    else:
        R = S
        D = D / 2.  # D is the total distance between the columns
        a = np.sqrt(D * D - R * R)
        Phi_w = 1. / (4 * np.arccosh(D / R)) * np.log(((x - a) ** 2 + y ** 2) / ((x + a) ** 2 + y ** 2)) + 0.5

        # Stability
        Phi_w = np.ma.masked_where(np.sqrt((x + D) * (x + D) + y * y) < R, Phi_w)
        Phi_w = np.ma.masked_where(np.sqrt((x - D) * (x - D) + y * y) < R, Phi_w)
        Phi_w = np.ma.masked_where(Phi_w < 0., Phi_w)
        Phi_w = np.ma.masked_where(Phi_w > 1., Phi_w)

        return Phi_w
Ejemplo n.º 45
0
def age_of_universe(z):
    """
    age_of_universe(): returns the age of the Universe (in Gyr) at
                       a redshift, z, for the given cosmology.
    USAGE: age = age_of_universe(z)
    NOTE: requires that a cosmology must first have been
          set using set_cosmology()
    """
    cosmology_set()
    a = 1.0/(1.0+z)
    if(WM >= 0.99999): # Einstein de Sitter Universe
        result = invH0*2.0*np.sqrt(a)/(3.0*h)
    else:
        if(WV <= 0.0): # Open Universe
            zplus1 = 1.0/a
            result1 = (WM/(2.0*h*np.power(1-WM,1.5)))
            result2 = 2.0*np.sqrt(1.0-WM)*np.sqrt(WM*(zplus1-1.0)+1.0)
            result3 = np.arccosh((WM*(zplus1-1.0)-WM+2.0)/(WM*zplus1))
            result = invH0*result1*(result2/result3)
        else: # Flat Universe with non-zero Cosmological Constant
            result1 = (2.0/(3.0*h*np.sqrt(1.0-WM)))
            result2 = np.arcsinh(np.sqrt((1.0/WM-1.0)*a)*a)
            result = invH0*result1*result2
    return result
Ejemplo n.º 46
0
def np_sample_gauss_pd(shape, oversample=5, radius=0.85, sigma=1.0):
    # rejection sample in Poincaré half-plane
    d = shape[1]
    n_samples = np.prod(shape) * oversample
    phi = np.random.rand(n_samples) * 2 * np.pi
    p = np.random.rand(n_samples)
    r = np.arccosh(1 + p *
                   (np.cosh(radius - 1e-5) - 1))  # support (-3sigma, 3sigma)
    #unif_samples = np.stack([np.sinh(r)*np.cos(phi), np.sinh(r)*np.sin(phi)],axis=1)
    unif_samples = np.stack([r * np.cos(phi), r * np.sin(phi)], axis=1)

    # zero mean, unit sigma in disk
    mean = np.array([[0.0, 0.0]])
    p_samples = np_gauss_prob_pd(unif_samples, mean, sigma)
    # accept in proportion to highest
    max_value = np.max(p_samples)
    accepted = np.random.rand(n_samples) < (p_samples / max_value)
    # select the samples - make sure it's enough
    u = unif_samples[:, 0][accepted]
    v = unif_samples[:, 1][accepted]
    # transform samples using cayley mapping z = (i-w)/(i+w)
    disk_samples = np.stack([u, v], axis=1)
    idx = (np.prod(shape) / 2).astype(np.int32)
    return np.reshape(disk_samples[:idx], shape)
Ejemplo n.º 47
0
def vec_math_ops(ip, port):
    # Connect to h2o
    h2o.init(ip, port)

    sin_cos_tan_atan_sinh_cosh_tanh_asinh_data = [
        [random.uniform(-10, 10) for r in range(10)] for c in range(10)
    ]
    asin_acos_atanh_data = [[random.uniform(-1, 1) for r in range(10)]
                            for c in range(10)]
    acosh_data = [[random.uniform(1, 10) for r in range(10)]
                  for c in range(10)]
    abs_data = [[random.uniform(-100000, 0) for r in range(10)]
                for c in range(10)]

    h2o_data1 = h2o.H2OFrame(
        python_obj=sin_cos_tan_atan_sinh_cosh_tanh_asinh_data)
    h2o_data2 = h2o.H2OFrame(python_obj=asin_acos_atanh_data)
    h2o_data3 = h2o.H2OFrame(python_obj=acosh_data)
    h2o_data4 = h2o.H2OFrame(python_obj=abs_data)

    np_data1 = np.array(sin_cos_tan_atan_sinh_cosh_tanh_asinh_data)
    np_data2 = np.array(asin_acos_atanh_data)
    np_data3 = np.array(acosh_data)
    np_data4 = np.array(abs_data)

    row, col = h2o_data1.dim()

    c = random.randint(0, col - 1)
    h2o.np_comparison_check(h2o.cos(h2o_data1[c]), np.cos(np_data1[:, c]), 10)
    h2o.np_comparison_check(h2o.sin(h2o_data1[c]), np.sin(np_data1[:, c]), 10)
    h2o.np_comparison_check(h2o.tan(h2o_data1[c]), np.tan(np_data1[:, c]), 10)
    h2o.np_comparison_check(h2o.acos(h2o_data2[c]), np.arccos(np_data2[:, c]),
                            10)
    h2o.np_comparison_check(h2o.asin(h2o_data2[c]), np.arcsin(np_data2[:, c]),
                            10)
    h2o.np_comparison_check(h2o.atan(h2o_data1[c]), np.arctan(np_data1[:, c]),
                            10)
    h2o.np_comparison_check(h2o.cosh(h2o_data1[c]), np.cosh(np_data1[:, c]),
                            10)
    h2o.np_comparison_check(h2o.sinh(h2o_data1[c]), np.sinh(np_data1[:, c]),
                            10)
    h2o.np_comparison_check(h2o.tanh(h2o_data1[c]), np.tanh(np_data1[:, c]),
                            10)
    h2o.np_comparison_check(h2o.acosh(h2o_data3[c]),
                            np.arccosh(np_data3[:, c]), 10)
    h2o.np_comparison_check(h2o.asinh(h2o_data1[c]),
                            np.arcsinh(np_data1[:, c]), 10)
    h2o.np_comparison_check(h2o.atanh(h2o_data2[c]),
                            np.arctanh(np_data2[:, c]), 10)
    h2o.np_comparison_check(h2o.abs(h2o_data4[c]), np.fabs(np_data4[:, c]), 10)
    h2o.np_comparison_check(h2o.sign(h2o_data2[c]), np.sign(np_data2[:, c]),
                            10)
    h2o.np_comparison_check(h2o.sqrt(h2o_data3[c]), np.sqrt(np_data3[:, c]),
                            10)
    h2o.np_comparison_check(h2o.trunc(h2o_data3[c]), np.trunc(np_data3[:, c]),
                            10)
    h2o.np_comparison_check(h2o.ceil(h2o_data3[c]), np.ceil(np_data3[:, c]),
                            10)
    h2o.np_comparison_check(h2o.floor(h2o_data3[c]), np.floor(np_data3[:, c]),
                            10)
    h2o.np_comparison_check(h2o.log(h2o_data3[c]), np.log(np_data3[:, c]), 10)
    h2o.np_comparison_check(h2o.log10(h2o_data3[c]), np.log10(np_data3[:, c]),
                            10)
    h2o.np_comparison_check(h2o.log1p(h2o_data3[c]), np.log1p(np_data3[:, c]),
                            10)
    h2o.np_comparison_check(h2o.log2(h2o_data3[c]), np.log2(np_data3[:, c]),
                            10)
    h2o.np_comparison_check(h2o.exp(h2o_data3[c]), np.exp(np_data3[:, c]), 10)
    h2o.np_comparison_check(h2o.expm1(h2o_data3[c]), np.expm1(np_data3[:, c]),
                            10)
    h2o_val = h2o.gamma(h2o_data3[c])[5, 0]
    num_val = math.gamma(h2o_data3[5, c])
    assert abs(h2o_val - num_val) <  max(abs(h2o_val), abs(num_val)) * 1e-6, \
        "check unsuccessful! h2o computed {0} and math computed {1}. expected equal gamma values between h2o and" \
        "math".format(h2o_val,num_val)
    h2o_val = h2o.lgamma(h2o_data3[c])[5, 0]
    num_val = math.lgamma(h2o_data3[5, c])
    assert abs(h2o_val - num_val) <  max(abs(h2o_val), abs(num_val)) * 1e-6, \
        "check unsuccessful! h2o computed {0} and math computed {1}. expected equal lgamma values between h2o and " \
        "math".format(h2o_val,num_val)
    h2o_val = h2o.digamma(h2o_data3[c])[5, 0]
    num_val = scipy.special.polygamma(0, h2o_data3[5, c])
    assert abs(h2o_val - num_val) <  max(abs(h2o_val), abs(num_val)) * 1e-6, \
        "check unsuccessful! h2o computed {0} and math computed {1}. expected equal digamma values between h2o and " \
        "math".format(h2o_val,num_val)
    h2o_val = h2o.trigamma(h2o_data3)[5, c]
    num_val = scipy.special.polygamma(1, h2o_data3[5, c])
    assert abs(h2o_val - num_val) <  max(abs(h2o_val), abs(num_val)) * 1e-6, \
        "check unsuccessful! h2o computed {0} and math computed {1}. expected equal trigamma values between h2o and " \
        "math".format(h2o_val,num_val)
Ejemplo n.º 48
0
 def func(x):
     import numpy as np
     return float(np.arccosh(x))
#cp_lines  = sns.cubehelix_palette(5, start=0, rot=-0.65)[::-1]

cp_points = sns.color_palette("colorblind", 5)
cp_lines = sns.color_palette("deep", 5, desat=0.9)

T_ren = T_list
tpf_corr = np.zeros([5, 32])
for (i, N) in enumerate(N_list):
    plt.plot(T_list_th,
             tpf_theory(T_list_th, k=int(N**0.8 / 5), N=N),
             color=cp_lines[i],
             alpha=0.5,
             linewidth=3.5,
             label='$N=%d$' % N)

    plt.plot(T_ren,
             tpf_plot[i],
             linestyle=' ',
             color=cp_points[i],
             marker=marker_list[i],
             markersize=14)

    tpf_corr[i] = tpf_theory(T_ren, k=int(N**0.8 / 5), N=N)
    T_ren = 2.0 / np.arccosh(np.exp(2.0 / T_ren))

plt.xlabel('$T$', fontsize=label_size)
plt.ylabel('$G_N(j)$', fontsize=label_size)
plt.legend(loc='upper right', fontsize=48)

plt.subplots_adjust(left=0.12, right=0.95, top=0.96, bottom=0.16)
plt.savefig('tpf1D.pdf')  # bbox_inches='tight')
Ejemplo n.º 50
0
def _protected_arccosh(x1):
    """Closure of division (x1/x2) for zero denominator."""
    with np.errstate(divide='ignore', invalid='ignore'):
        return np.where(x1 >= 1, np.arccosh(x1), 0)
Ejemplo n.º 51
0
 def compute_order(ap, aa, wpn):
     order = np.arccosh(
         ChebyshevIIApprox.compute_epsilon(ap) /
         ChebyshevIIApprox.compute_epsilon(aa)) / np.arccosh(1 / wpn)
     rounded_order = round(order)
     return rounded_order if rounded_order >= order else rounded_order + 1
Ejemplo n.º 52
0
import numpy as np
import matplotlib.pyplot as plt

N = 4
for epsilon in np.arange(0.35, 0.6, 0.05):
    Omega1 = np.arange(0, 1, 0.01)
    H1 = 1 / np.sqrt(1 + epsilon**2 * np.cos(N * np.arccos(Omega1))**2)
    Omega2 = np.arange(1, 3.01, 0.01)
    H2 = 1 / np.sqrt(1 + epsilon**2 * np.cosh(N * np.arccosh(Omega2))**2)
    H = np.concatenate((H1, H2))
    Omega = np.concatenate((Omega1, Omega2))
    plt.plot(Omega, H, label='$\epsilon$ = ' + str(round(epsilon, 2)))
plt.legend()
plt.savefig("varyingepsilon.eps")
plt.show()
Ejemplo n.º 53
0
def pdist(X):
    inner_prods = -np.outer(X[:, 0], X[:, 0]) + X[:, 1:] @ X[:, 1:].T
    dists = np.arccosh(np.clip(-inner_prods, a_min=1.0, a_max=None))

    return dists
Ejemplo n.º 54
0
def chebwin(M, at, sym=True):
    """Return a Dolph-Chebyshev window.

    Parameters
    ----------
    M : int
        Number of points in the output window. If zero or less, an empty
        array is returned.
    at : float
        Attenuation (in dB).
    sym : bool, optional
        When True, generates a symmetric window, for use in filter design.
        When False, generates a periodic window, for use in spectral analysis.

    Returns
    -------
    w : ndarray
        The window, with the maximum value always normalized to 1

    Examples
    --------
    Plot the window and its frequency response:

    >>> from scipy import signal
    >>> from scipy.fftpack import fft, fftshift
    >>> import matplotlib.pyplot as plt

    >>> window = signal.chebwin(51, at=100)
    >>> plt.plot(window)
    >>> plt.title("Dolph-Chebyshev window (100 dB)")
    >>> plt.ylabel("Amplitude")
    >>> plt.xlabel("Sample")

    >>> plt.figure()
    >>> A = fft(window, 2048) / (len(window)/2.0)
    >>> freq = np.linspace(-0.5, 0.5, len(A))
    >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
    >>> plt.plot(freq, response)
    >>> plt.axis([-0.5, 0.5, -120, 0])
    >>> plt.title("Frequency response of the Dolph-Chebyshev window (100 dB)")
    >>> plt.ylabel("Normalized magnitude [dB]")
    >>> plt.xlabel("Normalized frequency [cycles per sample]")

    """
    if M < 1:
        return np.array([])
    if M == 1:
        return np.ones(1, 'd')

    odd = M % 2
    if not sym and not odd:
        M = M + 1

    # compute the parameter beta
    order = M - 1.0
    beta = np.cosh(1.0 / order * np.arccosh(10 ** (np.abs(at) / 20.)))
    k = np.r_[0:M] * 1.0
    x = beta * np.cos(np.pi * k / M)
    # Find the window's DFT coefficients
    # Use analytic definition of Chebyshev polynomial instead of expansion
    # from scipy.special. Using the expansion in scipy.special leads to errors.
    p = np.zeros(x.shape)
    p[x > 1] = np.cosh(order * np.arccosh(x[x > 1]))
    p[x < -1] = (1 - 2 * (order % 2)) * np.cosh(order * np.arccosh(-x[x < -1]))
    p[np.abs(x) <= 1] = np.cos(order * np.arccos(x[np.abs(x) <= 1]))

    # Appropriate IDFT and filling up
    # depending on even/odd M
    if M % 2:
        w = np.real(fft(p))
        n = (M + 1) // 2
        w = w[:n] / w[0]
        w = np.concatenate((w[n - 1:0:-1], w))
    else:
        p = p * np.exp(1.j * np.pi / M * np.r_[0:M])
        w = np.real(fft(p))
        n = M // 2 + 1
        w = w / w[1]
        w = np.concatenate((w[n - 1:0:-1], w[1:n]))
    if not sym and not odd:
        w = w[:-1]
    return w
Ejemplo n.º 55
0
def test_ufunc_arccosh_u(A: dace.uint32[10]):
    return np.arccosh(A)
Ejemplo n.º 56
0
def test_ufunc_arccosh_f(A: dace.float32[10]):
    return np.arccosh(A)
Ejemplo n.º 57
0
def test_ufunc_arccosh_c(A: dace.complex64[10]):
    return np.arccosh(A)
Ejemplo n.º 58
0
class Acosh(Activation):
    op = 'Acosh'
    version = 'opset4'
    operation = staticmethod(lambda x: np.arccosh(x))
Ejemplo n.º 59
0
def vec_math_ops():
    seed0 = random.random()
    random.seed(seed0)
    print("Using seed %r" % seed0)

    sin_cos_tan_atan_sinh_cosh_tanh_asinh_data = [
        [random.uniform(-10, 10) for r in range(10)] for c in range(10)
    ]
    asin_acos_atanh_data = [[random.uniform(-1, 1) for r in range(10)]
                            for c in range(10)]
    acosh_data = [[random.uniform(1, 10) for r in range(10)]
                  for c in range(10)]
    abs_data = [[random.uniform(-100000, 0) for r in range(10)]
                for c in range(10)]
    zero_one_data = [random.randint(0, 1) for c in range(10)]
    zero_one_data = [zero_one_data, zero_one_data]

    h2o_data1 = h2o.H2OFrame(sin_cos_tan_atan_sinh_cosh_tanh_asinh_data)
    h2o_data2 = h2o.H2OFrame(asin_acos_atanh_data)
    h2o_data3 = h2o.H2OFrame(acosh_data)
    h2o_data4 = h2o.H2OFrame(abs_data)
    h2o_data5 = h2o.H2OFrame(zero_one_data)

    np_data1 = np.array(sin_cos_tan_atan_sinh_cosh_tanh_asinh_data)
    np_data2 = np.array(asin_acos_atanh_data)
    np_data3 = np.array(acosh_data)
    np_data4 = np.array(abs_data)
    np_data5 = np.array(zero_one_data)

    row, col = h2o_data1.dim

    c = random.randint(0, col - 1)
    for d in range(1, 6):
        h2o_signif = h2o_data5[c].signif(digits=d)
        h2o_round = h2o_data5[c].round(digits=d + 4)
        s = h2o_signif[0]
        r = h2o_round[0]
        assert (s == r).all(
        ), "Expected these to be equal, but signif: {0}, round: {1}".format(
            s, r)

    test1 = (h2o_data1 == h2o_data1).all()
    test2 = (h2o_data1 == h2o_data2).all()
    assert test1 is True and test2 is False, "API change detected, the tests below will be ineffective"

    print("Testing trigonometric functions")
    assert ((h2o_data1.cos() - h2o.H2OFrame(np.cos(np_data1))).abs() <
            1e-12).all()
    assert ((h2o_data1.sin() - h2o.H2OFrame(np.sin(np_data1))).abs() <
            1e-12).all()
    assert ((h2o_data1.tan() - h2o.H2OFrame(np.tan(np_data1))).abs() < 1e-12 *
            (h2o_data1.tan().abs() + 1)).all()
    print("Testing inverse trigonometric functions")
    assert ((h2o_data2.acos() - h2o.H2OFrame(np.arccos(np_data2))).abs() <
            1e-12).all()
    assert ((h2o_data2.asin() - h2o.H2OFrame(np.arcsin(np_data2))).abs() <
            1e-12).all()
    assert ((h2o_data1.atan() - h2o.H2OFrame(np.arctan(np_data1))).abs() <
            1e-12 * (h2o_data1.tan().abs() + 1)).all()
    print("Testing hyperbolic trigonometric functions")
    assert ((h2o_data1.cosh() - h2o.H2OFrame(np.cosh(np_data1))).abs() <
            1e-12 * h2o_data1.cosh().abs()).all()
    assert ((h2o_data1.sinh() - h2o.H2OFrame(np.sinh(np_data1))).abs() <
            1e-12 * h2o_data1.sinh().abs()).all()
    assert ((h2o_data1.tanh() - h2o.H2OFrame(np.tanh(np_data1))).abs() <
            1e-12 * h2o_data1.tanh().abs()).all()
    assert ((h2o_data3.acosh() - h2o.H2OFrame(np.arccosh(np_data3))).abs() <
            1e-12 * h2o_data3.acosh().abs()).all()
    assert ((h2o_data1.asinh() - h2o.H2OFrame(np.arcsinh(np_data1))).abs() <
            1e-12 * h2o_data1.asinh().abs()).all()
    assert ((h2o_data2.atanh() - h2o.H2OFrame(np.arctanh(np_data2))).abs() <
            1e-12 * h2o_data2.atanh().abs()).all()

    print("Testing gamma functions")
    x_val = h2o_data3[5, c]
    assert type(x_val) is float
    h2o_val = h2o_data3[c].gamma()[5, :].flatten()
    num_val = math.gamma(x_val)
    assert abs(h2o_val - num_val) < max(abs(h2o_val), abs(num_val)) * 1e-6, \
        "h2o computed gamma({0}) = {1} while math computed gamma({0}) = {2}".format(x_val, h2o_val, num_val)

    h2o_val = h2o_data3[c].lgamma()[5, :].flatten()
    num_val = math.lgamma(x_val)
    assert abs(h2o_val - num_val) < max(abs(h2o_val), abs(num_val)) * 1e-6, \
        "h2o computed lgamma({0}) = {1} while math computed lgamma({0}) = {2}".format(x_val, h2o_val, num_val)

    h2o_val = h2o_data3[c].digamma()[5, :].flatten()
    num_val = scipy.special.polygamma(0, x_val)
    assert abs(h2o_val - num_val) < max(abs(h2o_val), abs(num_val)) * 1e-6, \
        "h2o computed digamma({0}) = {1} while scipy computed digamma({0}) = {2}".format(x_val, h2o_val, num_val)

    h2o_val = h2o_data3[c].trigamma()[5, :].flatten()
    num_val = scipy.special.polygamma(1, x_val)
    assert abs(h2o_val - num_val) < max(abs(h2o_val), abs(num_val)) * 1e-6, \
        "h2o computed trigamma({0}) = {1} while scipy computed trigamma({0}) = {2}".format(x_val, h2o_val, num_val)
Ejemplo n.º 60
0
def np_arccosh(array):
    return np.arccosh(array)