Python cmath.exp() Examples

The following are 30 code examples of cmath.exp(). 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 cmath , or try the search function .
Example #1
Source File: _time_evolution_test.py    From OpenFermion-ProjectQ with Apache License 2.0 6 votes vote down vote up
def test_or_gate_identity():
    saving_backend = DummyEngine(save_commands=True)
    eng = MainEngine(backend=saving_backend, engine_list=[])
    qureg = eng.allocate_qureg(4)
    hamiltonian = QubitOperator((), 3.4)
    correct_h = copy.deepcopy(hamiltonian)
    gate = te.TimeEvolution(2.1, hamiltonian)
    gate | qureg
    eng.flush()
    cmd = saving_backend.received_commands[4]
    assert isinstance(cmd.gate, Ph)
    assert cmd.gate == Ph(-3.4 * 2.1)
    correct = numpy.array([[cmath.exp(-1j * 3.4 * 2.1), 0],
                           [0, cmath.exp(-1j * 3.4 * 2.1)]])
    print(correct)
    print(cmd.gate.matrix)
    assert numpy.allclose(cmd.gate.matrix, correct) 
Example #2
Source File: numpy_ops.py    From pennylane with Apache License 2.0 6 votes vote down vote up
def CRotz(theta):
    r"""Two-qubit controlled rotation about the z axis.

    Args:
        theta (float): rotation angle
    Returns:
        array: unitary 4x4 rotation matrix :math:`|0\rangle\langle 0|\otimes \mathbb{I}+|1\rangle\langle 1|\otimes R_z(\theta)`
    """
    return np.array(
        [
            [1, 0, 0, 0],
            [0, 1, 0, 0],
            [0, 0, cmath.exp(-1j * theta / 2), 0],
            [0, 0, 0, cmath.exp(1j * theta / 2)],
        ]
    ) 
Example #3
Source File: recipe-578997.py    From code with MIT License 6 votes vote down vote up
def DFT2D(image):
    global M, N
    (M, N) = image.size # (imgx, imgy)
    dft2d_red = [[0.0 for k in range(M)] for l in range(N)] 
    dft2d_grn = [[0.0 for k in range(M)] for l in range(N)] 
    dft2d_blu = [[0.0 for k in range(M)] for l in range(N)] 
    pixels = image.load()
    for k in range(M):
        for l in range(N):
            sum_red = 0.0
            sum_grn = 0.0
            sum_blu = 0.0
            for m in range(M):
                for n in range(N):
                    (red, grn, blu, alpha) = pixels[m, n]
                    e = cmath.exp(- 1j * pi2 * (float(k * m) / M + float(l * n) / N))
                    sum_red += red * e
                    sum_grn += grn * e
                    sum_blu += blu * e
            dft2d_red[l][k] = sum_red / M / N
            dft2d_grn[l][k] = sum_grn / M / N
            dft2d_blu[l][k] = sum_blu / M / N
    return (dft2d_red, dft2d_grn, dft2d_blu) 
Example #4
Source File: test_SWSHs.py    From spherical_functions with MIT License 6 votes vote down vote up
def test_SWSH_spin_behavior(Rs, special_angles, ell_max):
    # We expect that the SWSHs behave according to
    # sYlm( R * exp(gamma*z/2) ) = sYlm(R) * exp(-1j*s*gamma)
    # See http://moble.github.io/spherical_functions/SWSHs.html#fn:2
    # for a more detailed explanation
    # print("")
    for i, R in enumerate(Rs):
        # print("\t{0} of {1}: R = {2}".format(i, len(Rs), R))
        for gamma in special_angles:
            for ell in range(ell_max + 1):
                for s in range(-ell, ell + 1):
                    LM = np.array([[ell, m] for m in range(-ell, ell + 1)])
                    Rgamma = R * np.quaternion(math.cos(gamma / 2.), 0, 0, math.sin(gamma / 2.))
                    sYlm1 = sf.SWSH(Rgamma, s, LM)
                    sYlm2 = sf.SWSH(R, s, LM) * cmath.exp(-1j * s * gamma)
                    # print(R, gamma, ell, s, np.max(np.abs(sYlm1-sYlm2)))
                    assert np.allclose(sYlm1, sYlm2, atol=ell ** 6 * precision_SWSH, rtol=ell ** 6 * precision_SWSH) 
