Python numpy.sinh() Examples

The following are 30 code examples of numpy.sinh(). 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: cosmology.py    From easyGalaxy with MIT License 6 votes vote down vote up
def Dm(self, z, cm=False, meter=False, pc=False, kpc=False, mpc=False):
        Ok = self.Ok()
        sOk = num.sqrt(num.abs(Ok))
        Dc = self.Dc(z)
        Dh = self.Dh()

        conversion = self.lengthConversion(cm=cm,
                                           meter=meter,
                                           pc=pc,
                                           kpc=kpc,
                                           mpc=mpc)

        if Ok > 0:
            return Dh / sOk * num.sinh(sOk * Dc / Dh) * conversion
        elif Ok == 0:
            return Dc * conversion
        else:
            return Dh / sOk * num.sin(sOk * Dc / Dh) * conversion

    # Angular diameter distance
    # Ratio of an objects physical transvserse size to its angular size in radians 
Example #2
Source File: relativity.py    From tf-pose with Apache License 2.0 6 votes vote down vote up
def tauStep(dtau, v0, x0, t0, g):
        ## linear step in proper time of clock.
        ## If an object has proper acceleration g and starts at position x0 with speed v0 at time t0
        ## as seen from an inertial frame, then return the new v, x, t after proper time dtau has elapsed.
        

        ## Compute how much t will change given a proper-time step of dtau
        gamma = (1. - v0**2)**-0.5
        if g == 0:
            dt = dtau * gamma
        else:
            v0g = v0 * gamma
            dt = (np.sinh(dtau * g + np.arcsinh(v0g)) - v0g) / g
        
        #return v0 + dtau * g, x0 + v0*dt, t0 + dt
        v1, x1, t1 = Simulation.hypTStep(dt, v0, x0, t0, g)
        return v1, x1, t0+dt 
Example #3
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 #4
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 #5
Source File: matfuncs.py    From lambda-packs with MIT License 6 votes vote down vote up
def _eq_10_42(lam_1, lam_2, t_12):
    """
    Equation (10.42) of Functions of Matrices: Theory and Computation.

    Notes
    -----
    This is a helper function for _fragment_2_1 of expm_2009.
    Equation (10.42) is on page 251 in the section on Schur algorithms.
    In particular, section 10.4.3 explains the Schur-Parlett algorithm.
    expm([[lam_1, t_12], [0, lam_1])
    =
    [[exp(lam_1), t_12*exp((lam_1 + lam_2)/2)*sinch((lam_1 - lam_2)/2)],
    [0, exp(lam_2)]
    """

    # The plain formula t_12 * (exp(lam_2) - exp(lam_2)) / (lam_2 - lam_1)
    # apparently suffers from cancellation, according to Higham's textbook.
    # A nice implementation of sinch, defined as sinh(x)/x,
    # will apparently work around the cancellation.
    a = 0.5 * (lam_1 + lam_2)
    b = 0.5 * (lam_1 - lam_2)
    return t_12 * np.exp(a) * _sinch(b) 
Example #6
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 #7
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 #8
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 #9
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 #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_squeeze_operation.py    From strawberryfields with Apache License 2.0 6 votes vote down vote up
def matrix_elem(n, r, m):
    """Matrix element corresponding to squeezed density matrix[n, m]"""
    eps = 1e-10

    if n % 2 != m % 2:
        return 0.0

    if r == 0.0:
        return np.complex(n == m)  # delta function

    k = np.arange(m % 2, min([m, n]) + 1, 2)
    res = np.sum(
        (-1) ** ((n - k) / 2)
        * np.exp(
            (lg(m + 1) + lg(n + 1)) / 2
            - lg(k + 1)
            - lg((m - k) / 2 + 1)
            - lg((n - k) / 2 + 1)
        )
        * (np.sinh(r) / 2 + eps) ** ((n + m - 2 * k) / 2)
        / (np.cosh(r) ** ((n + m + 1) / 2))
    )
    return res 
Example #12
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 #13
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 #14
Source File: test_states.py    From strawberryfields with Apache License 2.0 6 votes vote down vote up
def test_number_expectation_two_mode_squeezed(self, setup_backend, tol, batch_size):
        """Tests the expectation value of photon numbers when there is correlation"""
        if batch_size is not None:
            pytest.skip("Does not support batch mode")
        backend = setup_backend(3)
        state = backend.state()
        r = 0.2
        phi = 0.0
        backend.prepare_squeezed_state(r, phi, 0)
        backend.prepare_squeezed_state(-r, phi, 2)
        backend.beamsplitter(np.pi/4, np.pi, 0, 2)
        state = backend.state()
        nbar = np.sinh(r) ** 2

        res = state.number_expectation([2, 0])
        assert np.allclose(res[0], 2 * nbar ** 2 + nbar, atol=tol, rtol=0)

        res = state.number_expectation([0])
        assert np.allclose(res[0], nbar, atol=tol, rtol=0)

        res = state.number_expectation([2])
        assert np.allclose(res[0], nbar, atol=tol, rtol=0) 
