Python numpy.cosh() Examples

The following are 30 code examples for showing how to use numpy.cosh(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module numpy , or try the search function .

Example 1
Project: EXOSIMS   Author: dsavransky   File: keplerSTM.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def psi2c2c3(self, psi0):

        c2 = np.zeros(len(psi0))
        c3 = np.zeros(len(psi0))

        psi12 = np.sqrt(np.abs(psi0))
        pos = psi0 >= 0
        neg = psi0 < 0
        if np.any(pos):
            c2[pos] = (1 - np.cos(psi12[pos]))/psi0[pos]
            c3[pos] = (psi12[pos] - np.sin(psi12[pos]))/psi12[pos]**3.
        if any(neg):
            c2[neg] = (1 - np.cosh(psi12[neg]))/psi0[neg]
            c3[neg] = (np.sinh(psi12[neg]) - psi12[neg])/psi12[neg]**3.

        tmp = c2+c3 == 0
        if any(tmp):
            c2[tmp] = 1./2.
            c3[tmp] = 1./6.

        return c2,c3 
Example 2
Project: solar-system   Author: lukekulik   File: uvf.py    License: MIT License 6 votes vote down vote up
def c2c3(psi):  # Stumpff functions definitions

    c2, c3 = 0, 0

    if np.any(psi > 1e-6):
        c2 = (1 - np.cos(np.sqrt(psi))) / psi
        c3 = (np.sqrt(psi) - np.sin(np.sqrt(psi))) / np.sqrt(psi ** 3)

    if np.any(psi < -1e-6):
        c2 = (1 - np.cosh(np.sqrt(-psi))) / psi
        c3 = (np.sinh(np.sqrt(-psi)) - np.sqrt(-psi)) / np.sqrt(-psi ** 3)

    if np.any(abs(psi) <= 1e-6):
        c2 = 0.5
        c3 = 1. / 6.

    return c2, c3 
Example 3
Project: larq   Author: larq   File: quantizers_test.py    License: Apache License 2.0 6 votes vote down vote up
def test_swish_grad(self):
        def swish_grad(x, beta):
            return (
                beta * (2 - beta * x * np.tanh(beta * x / 2)) / (1 + np.cosh(beta * x))
            )

        x = testing_utils.generate_real_values_with_zeros(shape=(8, 3, 3, 16))
        tf_x = tf.Variable(x)
        with tf.GradientTape() as tape:
            activation = lq.quantizers.SwishSign()(tf_x)
        grad = tape.gradient(activation, tf_x)
        np.testing.assert_allclose(grad.numpy(), swish_grad(x, beta=5.0))

        with tf.GradientTape() as tape:
            activation = lq.quantizers.SwishSign(beta=10.0)(tf_x)
        grad = tape.gradient(activation, tf_x)
        np.testing.assert_allclose(grad.numpy(), swish_grad(x, beta=10.0)) 
Example 4
Project: ocelot   Author: ocelot-collab   File: rk_py.py    License: GNU General Public License v3.0 6 votes vote down vote up
def fields(x,y,z, kx, ky, kz, B0):
    k1 =  -B0*kx/ky
    k2 = -B0*kz/ky
    kx_x = kx*x
    ky_y = ky*y
    kz_z = kz*z
    cosx = np.cos(kx_x)
    sinhy = np.sinh(ky_y)
    cosz = np.cos(kz_z)
    Bx = k1*np.sin(kx_x)*sinhy*cosz #// here kx is only real
    By = B0*cosx*np.cosh(ky_y)*cosz
    Bz = k2*cosx*sinhy*np.sin(kz_z)
    #Bx = ne.evaluate("k1*sin(kx*x)*sinhy*cosz")
    #By = ne.evaluate("B0*cosx*cosh(ky*y)*cosz")
    #Bz = ne.evaluate("k2*cosx*sinhy*sin(kz*z)")
    return Bx, By, Bz 
Example 5
Project: strawberryfields   Author: XanaduAI   File: test_decompositions_integration.py    License: Apache License 2.0 6 votes vote down vote up
def test_CXgate_decomp_equal(self, setup_eng, s, tol):
        """Tests that the CXgate gives the same transformation as its decomposition."""
        eng, prog = setup_eng(2)

        r = np.arcsinh(-s / 2)
        y = -1 / np.cosh(r)
        x = -np.tanh(r)
        theta = np.arctan2(y, x) / 2

        with prog.context as q:
            ops.CXgate(s) | q
            # run decomposition with reversed arguments
            ops.BSgate(-(np.pi / 2 + theta), 0) | q
            ops.Sgate(r, np.pi) | q[0]
            ops.Sgate(r, 0) | q[1]
            ops.BSgate(-theta, 0) | q

        eng.run(prog)
        assert np.all(eng.backend.is_vacuum(tol)) 
Example 6
Project: strawberryfields   Author: XanaduAI   File: test_circuitspecs_X8.py    License: Apache License 2.0 6 votes vote down vote up
def TMS(r, phi):
    """Two-mode squeezing.

    Args:
        r (float): squeezing magnitude
        phi (float): rotation parameter

    Returns:
        array: symplectic transformation matrix
    """
    cp = np.cos(phi)
    sp = np.sin(phi)
    ch = np.cosh(r)
    sh = np.sinh(r)

    S = np.array(
        [
            [ch, cp * sh, 0, sp * sh],
            [cp * sh, ch, sp * sh, 0],
            [0, sp * sh, ch, -cp * sh],
            [sp * sh, 0, -cp * sh, ch],
        ]
    )

    return S 
Example 7
Project: strawberryfields   Author: XanaduAI   File: test_ops_decompositions.py    License: Apache License 2.0 6 votes vote down vote up
def _squeezing(r, phi, mode, num_modes):
    """Squeezing in the phase space.

    Args:
        r (float): squeezing magnitude
        phi (float): rotation parameter
        mode (int): mode it is applied to
        num_modes (int): total number of modes in the system

    Returns:
        array: symplectic transformation matrix
    """
    cp = np.cos(phi)
    sp = np.sin(phi)
    ch = np.cosh(r)
    sh = np.sinh(r)

    S = np.array([[ch - cp * sh, -sp * sh], [-sp * sh, ch + cp * sh]])

    return expand(S, mode, num_modes) 
Example 8
Project: strawberryfields   Author: XanaduAI   File: test_circuitspecs_X12.py    License: Apache License 2.0 6 votes vote down vote up
def TMS(r, phi):
    """Two-mode squeezing.

    Args:
        r (float): squeezing magnitude
        phi (float): rotation parameter

    Returns:
        array: symplectic transformation matrix
    """
    cp = np.cos(phi)
    sp = np.sin(phi)
    ch = np.cosh(r)
    sh = np.sinh(r)

    S = np.array(
        [
            [ch, cp * sh, 0, sp * sh],
            [cp * sh, ch, sp * sh, 0],
            [0, sp * sh, ch, -cp * sh],
            [sp * sh, 0, -cp * sh, ch],
        ]
    )

    return S 
Example 9
Project: strawberryfields   Author: XanaduAI   File: test_utils.py    License: Apache License 2.0 6 votes vote down vote up
def test_squeezed_state_gaussian(self, r, phi, hbar, tol):
        """test squeezed state returns correct means and covariance"""
        means, cov = utils.squeezed_state(r, phi, basis="gaussian", hbar=hbar)

        cov_expected = (hbar / 2) * np.array(
            [
                [
                    np.cosh(2 * r) - np.cos(phi) * np.sinh(2 * r),
                    -2 * np.cosh(r) * np.sin(phi) * np.sinh(r),
                ],
                [
                    -2 * np.cosh(r) * np.sin(phi) * np.sinh(r),
                    np.cosh(2 * r) + np.cos(phi) * np.sinh(2 * r),
                ],
            ]
        )

        assert np.all(means == np.zeros([2]))
        assert np.allclose(cov, cov_expected, atol=tol, rtol=0) 
Example 10
Project: strawberryfields   Author: XanaduAI   File: test_utils.py    License: Apache License 2.0 6 votes vote down vote up
def test_displaced_squeezed_state_gaussian(self, r_d, phi_d, r_s, phi_s, hbar, tol):
        """test displaced squeezed state returns correct means and covariance"""
        means, cov = utils.displaced_squeezed_state(r_d, phi_d, r_s, phi_s, basis="gaussian", hbar=hbar)

        a = r_d * np.exp(1j * phi_d)
        means_expected = np.array([[a.real, a.imag]]) * np.sqrt(2 * hbar)
        cov_expected = (hbar / 2) * np.array(
            [
                [
                    np.cosh(2 * r_s) - np.cos(phi_s) * np.sinh(2 * r_s),
                    -2 * np.cosh(r_s) * np.sin(phi_s) * np.sinh(r_s),
                ],
                [
                    -2 * np.cosh(r_s) * np.sin(phi_s) * np.sinh(r_s),
                    np.cosh(2 * r_s) + np.cos(phi_s) * np.sinh(2 * r_s),
                ],
            ]
        )

        assert np.allclose(means, means_expected, atol=tol, rtol=0)
        assert np.allclose(cov, cov_expected, atol=tol, rtol=0) 
Example 11
Project: strawberryfields   Author: XanaduAI   File: test_utils.py    License: Apache License 2.0 6 votes vote down vote up
def test_displaced_squeezed_state_fock(self, r_d, phi_d, r_s, phi_s, hbar, cutoff, tol):
        """test displaced squeezed state returns correct Fock basis state vector"""
        state = utils.displaced_squeezed_state(r_d, phi_d, r_s, phi_s, basis="fock", fock_dim=cutoff, hbar=hbar)
        a = r_d * np.exp(1j * phi_d)

        if r_s == 0:
            pytest.skip("test only non-zero squeezing")

        n = np.arange(cutoff)
        gamma = a * np.cosh(r_s) + np.conj(a) * np.exp(1j * phi_s) * np.sinh(r_s)
        coeff = np.diag(
            (0.5 * np.exp(1j * phi_s) * np.tanh(r_s)) ** (n / 2) / np.sqrt(fac(n) * np.cosh(r_s))
        )

        expected = H(gamma / np.sqrt(np.exp(1j * phi_s) * np.sinh(2 * r_s)), coeff)
        expected *= np.exp(
            -0.5 * np.abs(a) ** 2 - 0.5 * np.conj(a) ** 2 * np.exp(1j * phi_s) * np.tanh(r_s)
        )

        assert np.allclose(state, expected, atol=tol, rtol=0) 
Example 12
Project: strawberryfields   Author: XanaduAI   File: test_states_wigner.py    License: Apache License 2.0 6 votes vote down vote up
def test_squeezed_coherent(setup_backend, hbar, tol):
    """Test Wigner function for a squeezed coherent state
    matches the analytic result"""
    backend = setup_backend(1)
    backend.prepare_coherent_state(np.abs(A), np.angle(A), 0)
    backend.squeeze(R, PHI, 0)

    state = backend.state()
    W = state.wigner(0, XVEC, XVEC)
    rot = rotm(PHI / 2)

    # exact wigner function
    alpha = A * np.cosh(R) - np.conjugate(A) * np.exp(1j * PHI) * np.sinh(R)
    mu = np.array([alpha.real, alpha.imag]) * np.sqrt(2 * hbar)
    cov = np.diag([np.exp(-2 * R), np.exp(2 * R)])
    cov = np.dot(rot, np.dot(cov, rot.T)) * hbar / 2.0
    Wexact = wigner(GRID, mu, cov)

    assert np.allclose(W, Wexact, atol=0.01, rtol=0) 
Example 13
Project: strawberryfields   Author: XanaduAI   File: test_twomode_squeezing_operation.py    License: Apache License 2.0 6 votes vote down vote up
def test_two_mode_squeezing(self, setup_backend, r, p, cutoff, pure, tol):
        r""" Test two-mode squeezing on vacuum-state for both pure states and
        mixed states with the amplitude given by
	        :math:`\delta_{kl} \frac{e^{in\phi} \tanh^n{r}}{\cosh{r}}`
        """

        backend = setup_backend(2)
        backend.two_mode_squeeze(r, p, 0, 1)

        state = backend.state()

        if pure:
            for k in it.product(range(cutoff), repeat=2):
                tmsv = get_amplitude(k, r, p)
                assert np.allclose(state.data[k], tmsv, atol=tol, rtol=0)
        else:
            for k in it.product(range(cutoff), repeat=2):
                for l in it.product(range(cutoff), repeat=2):
                    t = (k[0], l[0], k[1], l[1])
                    tmsv2 = get_amplitude(k, r, p) * np.conj(get_amplitude(l, r, p))

                    assert np.allclose(state.data[t], tmsv2, atol=tol, rtol=0) 
Example 14
Project: strawberryfields   Author: XanaduAI   File: test_states.py    License: Apache License 2.0 6 votes vote down vote up
def test_squeezed_coherent(self, setup_backend, hbar, batch_size, tol):
        """Test squeezed coherent state has correct mean and variance"""
        # quadrature rotation angle
        backend = setup_backend(1)
        qphi = 0.78

        backend.prepare_displaced_squeezed_state(np.abs(a), np.angle(a), r, phi, 0)

        state = backend.state()
        res = np.array(state.quad_expectation(0, phi=qphi)).T

        xphi_mean = (a.real * np.cos(qphi) + a.imag * np.sin(qphi)) * np.sqrt(2 * hbar)
        xphi_var = (np.cosh(2 * r) - np.cos(phi - 2 * qphi) * np.sinh(2 * r)) * hbar / 2
        res_exact = np.array([xphi_mean, xphi_var])

        if batch_size is not None:
            res_exact = np.tile(res_exact, batch_size)

        assert np.allclose(res.flatten(), res_exact.flatten(), atol=tol, rtol=0) 
Example 15
Project: Finance-Python   Author: alpha-miner   File: testAccumulatorsArithmetic.py    License: MIT License 6 votes vote down vote up
def testAcoshFunction(self):
        ma5 = MovingAverage(5, 'close')
        holder = Acosh(ma5)

        sampleClose = np.cosh(self.sampleClose)

        for i, close in enumerate(sampleClose):
            data = {'close': close}
            ma5.push(data)
            holder.push(data)

            expected = math.acosh(ma5.result())
            calculated = holder.result()
            self.assertAlmostEqual(calculated, expected, 12, "at index {0:d}\n"
                                                             "expected:   {1:f}\n"
                                                             "calculated: {2:f}".format(i, expected, calculated)) 
Example 16
Project: Computable   Author: ktraunmueller   File: filter_design.py    License: MIT License 6 votes vote down vote up
def cheb1ap(N, rp):
    """Return (z,p,k) zero, pole, gain for Nth order Chebyshev type I lowpass
    analog filter prototype with `rp` decibels of ripple in the passband.

    The filter's angular (e.g. rad/s) cutoff frequency is normalized to 1,
    defined as the point at which the gain first drops below -`rp`.

    """
    z = numpy.array([])
    eps = numpy.sqrt(10 ** (0.1 * rp) - 1.0)
    n = numpy.arange(1, N + 1)
    mu = 1.0 / N * numpy.log((1.0 + numpy.sqrt(1 + eps * eps)) / eps)
    theta = pi / 2.0 * (2 * n - 1.0) / N
    p = (-numpy.sinh(mu) * numpy.sin(theta) +
         1j * numpy.cosh(mu) * numpy.cos(theta))
    k = numpy.prod(-p, axis=0).real
    if N % 2 == 0:
        k = k / sqrt((1 + eps * eps))
    return z, p, k 
Example 17
Project: Computable   Author: ktraunmueller   File: filter_design.py    License: MIT License 6 votes vote down vote up
def cheb2ap(N, rs):
    """Return (z,p,k) zero, pole, gain for Nth order Chebyshev type II lowpass
    analog filter prototype with `rs` decibels of ripple in the stopband.

    The filter's angular (e.g. rad/s) cutoff frequency is normalized to 1,
    defined as the point at which the gain first reaches -`rs`.

    """
    de = 1.0 / sqrt(10 ** (0.1 * rs) - 1)
    mu = arcsinh(1.0 / de) / N

    if N % 2:
        n = numpy.concatenate((numpy.arange(1, N - 1, 2),
                               numpy.arange(N + 2, 2 * N, 2)))
    else:
        n = numpy.arange(1, 2 * N, 2)

    z = conjugate(1j / cos(n * pi / (2.0 * N)))
    p = exp(1j * (pi * numpy.arange(1, 2 * N, 2) / (2.0 * N) + pi / 2.0))
    p = sinh(mu) * p.real + 1j * cosh(mu) * p.imag
    p = 1.0 / p
    k = (numpy.prod(-p, axis=0) / numpy.prod(-z, axis=0)).real
    return z, p, k 
Example 18
Project: tangent   Author: google   File: functions.py    License: Apache License 2.0 5 votes vote down vote up
def numpy_cosh(a):
  return np.cosh(a) 
Example 19
Project: tangent   Author: google   File: functions.py    License: Apache License 2.0 5 votes vote down vote up
def tfe_cosh(t):
  return tf.cosh(t) 
Example 20
Project: tangent   Author: google   File: grads.py    License: Apache License 2.0 5 votes vote down vote up
def cosh(y, x):
  d[x] = d[y] * numpy.sinh(x) 
Example 21
Project: tangent   Author: google   File: grads.py    License: Apache License 2.0 5 votes vote down vote up
def sinh(y, x):
  d[x] = d[y] * numpy.cosh(x) 
Example 22
Project: tangent   Author: google   File: tangents.py    License: Apache License 2.0 5 votes vote down vote up
def tsinh(z, x):
  d[z] = d[x] * numpy.cosh(x) 
Example 23
Project: recruit   Author: Frank-qlu   File: test_old_ma.py    License: Apache License 2.0 5 votes vote down vote up
def test_testUfuncs1(self):
        # Test various functions such as sin, cos.
        (x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d
        assert_(eq(np.cos(x), cos(xm)))
        assert_(eq(np.cosh(x), cosh(xm)))
        assert_(eq(np.sin(x), sin(xm)))
        assert_(eq(np.sinh(x), sinh(xm)))
        assert_(eq(np.tan(x), tan(xm)))
        assert_(eq(np.tanh(x), tanh(xm)))
        with np.errstate(divide='ignore', invalid='ignore'):
            assert_(eq(np.sqrt(abs(x)), sqrt(xm)))
            assert_(eq(np.log(abs(x)), log(xm)))
            assert_(eq(np.log10(abs(x)), log10(xm)))
        assert_(eq(np.exp(x), exp(xm)))
        assert_(eq(np.arcsin(z), arcsin(zm)))
        assert_(eq(np.arccos(z), arccos(zm)))
        assert_(eq(np.arctan(z), arctan(zm)))
        assert_(eq(np.arctan2(x, y), arctan2(xm, ym)))
        assert_(eq(np.absolute(x), absolute(xm)))
        assert_(eq(np.equal(x, y), equal(xm, ym)))
        assert_(eq(np.not_equal(x, y), not_equal(xm, ym)))
        assert_(eq(np.less(x, y), less(xm, ym)))
        assert_(eq(np.greater(x, y), greater(xm, ym)))
        assert_(eq(np.less_equal(x, y), less_equal(xm, ym)))
        assert_(eq(np.greater_equal(x, y), greater_equal(xm, ym)))
        assert_(eq(np.conjugate(x), conjugate(xm)))
        assert_(eq(np.concatenate((x, y)), concatenate((xm, ym))))
        assert_(eq(np.concatenate((x, y)), concatenate((x, y))))
        assert_(eq(np.concatenate((x, y)), concatenate((xm, y))))
        assert_(eq(np.concatenate((x, y, x)), concatenate((x, ym, x)))) 
Example 24
Project: recruit   Author: Frank-qlu   File: test_old_ma.py    License: Apache License 2.0 5 votes vote down vote up
def test_testUfuncRegression(self):
        f_invalid_ignore = [
            'sqrt', 'arctanh', 'arcsin', 'arccos',
            'arccosh', 'arctanh', 'log', 'log10', 'divide',
            'true_divide', 'floor_divide', 'remainder', 'fmod']
        for f in ['sqrt', 'log', 'log10', 'exp', 'conjugate',
                  'sin', 'cos', 'tan',
                  'arcsin', 'arccos', 'arctan',
                  'sinh', 'cosh', 'tanh',
                  'arcsinh',
                  'arccosh',
                  'arctanh',
                  'absolute', 'fabs', 'negative',
                  'floor', 'ceil',
                  'logical_not',
                  'add', 'subtract', 'multiply',
                  'divide', 'true_divide', 'floor_divide',
                  'remainder', 'fmod', 'hypot', 'arctan2',
                  'equal', 'not_equal', 'less_equal', 'greater_equal',
                  'less', 'greater',
                  'logical_and', 'logical_or', 'logical_xor']:
            try:
                uf = getattr(umath, f)
            except AttributeError:
                uf = getattr(fromnumeric, f)
            mf = getattr(np.ma, f)
            args = self.d[:uf.nin]
            with np.errstate():
                if f in f_invalid_ignore:
                    np.seterr(invalid='ignore')
                if f in ['arctanh', 'log', 'log10']:
                    np.seterr(divide='ignore')
                ur = uf(*args)
                mr = mf(*args)
            assert_(eq(ur.filled(0), mr.filled(0), f))
            assert_(eqmask(ur.mask, mr.mask)) 
Example 25
Project: recruit   Author: Frank-qlu   File: test_core.py    License: Apache License 2.0 5 votes vote down vote up
def test_basic_ufuncs(self):
        # Test various functions such as sin, cos.
        (x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d
        assert_equal(np.cos(x), cos(xm))
        assert_equal(np.cosh(x), cosh(xm))
        assert_equal(np.sin(x), sin(xm))
        assert_equal(np.sinh(x), sinh(xm))
        assert_equal(np.tan(x), tan(xm))
        assert_equal(np.tanh(x), tanh(xm))
        assert_equal(np.sqrt(abs(x)), sqrt(xm))
        assert_equal(np.log(abs(x)), log(xm))
        assert_equal(np.log10(abs(x)), log10(xm))
        assert_equal(np.exp(x), exp(xm))
        assert_equal(np.arcsin(z), arcsin(zm))
        assert_equal(np.arccos(z), arccos(zm))
        assert_equal(np.arctan(z), arctan(zm))
        assert_equal(np.arctan2(x, y), arctan2(xm, ym))
        assert_equal(np.absolute(x), absolute(xm))
        assert_equal(np.angle(x + 1j*y), angle(xm + 1j*ym))
        assert_equal(np.angle(x + 1j*y, deg=True), angle(xm + 1j*ym, deg=True))
        assert_equal(np.equal(x, y), equal(xm, ym))
        assert_equal(np.not_equal(x, y), not_equal(xm, ym))
        assert_equal(np.less(x, y), less(xm, ym))
        assert_equal(np.greater(x, y), greater(xm, ym))
        assert_equal(np.less_equal(x, y), less_equal(xm, ym))
        assert_equal(np.greater_equal(x, y), greater_equal(xm, ym))
        assert_equal(np.conjugate(x), conjugate(xm)) 
Example 26
Project: recruit   Author: Frank-qlu   File: test_core.py    License: Apache License 2.0 5 votes vote down vote up
def test_testUfuncRegression(self):
        # Tests new ufuncs on MaskedArrays.
        for f in ['sqrt', 'log', 'log10', 'exp', 'conjugate',
                  'sin', 'cos', 'tan',
                  'arcsin', 'arccos', 'arctan',
                  'sinh', 'cosh', 'tanh',
                  'arcsinh',
                  'arccosh',
                  'arctanh',
                  'absolute', 'fabs', 'negative',
                  'floor', 'ceil',
                  'logical_not',
                  'add', 'subtract', 'multiply',
                  'divide', 'true_divide', 'floor_divide',
                  'remainder', 'fmod', 'hypot', 'arctan2',
                  'equal', 'not_equal', 'less_equal', 'greater_equal',
                  'less', 'greater',
                  'logical_and', 'logical_or', 'logical_xor',
                  ]:
            try:
                uf = getattr(umath, f)
            except AttributeError:
                uf = getattr(fromnumeric, f)
            mf = getattr(numpy.ma.core, f)
            args = self.d[:uf.nin]
            ur = uf(*args)
            mr = mf(*args)
            assert_equal(ur.filled(0), mr.filled(0), f)
            assert_mask_equal(ur.mask, mr.mask, err_msg=f) 
Example 27
Project: mars   Author: mars-project   File: cosh.py    License: Apache License 2.0 5 votes vote down vote up
def cosh(x, out=None, where=None, **kwargs):
    """
    Hyperbolic cosine, element-wise.

    Equivalent to ``1/2 * (mt.exp(x) + mt.exp(-x))`` and ``mt.cos(1j*x)``.

    Parameters
    ----------
    x : array_like
        Input tensor.
    out : Tensor, None, or tuple of Tensor and None, optional
        A location into which the result is stored. If provided, it must have
        a shape that the inputs broadcast to. If not provided or `None`,
        a freshly-allocated tensor is returned. A tuple (possible only as a
        keyword argument) must have length equal to the number of outputs.
    where : array_like, optional
        Values of True indicate to calculate the ufunc at that position, values
        of False indicate to leave the value in the output alone.
    **kwargs

    Returns
    -------
    out : Tensor
        Output array of same shape as `x`.

    Examples
    --------
    >>> import mars.tensor as mt

    >>> mt.cosh(0).execute()
    1.0

    The hyperbolic cosine describes the shape of a hanging cable:

    >>> import matplotlib.pyplot as plt
    >>> x = mt.linspace(-4, 4, 1000)
    >>> plt.plot(x.execute(), mt.cosh(x).execute())
    >>> plt.show()
    """
    op = TensorCosh(**kwargs)
    return op(x, out=out, where=where) 
Example 28
Project: lambda-packs   Author: ryfeus   File: _discrete_distns.py    License: MIT License 5 votes vote down vote up
def _stats(self, lambda_):
        mu = 1/(exp(lambda_)-1)
        var = exp(-lambda_)/(expm1(-lambda_))**2
        g1 = 2*cosh(lambda_/2.0)
        g2 = 4+2*cosh(lambda_)
        return mu, var, g1, g2 
Example 29
Project: lambda-packs   Author: ryfeus   File: test_old_ma.py    License: MIT License 5 votes vote down vote up
def test_testUfuncs1(self):
        # Test various functions such as sin, cos.
        (x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d
        self.assertTrue(eq(np.cos(x), cos(xm)))
        self.assertTrue(eq(np.cosh(x), cosh(xm)))
        self.assertTrue(eq(np.sin(x), sin(xm)))
        self.assertTrue(eq(np.sinh(x), sinh(xm)))
        self.assertTrue(eq(np.tan(x), tan(xm)))
        self.assertTrue(eq(np.tanh(x), tanh(xm)))
        with np.errstate(divide='ignore', invalid='ignore'):
            self.assertTrue(eq(np.sqrt(abs(x)), sqrt(xm)))
            self.assertTrue(eq(np.log(abs(x)), log(xm)))
            self.assertTrue(eq(np.log10(abs(x)), log10(xm)))
        self.assertTrue(eq(np.exp(x), exp(xm)))
        self.assertTrue(eq(np.arcsin(z), arcsin(zm)))
        self.assertTrue(eq(np.arccos(z), arccos(zm)))
        self.assertTrue(eq(np.arctan(z), arctan(zm)))
        self.assertTrue(eq(np.arctan2(x, y), arctan2(xm, ym)))
        self.assertTrue(eq(np.absolute(x), absolute(xm)))
        self.assertTrue(eq(np.equal(x, y), equal(xm, ym)))
        self.assertTrue(eq(np.not_equal(x, y), not_equal(xm, ym)))
        self.assertTrue(eq(np.less(x, y), less(xm, ym)))
        self.assertTrue(eq(np.greater(x, y), greater(xm, ym)))
        self.assertTrue(eq(np.less_equal(x, y), less_equal(xm, ym)))
        self.assertTrue(eq(np.greater_equal(x, y), greater_equal(xm, ym)))
        self.assertTrue(eq(np.conjugate(x), conjugate(xm)))
        self.assertTrue(eq(np.concatenate((x, y)), concatenate((xm, ym))))
        self.assertTrue(eq(np.concatenate((x, y)), concatenate((x, y))))
        self.assertTrue(eq(np.concatenate((x, y)), concatenate((xm, y))))
        self.assertTrue(eq(np.concatenate((x, y, x)), concatenate((x, ym, x)))) 
Example 30
Project: lambda-packs   Author: ryfeus   File: test_core.py    License: MIT License 5 votes vote down vote up
def test_basic_ufuncs(self):
        # Test various functions such as sin, cos.
        (x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d
        assert_equal(np.cos(x), cos(xm))
        assert_equal(np.cosh(x), cosh(xm))
        assert_equal(np.sin(x), sin(xm))
        assert_equal(np.sinh(x), sinh(xm))
        assert_equal(np.tan(x), tan(xm))
        assert_equal(np.tanh(x), tanh(xm))
        assert_equal(np.sqrt(abs(x)), sqrt(xm))
        assert_equal(np.log(abs(x)), log(xm))
        assert_equal(np.log10(abs(x)), log10(xm))
        assert_equal(np.exp(x), exp(xm))
        assert_equal(np.arcsin(z), arcsin(zm))
        assert_equal(np.arccos(z), arccos(zm))
        assert_equal(np.arctan(z), arctan(zm))
        assert_equal(np.arctan2(x, y), arctan2(xm, ym))
        assert_equal(np.absolute(x), absolute(xm))
        assert_equal(np.angle(x + 1j*y), angle(xm + 1j*ym))
        assert_equal(np.angle(x + 1j*y, deg=True), angle(xm + 1j*ym, deg=True))
        assert_equal(np.equal(x, y), equal(xm, ym))
        assert_equal(np.not_equal(x, y), not_equal(xm, ym))
        assert_equal(np.less(x, y), less(xm, ym))
        assert_equal(np.greater(x, y), greater(xm, ym))
        assert_equal(np.less_equal(x, y), less_equal(xm, ym))
        assert_equal(np.greater_equal(x, y), greater_equal(xm, ym))
        assert_equal(np.conjugate(x), conjugate(xm))