Example #5
Source File: test_SWSHs.py    From spherical_functions with MIT License 6 votes vote down vote up
def test_SWSH_NINJA_values(special_angles, ell_max):
    def m2Y22(iota, phi):
        return math.sqrt(5 / (64 * np.pi)) * (1 + math.cos(iota)) ** 2 * cmath.exp(2j * phi)

    def m2Y21(iota, phi):
        return math.sqrt(5 / (16 * np.pi)) * math.sin(iota) * (1 + math.cos(iota)) * cmath.exp(1j * phi)

    def m2Y20(iota, phi):
        return math.sqrt(15 / (32 * np.pi)) * math.sin(iota) ** 2

    def m2Y2m1(iota, phi):
        return math.sqrt(5 / (16 * np.pi)) * math.sin(iota) * (1 - math.cos(iota)) * cmath.exp(-1j * phi)

    def m2Y2m2(iota, phi):
        return math.sqrt(5 / (64 * np.pi)) * (1 - math.cos(iota)) ** 2 * cmath.exp(-2j * phi)

    for iota in special_angles:
        for phi in special_angles:
            assert abs(slow_sYlm(-2, 2, 2, iota, phi) - m2Y22(iota, phi)) < ell_max * precision_SWSH
            assert abs(slow_sYlm(-2, 2, 1, iota, phi) - m2Y21(iota, phi)) < ell_max * precision_SWSH
            assert abs(slow_sYlm(-2, 2, 0, iota, phi) - m2Y20(iota, phi)) < ell_max * precision_SWSH
            assert abs(slow_sYlm(-2, 2, -1, iota, phi) - m2Y2m1(iota, phi)) < ell_max * precision_SWSH
            assert abs(slow_sYlm(-2, 2, -2, iota, phi) - m2Y2m2(iota, phi)) < ell_max * precision_SWSH 
Example #6
Source File: default_gaussian.py    From pennylane with Apache License 2.0 6 votes vote down vote up
def coherent_state(a, phi=0, hbar=2.0):
    r"""Returns a coherent state.

    Args:
        a (complex) : the displacement
        phi (float): the phase
        hbar (float): (default 2) the value of :math:`\hbar` in the commutation
            relation :math:`[\x,\p]=i\hbar`
    Returns:
        array: the coherent state
    """
    alpha = a * cmath.exp(1j * phi)
    means = np.array([alpha.real, alpha.imag]) * math.sqrt(2 * hbar)
    cov = np.identity(2) * hbar / 2
    state = [means, cov]
    return state 
Example #7
Source File: default_gaussian.py    From pennylane with Apache License 2.0 6 votes vote down vote up
def displaced_squeezed_state(a, phi_a, r, phi_r, hbar=2.0):
    r"""Returns a squeezed coherent state

    Args:
        a (real): the displacement magnitude
        phi_a (real): the displacement phase
        r (float): the squeezing magnitude
        phi_r (float): the squeezing phase :math:`\phi_r`
        hbar (float): (default 2) the value of :math:`\hbar` in the commutation
            relation :math:`[\x,\p]=i\hbar`

    Returns:
        array: the squeezed coherent state
    """
    alpha = a * cmath.exp(1j * phi_a)
    means = np.array([alpha.real, alpha.imag]) * math.sqrt(2 * hbar)
    state = [means, squeezed_cov(r, phi_r, hbar)]
    return state 