Example #15
Source File: matfuncs.py    From Computable with MIT License 6 votes vote down vote up
def _eq_10_42(lam_1, lam_2, t_12):
    """
    Equation (10.42) of Functions of Matrices: Theory and Computation.

    Notes
    -----
    This is a helper function for _fragment_2_1 of expm_2009.
    Equation (10.42) is on page 251 in the section on Schur algorithms.
    In particular, section 10.4.3 explains the Schur-Parlett algorithm.
    expm([[lam_1, t_12], [0, lam_1])
    =
    [[exp(lam_1), t_12*exp((lam_1 + lam_2)/2)*sinch((lam_1 - lam_2)/2)],
    [0, exp(lam_2)]
    """

    # The plain formula t_12 * (exp(lam_2) - exp(lam_2)) / (lam_2 - lam_1)
    # apparently suffers from cancellation, according to Higham's textbook.
    # A nice implementation of sinch, defined as sinh(x)/x,
    # will apparently work around the cancellation.
    a = 0.5 * (lam_1 + lam_2)
    b = 0.5 * (lam_1 - lam_2)
    return t_12 * np.exp(a) * _sinch(b) 
Example #16
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 #17
Source File: display.py    From scarlet with MIT License 6 votes vote down vote up
def __init__(self, img, percentiles=[1, 99]):
        """Create norm that is linear between lower and upper percentile of img
        Parameters
        ----------
        img: array_like
            Image to normalize
        percentile: array_like, default=[1,99]
            Lower and upper percentile to consider. Pixel values below will be
            set to zero, above to saturated.
        """
        assert len(percentiles) == 2
        vmin, vmax = np.percentile(img, percentiles)
        # solution for beta assumes flat spectrum at vmax
        stretch = vmax - vmin
        beta = stretch / np.sinh(1)
        super().__init__(minimum=vmin, stretch=stretch, Q=beta) 
Example #18
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 #19
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 #20
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 #21
Source File: test_core.py    From recruit with 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 #22
Source File: test_tf_integration.py    From strawberryfields with Apache License 2.0 5 votes vote down vote up
def test_2mode_squeezed_vacuum_gradients(self, setup_eng, cutoff, tol, batch_size):
        """Tests whether the gradient for the probability of the states |0,0> and |1,1>
         created by an S2gate is correct."""
        if batch_size is not None:
            pytest.skip(
                "Cannot calculate gradient in batch mode, as tape.gradient "
                "cannot differentiate non-scalar output."
            )

        R = 0.3
        PHI = 0.2

        eng, prog = setup_eng(2)
        _r, _phi = prog.params("r", "phi")
        vacuum = np.zeros((cutoff, cutoff), dtype=np.complex64)
        vacuum[0, 0] = 1.0 + 0.0j

        with prog.context as q:
            Ket(vacuum) | (q[0], q[1])
            S2gate(_r, _phi) | (q[0], q[1])

        r = tf.Variable(R)
        phi = tf.Variable(PHI)

        with tf.GradientTape(persistent=True) as tape:
            state = eng.run(prog, args={"r": r, "phi": phi}).state
            prob00 = tf.abs(state.ket()[0, 0])**2
            prob11 = tf.abs(state.ket()[1, 1])**2

        r_grad, phi_grad = tape.gradient(prob00, [r, phi])
        assert np.allclose(r_grad, -2*np.tanh(R)/np.cosh(R)**2, atol=tol, rtol=0)
        assert np.allclose(phi_grad, 0.0, atol=tol, rtol=0)

        r_grad, phi_grad = tape.gradient(prob11, [r, phi])
        assert np.allclose(r_grad, 2*(np.sinh(R) - np.sinh(R)**3)/np.cosh(R)**5, atol=tol, rtol=0)
        assert np.allclose(phi_grad, 0.0, atol=tol, rtol=0) 
