Python numpy.cosh() Examples

The following are 30 code examples of numpy.cosh(). 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 also want to check out all available functions/classes of the module numpy , or try the search function .
Example #1
Source File: keplerSTM.py    From EXOSIMS with 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
Source File: uvf.py    From solar-system with 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
Source File: filter_design.py    From Computable with 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 #4
Source File: filter_design.py    From Computable with 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 #5
Source File: test_twomode_squeezing_operation.py    From strawberryfields with 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 #6
Source File: testAccumulatorsArithmetic.py    From Finance-Python with 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 #7
Source File: test_states.py    From strawberryfields with 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 #8
Source File: test_states_wigner.py    From strawberryfields with 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 #9
Source File: quantizers_test.py    From larq with 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 #10
Source File: test_utils.py    From strawberryfields with 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 #11
Source File: test_utils.py    From strawberryfields with 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 #12
Source File: test_utils.py    From strawberryfields with 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 #13
Source File: rk_py.py    From ocelot with 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 #14
Source File: test_circuitspecs_X12.py    From strawberryfields with 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 #15
Source File: test_ops_decompositions.py    From strawberryfields with 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 #16
Source File: test_circuitspecs_X8.py    From strawberryfields with 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 #17
Source File: test_decompositions_integration.py    From strawberryfields with 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 #18
Source File: test_utils.py    From strawberryfields with Apache License 2.0 5 votes vote down vote up
def test_squeezed_state_fock(self, r, phi, cutoff, hbar, tol):
        """test squeezed state returns correct Fock basis state vector"""
        state = utils.squeezed_state(r, phi, basis="fock", fock_dim=cutoff, hbar=hbar)

        n = np.arange(cutoff)
        kets = (np.sqrt(fac(2 * (n // 2))) / (2 ** (n // 2) * fac(n // 2))) * (
            -np.exp(1j * phi) * np.tanh(r)
        ) ** (n // 2)
        expected = np.where(n % 2 == 0, np.sqrt(1 / np.cosh(r)) * kets, 0)

        assert np.allclose(state, expected, atol=tol, rtol=0) 
Example #19
Source File: stochastic_optics.py    From eht-imaging with GNU General Public License v3.0 5 votes vote down vote up
def P_phi(self, phi):
        if self.model == 'von_Mises':
            return self.P_phi_prefac * np.cosh(self.kzeta*np.cos(phi - self.phi0))  
        elif self.model == 'boxcar':
            return self.P_phi_prefac * (1.0 - ((np.pi/(2.0*(1.0 + self.kzeta)) < (phi - self.phi0) % np.pi) & ((phi - self.phi0) % np.pi < np.pi - np.pi/(2.0*(1.0 + self.kzeta)))))
        elif self.model == 'dipole':
            return self.P_phi_prefac * (1.0 + self.kzeta*np.sin(phi - self.phi0)**2)**(-(self.scatt_alpha + 2.0)/2.0) 
Example #20
Source File: test_old_ma.py    From Computable with MIT License 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',
                # 'nonzero', 'around',
                'floor', 'ceil',
                # 'sometrue', 'alltrue',
                '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)
            self.assertTrue(eq(ur.filled(0), mr.filled(0), f))
            self.assertTrue(eqmask(ur.mask, mr.mask)) 
Example #21
Source File: test_old_ma.py    From Mastering-Elasticsearch-7.0 with 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
        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 #22
Source File: test_ops_decompositions.py    From strawberryfields with Apache License 2.0 5 votes vote down vote up
def _two_mode_squeezing(r, phi, modes, num_modes):
    """Two mode squeezing in the phase space.

    Args:
        r (float): squeezing magnitude
        phi (float): rotation parameter
        modes (list[int]): modes 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, 0, sp * sh],
            [cp * sh, ch, sp * sh, 0],
            [0, sp * sh, ch, -cp * sh],
            [sp * sh, 0, -cp * sh, ch],
        ]
    )

    return expand(S, modes, num_modes) 
Example #23
Source File: test_old_ma.py    From Mastering-Elasticsearch-7.0 with MIT License 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 #24
Source File: test_core.py    From Mastering-Elasticsearch-7.0 with 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)) 
Example #25
Source File: test_core.py    From Mastering-Elasticsearch-7.0 with MIT License 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 #26
Source File: test_tf_integration.py    From strawberryfields with Apache License 2.0 5 votes vote down vote up
def test_displaced_squeezed_mean_photon_gradient(self, setup_eng, cutoff, tol, batch_size):
        """Test whether the gradient of the mean photon number of a displaced squeezed
        state is correct.

        .. note::

            As this test contains multiple gates being applied to the program,
            this test will fail in TensorFlow 2.1 due to the bug discussed in
            https://github.com/tensorflow/tensorflow/issues/37307, if `tf.einsum` is being used
            in ``tfbackend/ops.py`` rather than _einsum_v1.
        """
        if batch_size is not None:
            pytest.skip(
                "Cannot calculate gradient in batch mode, as tape.gradient "
                "cannot differentiate non-scalar output."
            )

        eng, prog = setup_eng(1)

        with prog.context as q:
            Sgate(prog.params("r"), prog.params("phi")) | q
            Dgate(prog.params("a")) | q

        a = tf.Variable(ALPHA)
        r = tf.Variable(0.105)
        phi = tf.Variable(0.123)

        with tf.GradientTape() as tape:
            state = eng.run(prog, args={"a": a, "r": r, "phi": phi}).state
            mean, _ = state.mean_photon(0)

        # test the mean and variance of the photon number is correct
        mean_ex = a ** 2 + tf.sinh(r) ** 2
        assert np.allclose(mean, mean_ex, atol=tol, rtol=0)

        # test the gradient of the mean is correct
        grad = tape.gradient(mean, [a, r, phi])
        grad_ex = [2 * a, 2 * tf.sinh(r) * tf.cosh(r), 0]
        assert np.allclose(grad, grad_ex, atol=tol, rtol=0) 
Example #27
Source File: ops.py    From strawberryfields with Apache License 2.0 5 votes vote down vote up
def displacedSqueezed(r_d, phi_d, r_s, phi_s, trunc):
    r"""
    The displaced squeezed state :math:`\ket{\alpha,\zeta} = D(\alpha)S(r\exp{(i\phi)})\ket{0}`  where `alpha = r_d * np.exp(1j * phi_d)` and `zeta = r_s * np.exp(1j * phi_s)`.
    """
    if np.allclose(r_s, 0.0):
        return coherentState(r_d, phi_d, trunc)

    if np.allclose(r_d, 0.0):
        return squeezedState(r_s, phi_s, trunc)

    ph = np.exp(1j * phi_s)
    ch = cosh(r_s)
    sh = sinh(r_s)
    th = tanh(r_s)
    alpha = r_d * np.exp(1j * phi_d)

    gamma = alpha * ch + np.conj(alpha) * ph * sh
    hermite_arg = gamma / np.sqrt(ph * np.sinh(2 * r_s) + 1e-10)

    # normalization constant
    N = np.exp(-0.5 * np.abs(alpha) ** 2 - 0.5 * np.conj(alpha) ** 2 * ph * th)

    coeff = np.array([(0.5 * ph * th) ** (n / 2) / np.sqrt(fac(n) * ch) for n in range(trunc)])
    vec = np.array([H(hermite_arg, row) for row in np.diag(coeff)])
    state = N * vec

    return state 
Example #28
Source File: ops.py    From strawberryfields with Apache License 2.0 5 votes vote down vote up
def squeezedState(r, theta, trunc):
    r"""
    The squeezed state :math:`S(re^{i\theta})`.
    """

    def entry(n):
        """squeezed summation term"""
        return (sqrt(fac(2 * n)) / (2 ** n * fac(n))) * (-exp(1j * theta) * tanh(r)) ** n

    vec = array([entry(n // 2) if n % 2 == 0 else 0.0 + 0.0j for n in range(trunc)])
    return sqrt(1 / cosh(r)) * vec 
Example #29
Source File: characteristic_funs.py    From fftoptionlib with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def cir_int_rt_chf(u, t, k, theta, sigma, r0):
    r = np.sqrt(k ** 2 - 1j * u * 2 * sigma ** 2)
    cosh_fun = np.cosh(r * t / 2)
    sinh_fun = np.sinh(r * t / 2)
    coth_fun = cosh_fun / sinh_fun
    a_t_v = np.exp(t * theta * (k ** 2) / (sigma ** 2)) / (cosh_fun + (k / r) * sinh_fun) ** (
        2 * k * theta / (sigma ** 2))
    b_t_v = 2 * 1j * u / (k + r * coth_fun)
    return a_t_v * np.exp(b_t_v * r0) 
Example #30
Source File: kernel_approximation.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def transform(self, X):
        """Apply approximate feature map to X.

        Parameters
        ----------
        X : {array-like, sparse matrix}, shape = (n_samples, n_features)

        Returns
        -------
        X_new : {array, sparse matrix}, \
               shape = (n_samples, n_features * (2*sample_steps + 1))
            Whether the return value is an array of sparse matrix depends on
            the type of the input X.
        """
        msg = ("%(name)s is not fitted. Call fit to set the parameters before"
               " calling transform")
        check_is_fitted(self, "sample_interval_", msg=msg)

        X = check_array(X, accept_sparse='csr')
        sparse = sp.issparse(X)

        # check if X has negative values. Doesn't play well with np.log.
        if ((X.data if sparse else X) < 0).any():
            raise ValueError("Entries of X must be non-negative.")
        # zeroth component
        # 1/cosh = sech
        # cosh(0) = 1.0

        transf = self._transform_sparse if sparse else self._transform_dense
        return transf(X)