Example #8
Source File: fluxonium.py    From scqubits with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def hamiltonian(self):  # follow Zhu et al., PRB 87, 024510 (2013)
        """Construct Hamiltonian matrix in harmonic-oscillator basis, following Zhu et al., PRB 87, 024510 (2013)

        Returns
        -------
        ndarray
        """
        dimension = self.hilbertdim()
        diag_elements = [i * self.E_plasma() for i in range(dimension)]
        lc_osc_matrix = np.diag(diag_elements)

        exp_matrix = self.exp_i_phi_operator() * cmath.exp(1j * 2 * np.pi * self.flux)
        cos_matrix = 0.5 * (exp_matrix + exp_matrix.conjugate().T)

        hamiltonian_mat = lc_osc_matrix - self.EJ * cos_matrix
        return np.real(hamiltonian_mat)  # use np.real to remove rounding errors from matrix exponential,
        # fluxonium Hamiltonian in harm. osc. basis is real-valued 
Example #9
Source File: recipe-578997.py    From code with MIT License 6 votes vote down vote up
def IDFT2D(dft2d):
    (dft2d_red, dft2d_grn, dft2d_blu) = dft2d
    global M, N
    image = Image.new("RGB", (M, N))
    pixels = image.load() 
    for m in range(M):
        for n in range(N):
            sum_red = 0.0
            sum_grn = 0.0
            sum_blu = 0.0
            for k in range(M):
                for l in range(N):
                    e = cmath.exp(1j * pi2 * (float(k * m) / M + float(l * n) / N))
                    sum_red += dft2d_red[l][k] * e
                    sum_grn += dft2d_grn[l][k] * e
                    sum_blu += dft2d_blu[l][k] * e
            red = int(sum_red.real + 0.5)
            grn = int(sum_grn.real + 0.5)
            blu = int(sum_blu.real + 0.5)
            pixels[m, n] = (red, grn, blu)
    return image

# TEST
# Recreate input image from 2D DFT results to compare to input image 
Example #10
Source File: fsim_gate.py    From Cirq with Apache License 2.0 6 votes vote down vote up
def _apply_unitary_(self,
                        args: 'cirq.ApplyUnitaryArgs') -> Optional[np.ndarray]:
        if cirq.is_parameterized(self):
            return None
        if self.theta != 0:
            inner_matrix = protocols.unitary(cirq.rx(2 * self.theta))
            oi = args.subspace_index(0b01)
            io = args.subspace_index(0b10)
            out = cirq.apply_matrix_to_slices(args.target_tensor,
                                              inner_matrix,
                                              slices=[oi, io],
                                              out=args.available_buffer)
        else:
            out = args.target_tensor
        if self.phi != 0:
            ii = args.subspace_index(0b11)
            out[ii] *= cmath.exp(-1j * self.phi)
        return out 
Example #11
Source File: gate_data.py    From pennylane with Apache License 2.0 6 votes vote down vote up
def CRotz(theta):
    r"""Two-qubit controlled rotation about the z axis.

    Args:
        theta (float): rotation angle
    Returns:
        array: unitary 4x4 rotation matrix :math:`|0\rangle\langle 0|\otimes \mathbb{I}+|1\rangle\langle 1|\otimes R_z(\theta)`
    """
    return np.array(
        [
            [1, 0, 0, 0],
            [0, 1, 0, 0],
            [0, 0, cmath.exp(-1j * theta / 2), 0],
            [0, 0, 0, cmath.exp(1j * theta / 2)],
        ]
    ) 
Example #12
Source File: vectors.py    From micropython-tft-gui with MIT License 6 votes vote down vote up
def arrow(tft, origin, vec, lc, color):
    ccw = cmath.exp(3j * cmath.pi/4)  # Unit vectors
    cw = cmath.exp(-3j * cmath.pi/4)
    length, theta = cmath.polar(vec)
    uv = cmath.rect(1, theta)  # Unit rotation vector
    start = -vec
    if length > 3 * lc:  # If line is long
        ds = cmath.rect(lc, theta)
        start += ds  # shorten to allow for length of tail chevrons
    chev = lc + 0j
    pline(tft, origin, vec, color)  # Origin to tip
    pline(tft, origin, start, color)  # Origin to tail
    pline(tft, origin + conj(vec), chev*ccw*uv, color)  # Tip chevron
    pline(tft, origin + conj(vec), chev*cw*uv, color)
    if length > lc:  # Confusing appearance of very short vectors with tail chevron
        pline(tft, origin + conj(start), chev*ccw*uv, color)  # Tail chevron
        pline(tft, origin + conj(start), chev*cw*uv, color)