Example #23
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 #24
Source File: test_decompositions.py    From strawberryfields with Apache License 2.0 5 votes vote down vote up
def test_mean_photon(self, tol, make_symmetric):
        """Test that the mean photon number is correct in graph_embed"""
        num_modes = 6
        A = np.random.random([num_modes, num_modes]) + 1j * np.random.random([num_modes, num_modes])
        if make_symmetric:
            A += A.T
        n_mean = 1.0
        sc, _, _ = dec.bipartite_graph_embed(A, mean_photon_per_mode=n_mean)
        n_mean_calc = np.sum(np.sinh(sc) ** 2) / (num_modes)
        assert np.allclose(n_mean, n_mean_calc, atol=tol, rtol=0) 
Example #25
Source File: test_core.py    From recruit with 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
Source File: test_old_ma.py    From recruit with 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 #27
Source File: test_old_ma.py    From recruit with 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 #28
Source File: ls_fap.py    From feets with MIT License 5 votes vote down vote up
def tau_davies(Z, fmax, t, y, dy, normalization="standard", dH=1, dK=3):
    """tau factor for estimating Davies bound (Baluev 2008, Table 1)"""
    N = len(t)
    NH = N - dH  # DOF for null hypothesis
    NK = N - dK  # DOF for periodic hypothesis
    Dt = _weighted_var(t, dy)
    Teff = np.sqrt(4 * np.pi * Dt)
    W = fmax * Teff
    if normalization == "psd":
        # 'psd' normalization is same as Baluev's z
        return W * np.exp(-Z) * np.sqrt(Z)
    elif normalization == "standard":
        # 'standard' normalization is Z = 2/NH * z_1
        return (
            _gamma(NH)
            * W
            * (1 - Z) ** (0.5 * (NK - 1))
            * np.sqrt(0.5 * NH * Z)
        )
    elif normalization == "model":
        # 'model' normalization is Z = 2/NK * z_2
        return _gamma(NK) * W * (1 + Z) ** (-0.5 * NK) * np.sqrt(0.5 * NK * Z)
    elif normalization == "log":
        # 'log' normalization is Z = 2/NK * z_3
        return (
            _gamma(NK)
            * W
            * np.exp(-0.5 * Z * (NK - 0.5))
            * np.sqrt(NK * np.sinh(0.5 * Z))
        )
    else:
        raise NotImplementedError("normalization={0}".format(normalization)) 
Example #29
Source File: gaussiancircuit.py    From strawberryfields with Apache License 2.0 5 votes vote down vote up
def squeeze(self, r, phi, k):
        """ Implements a squeezing operation in mode k by the amount z = r*exp(1j*phi)."""
        if self.active[k] is None:
            raise ValueError("Cannot squeeze mode, mode does not exist")

        phase = np.exp(1j * phi)
        phase2 = phase * phase
        sh = np.sinh(r)
        ch = np.cosh(r)
        sh2 = sh * sh
        ch2 = ch * ch
        shch = sh * ch
        nk = np.copy(self.nmat[k])
        mk = np.copy(self.mmat[k])

        alphak = np.copy(self.mean[k])
        # Update displacement of mode k
        self.mean[k] = alphak * ch - phase * np.conj(alphak) * sh
        # Update covariance matrix elements. Only the k column and row of nmat and mmat need to be updated.
        # First update the diagonal elements
        self.nmat[k, k] = (
            sh2
            - phase * shch * np.conj(mk[k])
            - shch * np.conj(phase) * mk[k]
            + ch2 * nk[k]
            + sh2 * nk[k]
        )
        self.mmat[k, k] = (
            -(phase * shch) + phase2 * sh2 * np.conj(mk[k]) + ch2 * mk[k] - 2 * phase * shch * nk[k]
        )

        # Update the column k
        for l in np.delete(np.arange(self.nlen), k):
            self.nmat[k, l] = -(sh * np.conj(phase) * mk[l]) + ch * nk[l]
            self.mmat[k, l] = ch * mk[l] - phase * sh * nk[l]

        # Update row k
        self.nmat[:, k] = np.conj(self.nmat[k])
        self.mmat[:, k] = self.mmat[k] 
Example #30
Source File: test_decompositions.py    From strawberryfields with Apache License 2.0 5 votes vote down vote up
def test_mean_photon(self, tol):
        """Test that the mean photon number is correct in graph_embed"""
        num_modes = 6
        A = np.random.random([num_modes, num_modes]) + 1j * np.random.random([num_modes, num_modes])
        A += A.T
        n_mean = 10.0 / num_modes
        sc, _ = dec.graph_embed(A, mean_photon_per_mode=n_mean)
        n_mean_calc = np.mean(np.sinh(sc) ** 2)

        assert np.allclose(n_mean, n_mean_calc, atol=tol, rtol=0)