# Vector display 
Example #13
Source File: test_muegamma.py    From flavio with MIT License 6 votes vote down vote up
def test_tauegamma_implementation(self):
        input_dict_list=[{
        'Cgamma_mue':np.random.random()*1e-8*exp(1j*2*pi*np.random.random()),
        'Cgamma_emu':np.random.random()*1e-8*exp(1j*2*pi*np.random.random()),
        } for i in range(10)]
        BRs = np.array([
            flavio.np_prediction(
                'BR(mu->egamma)',
                Wilson(input_dict, 100,  'WET', 'flavio')
            )
            for input_dict in input_dict_list
        ])
        compare_BRs = np.array([
            compare_BR(
                Wilson(input_dict, 100,  'WET', 'flavio'),
                'mu', 'e',
            )
            for input_dict in input_dict_list
        ])
        self.assertAlmostEqual(np.max(np.abs(1-BRs/compare_BRs)), 0, delta=0.005) 
Example #14
Source File: path.py    From svgpathtools with MIT License 6 votes vote down vote up
def phase2t(self, psi):
        """Given phase -pi < psi <= pi,
        returns the t value such that
        exp(1j*psi) = self.u1transform(self.point(t)).
        """
        def _deg(rads, domain_lower_limit):
            # Convert rads to degrees in [0, 360) domain
            degs = degrees(rads % (2*pi))

            # Convert to [domain_lower_limit, domain_lower_limit + 360) domain
            k = domain_lower_limit // 360
            degs += k * 360
            if degs < domain_lower_limit:
                degs += 360
            return degs

        if self.delta > 0:
            degs = _deg(psi, domain_lower_limit=self.theta)
        else:
            degs = _deg(psi, domain_lower_limit=self.theta)
        return (degs - self.theta)/self.delta 
Example #15
Source File: test_taulgamma.py    From flavio with MIT License 6 votes vote down vote up
def test_taumugamma_implementation(self):
        input_dict_list=[{
        'Cgamma_taumu':np.random.random()*1e-8*exp(1j*2*pi*np.random.random()),
        'Cgamma_mutau':np.random.random()*1e-8*exp(1j*2*pi*np.random.random()),
        } for i in range(10)]
        BRs = np.array([
            flavio.np_prediction(
                'BR(tau->mugamma)',
                Wilson(input_dict, 100,  'WET', 'flavio')
            )
            for input_dict in input_dict_list
        ])
        compare_BRs = np.array([
            compare_BR(
                Wilson(input_dict, 100,  'WET', 'flavio'),
                'tau', 'mu',
            )
            for input_dict in input_dict_list
        ])
        self.assertAlmostEqual(np.max(np.abs(1-BRs/compare_BRs)), 0, delta=0.02) 
Example #16
Source File: test_taulgamma.py    From flavio with MIT License 6 votes vote down vote up
def test_tauegamma_implementation(self):
        input_dict_list=[{
        'Cgamma_taue':np.random.random()*1e-8*exp(1j*2*pi*np.random.random()),
        'Cgamma_etau':np.random.random()*1e-8*exp(1j*2*pi*np.random.random()),
        } for i in range(10)]
        BRs = np.array([
            flavio.np_prediction(
                'BR(tau->egamma)',
                Wilson(input_dict, 100,  'WET', 'flavio')
            )
            for input_dict in input_dict_list
        ])
        compare_BRs = np.array([
            compare_BR(
                Wilson(input_dict, 100,  'WET', 'flavio'),
                'tau', 'e',
            )
            for input_dict in input_dict_list
        ])
        self.assertAlmostEqual(np.max(np.abs(1-BRs/compare_BRs)), 0, delta=0.002) 
Example #17
Source File: nanogui.py    From micropython-nano-gui with MIT License 6 votes vote down vote up
def arrow(dev, origin, vec, lc, color, ccw=cmath.exp(3j * cmath.pi/4), cw=cmath.exp(-3j * cmath.pi/4)):
    length, theta = cmath.polar(vec)
    uv = cmath.rect(1, theta)  # Unit rotation vector
    start = -vec
    if length > 3 * lc:  # If line is long
        ds = cmath.rect(lc, theta)
        start += ds  # shorten to allow for length of tail chevrons
    chev = lc + 0j
    polar(dev, origin, vec, color)  # Origin to tip
    polar(dev, origin, start, color)  # Origin to tail
    polar(dev, origin + conj(vec), chev*ccw*uv, color)  # Tip chevron
    polar(dev, origin + conj(vec), chev*cw*uv, color)
    if length > lc:  # Confusing appearance of very short vectors with tail chevron
        polar(dev, origin + conj(start), chev*ccw*uv, color)  # Tail chevron
        polar(dev, origin + conj(start), chev*cw*uv, color)

# If a (framebuf based) device is passed to refresh, the screen is cleared.
# None causes pending widgets to be drawn and the result to be copied to hardware.
# The pend mechanism enables a displayable object to postpone its renedering
# until it is complete: efficient for e.g. Dial which may have multiple Pointers 
Example #18
Source File: matrices.py    From pyquil with Apache License 2.0 5 votes vote down vote up
def CPHASE10(phi: float) -> np.ndarray:
    return np.diag([1.0, 1.0, np.exp(1j * phi), 1.0]) 
Example #19
Source File: abstract_reader.py    From ditto with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_sequence_impedance_matrix(self, phase_impedance_matrix):
        """Get sequence impedance matrix from phase impedance matrix."""

        phase_impedance_matrix = np.array(phase_impedance_matrix)
        # If we have a 3 by 3 phase impedance matrix
        if phase_impedance_matrix.shape == (3, 3):
            a = cmath.exp(complex(0, 2.0 / 3 * cmath.pi))
            A = np.array(
                [
                    [complex(1.0, 0), complex(1.0, 0), complex(1.0, 0)],
                    [complex(1.0, 0), a ** 2, a],
                    [complex(1.0, 0), a, a ** 2],
                ]
            )
            A_inv = (
                1.0
                / 3.0
                * np.array(
                    [
                        [complex(1.0, 0), complex(1.0, 0), complex(1.0, 0)],
                        [complex(1.0, 0), a, a ** 2],
                        [complex(1.0, 0), a ** 2, a],
                    ]
                )
            )
        # if we have a 2 by 2 phase impedance matrix
        elif phase_impedance_matrix.shape == (2, 2):
            A = np.array([[1.0, 1.0], [1.0, -1.0]])
            A_inv = np.array([[0.5, 0.5], [0.5, -0.5]])
        else:
            return []
        return np.dot(A_inv, np.dot(phase_impedance_matrix, A)) 
Example #20
Source File: gate_data.py    From pennylane with Apache License 2.0 5 votes vote down vote up
def Rphi(phi):
    r"""One-qubit phase shift.

    Args:
        phi (float): phase shift angle
    Returns:
        array: unitary 2x2 phase shift matrix
    """
    return np.array([[1, 0], [0, cmath.exp(1j * phi)]]) 
Example #21
Source File: qubit.py    From pennylane with Apache License 2.0 5 votes vote down vote up
def _matrix(cls, *params):
        phi = params[0]
        return np.array([[1, 0], [0, cmath.exp(1j * phi)]]) 
Example #22
Source File: qubit.py    From pennylane with Apache License 2.0 5 votes vote down vote up
def _eigvals(cls, *params):
        theta = params[0]
        p = cmath.exp(-0.5j * theta)

        return np.array([p, p.conjugate()]) 
Example #23
Source File: qubit.py    From pennylane with Apache License 2.0 5 votes vote down vote up
def _eigvals(cls, *params):
        return np.array([1, cmath.exp(1j * np.pi / 4)]) 
Example #24
Source File: qubit.py    From pennylane with Apache License 2.0 5 votes vote down vote up
def _matrix(cls, *params):
        return np.array([[1, 0], [0, cmath.exp(1j * np.pi / 4)]]) 
Example #25
Source File: numpy_ops.py    From pennylane with Apache License 2.0 5 votes vote down vote up
def CRot3(a, b, c):
    r"""Arbitrary two-qubit controlled rotation using three Euler angles.

    Args:
        a,b,c (float): rotation angles
    Returns:
        array: unitary 4x4 rotation matrix :math:`|0\rangle\langle 0|\otimes \mathbb{I}+|1\rangle\langle 1|\otimes R(a,b,c)`
    """
    return np.array(
        [
            [1, 0, 0, 0],
            [0, 1, 0, 0],
            [
                0,
                0,
                cmath.exp(-1j * (a + c) / 2) * math.cos(b / 2),
                -cmath.exp(1j * (a - c) / 2) * math.sin(b / 2),
            ],
            [
                0,
                0,
                cmath.exp(-1j * (a - c) / 2) * math.sin(b / 2),
                cmath.exp(1j * (a + c) / 2) * math.cos(b / 2),
            ],
        ]
    )


# ========================================================
#  General gates and observables
# ======================================================== 
Example #26
Source File: two_qubit_decompositions_test.py    From Cirq with Apache License 2.0 5 votes vote down vote up
def _random_single_partial_cz_effect():
    return cirq.dot(
        cirq.kron(cirq.testing.random_unitary(2),
                  cirq.testing.random_unitary(2)),
        np.diag([1, 1, 1, cmath.exp(2j * random.random() * np.pi)]),
        cirq.kron(cirq.testing.random_unitary(2),
                  cirq.testing.random_unitary(2))) 
Example #27
Source File: numpy_ops.py    From pennylane with Apache License 2.0 5 votes vote down vote up
def Rphi(phi):
    r"""One-qubit phase shift.

    Args:
        phi (float): phase shift angle
    Returns:
        array: unitary 2x2 phase shift matrix
    """
    return np.array([[1, 0], [0, cmath.exp(1j * phi)]]) 
Example #28
Source File: fsim_gate.py    From Cirq with Apache License 2.0 5 votes vote down vote up
def _pauli_expansion_(self) -> value.LinearDict[str]:
        if protocols.is_parameterized(self):
            return NotImplemented
        a = math.cos(self.theta)
        b = -1j * math.sin(self.theta)
        c = cmath.exp(-1j * self.phi)
        return value.LinearDict({
            'II': (1 + c) / 4 + a / 2,
            'IZ': (1 - c) / 4,
            'ZI': (1 - c) / 4,
            'ZZ': (1 + c) / 4 - a / 2,
            'XX': b / 2,
            'YY': b / 2,
        }) 
Example #29
Source File: two_qubit_decompositions_test.py    From Cirq with Apache License 2.0 5 votes vote down vote up
def _random_double_partial_cz_effect():
    return cirq.dot(
        cirq.kron(cirq.testing.random_unitary(2),
                  cirq.testing.random_unitary(2)),
        np.diag([1, 1, 1, cmath.exp(2j * random.random() * np.pi)]),
        cirq.kron(cirq.testing.random_unitary(2),
                  cirq.testing.random_unitary(2)),
        np.diag([1, 1, 1, cmath.exp(2j * random.random() * np.pi)]),
        cirq.kron(cirq.testing.random_unitary(2),
                  cirq.testing.random_unitary(2))) 
Example #30
Source File: fsim_gate.py    From Cirq with Apache License 2.0 5 votes vote down vote up
def _unitary_(self) -> Optional[np.ndarray]:
        if self._is_parameterized_():
            return None
        a = math.cos(self.theta)
        b = -1j * math.sin(self.theta)
        c = cmath.exp(-1j * self.phi)
        return np.array([
            [1, 0, 0, 0],
            [0, a, b, 0],
            [0, b, a, 0],
            [0, 0, 0, c],
        ])