Example #1
0
def test_dynamic_single_qubit_rotations():
    a, b, c = cirq.LineQubit.range(3)
    t = sympy.Symbol('t')

    # Dynamic single qubit rotations.
    assert_url_to_circuit_returns(
        '{"cols":[["X^t","Y^t","Z^t"],["X^-t","Y^-t","Z^-t"]]}',
        cirq.Circuit(
            cirq.X(a)**t,
            cirq.Y(b)**t,
            cirq.Z(c)**t,
            cirq.X(a)**-t,
            cirq.Y(b)**-t,
            cirq.Z(c)**-t,
        ))
    assert_url_to_circuit_returns(
        '{"cols":[["e^iXt","e^iYt","e^iZt"],["e^-iXt","e^-iYt","e^-iZt"]]}',
        cirq.Circuit(
            cirq.Rx(2 * sympy.pi * t).on(a),
            cirq.Ry(2 * sympy.pi * t).on(b),
            cirq.Rz(2 * sympy.pi * t).on(c),
            cirq.Rx(2 * sympy.pi * -t).on(a),
            cirq.Ry(2 * sympy.pi * -t).on(b),
            cirq.Rz(2 * sympy.pi * -t).on(c),
        ))
Example #2
0
 def U(i, ψ=None, χ=None, ϕ=None):
     """U: Random SU(2) element"""
     ψ = 2 * π * rand() if ψ is None else ψ
     χ = 2 * π * rand() if χ is None else χ
     φ = arcsin(sqrt(rand())) if ϕ is None else ϕ
     for g in [cirq.Rz(χ + ψ), cirq.Ry(2 * φ), cirq.Rz(χ - ψ)]:
         yield g(cirq.LineQubit(i))
Example #3
0
 def U(i):
     """U: Random SU(2) element"""
     ψ = 2 * π * rand()
     χ = 2 * π * rand()
     φ = arcsin(sqrt(rand()))
     for g in [cirq.Rz(χ + ψ), cirq.Ry(2 * φ), cirq.Rz(χ - ψ)]:
         yield g(cirq.LineQubit(i))
Example #4
0
def test_rxyz_exponent(theta, exp):
    def resolve(gate):
        return cirq.resolve_parameters(gate, {'theta': np.pi / 4}, {'exp': 1 / 4})

    assert resolve(cirq.Rx(rads=theta) ** exp) == resolve(cirq.Rx(rads=theta * exp))
    assert resolve(cirq.Ry(rads=theta) ** exp) == resolve(cirq.Ry(rads=theta * exp))
    assert resolve(cirq.Rz(rads=theta) ** exp) == resolve(cirq.Rz(rads=theta * exp))
Example #5
0
def cphase_symbols_to_sqrt_iswap(a, b, turns):
    """Version of cphase_to_sqrt_iswap that works with symbols.

    Note that the formulae contained below will need to be flattened
    into a sweep before serializing.
    """
    theta = sympy.Mod(turns, 2.0) * sympy.pi

    # -1 if theta > pi.  Adds a hacky fudge factor so theta=pi is not 0
    sign = sympy.sign(sympy.pi - theta + 1e-9)

    # For sign = 1: theta. For sign = -1, 2pi-theta
    theta_prime = (sympy.pi - sign * sympy.pi) + sign * theta

    phi = sympy.asin(np.sqrt(2) * sympy.sin(theta_prime / 4))
    xi = sympy.atan(sympy.tan(phi) / np.sqrt(2))

    yield cirq.Rz(sign * 0.5 * theta_prime).on(a)
    yield cirq.Rz(sign * 0.5 * theta_prime).on(b)
    yield cirq.Rx(xi).on(a)
    yield cirq.X(b)**(-sign * 0.5)
    yield SQRT_ISWAP_INV(a, b)
    yield cirq.Rx(-2 * phi).on(a)
    yield SQRT_ISWAP(a, b)
    yield cirq.Rx(xi).on(a)
    yield cirq.X(b)**(sign * 0.5)
    def trotter_step(
            self,
            qubits: Sequence[cirq.QubitId],
            time: float,
            control_qubit: Optional[cirq.QubitId] = None) -> cirq.OP_TREE:

        n_qubits = len(qubits)

        # Simulate the one-body terms for half of the full time
        yield (cirq.Rz(rads=-0.5 * self.orbital_energies[i] * time).on(
            qubits[i]) for i in range(n_qubits))

        # Rotate to the computational basis
        yield bogoliubov_transform(qubits, self.basis_change_matrix)

        # Simulate the two-body terms for the full time
        def two_body_interaction(p, q, a, b) -> cirq.OP_TREE:
            yield rot11(rads=-2 * self.hamiltonian.two_body[p, q] * time).on(
                a, b)

        yield swap_network(qubits, two_body_interaction)
        # The qubit ordering has been reversed
        qubits = qubits[::-1]

        # Rotate back to the basis in which the one-body term is diagonal
        yield cirq.inverse(
            bogoliubov_transform(qubits, self.basis_change_matrix))

        # Simulate the one-body terms for half of the full time
        yield (cirq.Rz(rads=-0.5 * self.orbital_energies[i] * time).on(
            qubits[i]) for i in range(n_qubits))
Example #7
0
def test_str():
    assert str(cirq.X) == 'X'
    assert str(cirq.X**0.5) == 'X**0.5'
    assert str(cirq.Rx(np.pi)) == 'Rx(π)'
    assert str(cirq.Rx(0.5 * np.pi)) == 'Rx(0.5π)'
    assert str(cirq.XPowGate(
        global_shift=-0.25)) == 'XPowGate(exponent=1.0, global_shift=-0.25)'

    assert str(cirq.Z) == 'Z'
    assert str(cirq.Z**0.5) == 'S'
    assert str(cirq.Z**0.125) == 'Z**0.125'
    assert str(cirq.Rz(np.pi)) == 'Rz(π)'
    assert str(cirq.Rz(1.4 * np.pi)) == 'Rz(1.4π)'
    assert str(cirq.ZPowGate(
        global_shift=0.25)) == 'ZPowGate(exponent=1.0, global_shift=0.25)'

    assert str(cirq.S) == 'S'
    assert str(cirq.S**-1) == 'S**-1'
    assert str(cirq.T) == 'T'
    assert str(cirq.T**-1) == 'T**-1'

    assert str(cirq.Y) == 'Y'
    assert str(cirq.Y**0.5) == 'Y**0.5'
    assert str(cirq.Ry(np.pi)) == 'Ry(π)'
    assert str(cirq.Ry(3.14 * np.pi)) == 'Ry(3.14π)'
    assert str(cirq.YPowGate(
        exponent=2,
        global_shift=-0.25)) == 'YPowGate(exponent=2, global_shift=-0.25)'

    assert str(cirq.CX) == 'CNOT'
    assert str(cirq.CNOT**0.5) == 'CNOT**0.5'
Example #8
0
    def __init__(self, path: list, test_type: BellTestType, add_measurements,
                 num_shots):
        super().__init__()

        qubit_a = path[0]
        qubit_b = path[-1]

        self.qubit_a = qubit_a
        self.qubit_b = qubit_b
        self.path = path
        self.test_type = test_type
        self.add_measurements = add_measurements
        self.num_shots = num_shots

        # Build the circuit
        _path = [cirq.GridQubit(0, i) for i in path]
        _qubit_a, _qubit_b = _path[0], _path[-1]

        circuit = cirq.Circuit()

        circuit.append(cirq.X(_qubit_a))
        circuit.append(cirq.X(_qubit_b))
        circuit.append(cirq.H(_qubit_a))

        # CNOT along path
        for (_x, _y) in zip(_path[:-2], _path[1:-1]):
            circuit.append(cirq.H(_y))
            circuit.append(cirq.CZ(_x, _y))
            circuit.append(cirq.H(_y))

        # CNOT the last pair
        circuit.append(cirq.H(_qubit_b))
        circuit.append(cirq.CZ(_qubit_a, _qubit_b))
        circuit.append(cirq.H(_qubit_b))

        # undo CNOT along path
        for (_x, _y) in reversed(list(zip(_path[:-2], _path[1:-1]))):
            circuit.append(cirq.H(_y))
            circuit.append(cirq.CZ(_x, _y))
            circuit.append(cirq.H(_y))

        # measurement directions
        angle_a, angle_b = test_type.value
        if angle_a != 0:
            circuit.append(cirq.Rz(angle_a)(_qubit_a))
        if angle_b != 0:
            circuit.append(cirq.Rz(angle_b)(_qubit_b))

        # final hadamards
        circuit.append(cirq.H(_qubit_a))
        circuit.append(cirq.H(_qubit_b))

        # measurements
        if add_measurements:
            circuit.append(cirq.measure(_qubit_a, key="A"))
            circuit.append(cirq.measure(_qubit_b, key="B"))

        # store the resulting circuit
        self.circuit = circuit
def apply_C_unitary(length, gamma):
    # Apply the compute --> rotate --> uncompute  method to change the phase of a specific computational basis state
    for j in set_edges:
        yield cirq.CNOT.on(cirq.GridQubit(0, j.start_node),
                           cirq.GridQubit(0, j.end_node))
        yield cirq.Rz((-1 * gamma)).on(cirq.GridQubit(0, j.end_node))
        yield cirq.CNOT.on(cirq.GridQubit(0, j.start_node),
                           cirq.GridQubit(0, j.end_node))
        yield cirq.Rz((-1 * gamma)).on(work_qubit)
Example #10
0
def apply_C_unitary(length, gamma):
    # Apply the compute --> rotate --> uncompute  method to change the phase of a specific computational basis state

    for i in the_search:
        for j in range (0, len(i)-1):
            yield cirq.CNOT.on(cirq.GridQubit(0, i[j]), cirq.GridQubit(0, i[j+1]))
            yield cirq.Rz((-1*gamma)).on(cirq.GridQubit(0, i[(j+1)]))
            yield cirq.CNOT.on(cirq.GridQubit(0, i[j]), cirq.GridQubit(0, i[(j+1)]))
            yield cirq.Rz((-1*gamma)).on(work_qubit)
Example #11
0
def _gen_single_bit_rotation_problem(bit, symbols):
    """Generate a toy problem on 1 qubit."""
    starting_state = np.random.uniform(0, 2 * np.pi, 3)
    circuit = cirq.Circuit(
        cirq.Rx(starting_state[0])(bit),
        cirq.Ry(starting_state[1])(bit),
        cirq.Rz(starting_state[2])(bit),
        cirq.Rz(symbols[2])(bit),
        cirq.Ry(symbols[1])(bit),
        cirq.Rx(symbols[0])(bit))

    return circuit
Example #12
0
def test_gate_with_custom_names():
    q0, q1, q2, q3 = cirq.LineQubit.range(4)
    gate = cirq.BooleanHamiltonianGate(['a', 'b'], ['a'], 0.1)
    assert cirq.decompose(gate.on(q0, q1)) == [cirq.Rz(rads=-0.05).on(q0)]
    assert cirq.decompose_once_with_qubits(gate, (q0, q1)) == [cirq.Rz(rads=-0.05).on(q0)]
    assert cirq.decompose(gate.on(q2, q3)) == [cirq.Rz(rads=-0.05).on(q2)]
    assert cirq.decompose_once_with_qubits(gate, (q2, q3)) == [cirq.Rz(rads=-0.05).on(q2)]

    with pytest.raises(ValueError, match='Wrong number of qubits'):
        gate.on(q2)
    with pytest.raises(ValueError, match='Wrong shape of qids'):
        gate.on(q0, cirq.LineQid(1, 3))
Example #13
0
    def trotter_step(
            self,
            qubits: Sequence[cirq.Qid],
            time: float,
            control_qubit: Optional[cirq.Qid]=None
            ) -> cirq.OP_TREE:

        n_qubits = len(qubits)

        # Change to the basis in which the one-body term is diagonal
        yield bogoliubov_transform(
                qubits, self.one_body_basis_change_matrix.T.conj())

        # Simulate the one-body terms.
        for p in range(n_qubits):
            yield cirq.Rz(rads=
                    -self.one_body_energies[p] * time
                    ).on(qubits[p])

        # Simulate each singular vector of the two-body terms.
        prior_basis_matrix = self.one_body_basis_change_matrix

        for j in range(len(self.eigenvalues)):

            # Get the two-body coefficients and basis change matrix.
            two_body_coefficients = self.scaled_density_density_matrices[j]
            basis_change_matrix = self.basis_change_matrices[j]

            # Merge previous basis change matrix with the inverse of the
            # current one
            merged_basis_change_matrix = numpy.dot(prior_basis_matrix,
                                                   basis_change_matrix.T.conj())
            yield bogoliubov_transform(qubits, merged_basis_change_matrix)

            # Simulate the off-diagonal two-body terms.
            yield swap_network(
                    qubits,
                    lambda p, q, a, b: rot11(rads=
                        -2 * two_body_coefficients[p, q] * time).on(a, b))
            qubits = qubits[::-1]

            # Simulate the diagonal two-body terms.
            for p in range(n_qubits):
                yield cirq.Rz(rads=
                        -two_body_coefficients[p, p] * time
                        ).on(qubits[p])

            # Update prior basis change matrix
            prior_basis_matrix = basis_change_matrix

        # Undo final basis transformation
        yield bogoliubov_transform(qubits, prior_basis_matrix)
Example #14
0
    def test_parametrize(self):
        """Tests that parametrize yields the correct queue of operations."""

        operation = CirqOperation(
            lambda a, b, c:
            [cirq.X, cirq.Ry(a),
             cirq.Rx(b), cirq.Z,
             cirq.Rz(c)])
        operation.parametrize(0.1, 0.2, 0.3)

        assert operation.parametrized_cirq_gates[0] == cirq.X
        assert operation.parametrized_cirq_gates[1] == cirq.Ry(0.1)
        assert operation.parametrized_cirq_gates[2] == cirq.Rx(0.2)
        assert operation.parametrized_cirq_gates[3] == cirq.Z
        assert operation.parametrized_cirq_gates[4] == cirq.Rz(0.3)
Example #15
0
def main():
    """
    Simulates HHL with matrix input, and outputs Pauli observables of the
    resulting qubit state |x>.
    Expected observables are calculated from the expected solution |x>.
    """

    # Eigendecomposition:
    # >>> import numpy as np
    # >>> x, y = np.linalg.eigh(A) # Eigendecomposition for a complex Hermitian matrix.
    # >>> [z for z in zip(list(x.astype(np.float32)), list(np.transpose(y)))]
    # [(0.34899944, array([-0.23681357+0.j,  0.23727026-0.94213702j])),
    #  (4.5370007,  array([-0.97155511+0.j, -0.05783389+0.229643j]))]
    # |b> = (0.64510-0.47848j, 0.35490-0.47848j)
    # |x> = (-0.0662724-0.214548j, 0.784392-0.578192j)
    A = np.array([[4.30213466 - 6.01593490e-08j, 0.23531802 + 9.34386156e-01j],
                  [0.23531882 - 9.34388383e-01j,
                   0.58386534 + 6.01593489e-08j]])
    t = 0.358166 * math.pi
    register_size = 4
    input_prep_gates = [cirq.Rx(1.276359), cirq.Rz(1.276359)]
    expected = (0.144130, 0.413217, -0.899154)

    # Set C to be the smallest eigenvalue that can be represented by the
    # circuit.
    C = 2 * math.pi / (2**register_size * t)

    # Simulate circuit
    print("Expected observable outputs:")
    print("X =", expected[0])
    print("Y =", expected[1])
    print("Z =", expected[2])
    print("Actual: ")
    simulate(hhl_circuit(A, C, t, register_size, *input_prep_gates))
Example #16
0
    def test_pyquil2cirq(self):
        qprog = pyquil.quil.Program().inst(pyquil.gates.X(0),
                                           pyquil.gates.T(1),
                                           pyquil.gates.RZ(0.1, 3),
                                           pyquil.gates.CNOT(0, 1),
                                           pyquil.gates.SWAP(0, 1),
                                           pyquil.gates.CZ(1, 0))

        circuit = pyquil2cirq(qprog)
        qubits = [cirq.GridQubit(i, 0) for i in qprog.get_qubits()]

        gates = [
            cirq.X(qubits[0]),
            cirq.T(qubits[1]),
            cirq.Rz(rads=0.1)(qubits[2]),
            cirq.CNOT(qubits[0], qubits[1]),
            cirq.SWAP(qubits[0], qubits[1]),
            cirq.CZ(qubits[1], qubits[0])
        ]

        ref_circuit = cirq.Circuit()
        ref_circuit.append(gates,
                           strategy=cirq.circuits.InsertStrategy.EARLIEST)

        # Get the unitary matrix for the circuit
        U = circuit.unitary()

        # Get the unitary matrix for the reference circuit
        U_ref = ref_circuit.unitary()

        # Check that the matrices are identical to within a global phase. See J. Chem. Phys. 134, 144112 (2011).
        self.assertTrue(compare_unitary(U, U_ref))
Example #17
0
def main():
    """
    Simulates HHL with matrix input, and outputs Pauli observables of the
    resulting qubit state |x>.
    Expected observables are calculated from the expected solution |x>.
    """

    # Eigendecomposition:
    #   (4.537, [-0.971555, -0.0578339+0.229643j])
    #   (0.349, [-0.236813, 0.237270-0.942137j])
    # |b> = (0.64510-0.47848j, 0.35490-0.47848j)
    # |x> = (-0.0662724-0.214548j, 0.784392-0.578192j)
    A = np.array([[4.30213466-6.01593490e-08j,
                   0.23531802+9.34386156e-01j],
                  [0.23531882-9.34388383e-01j,
                   0.58386534+6.01593489e-08j]])
    t = 0.358166*math.pi
    register_size = 4
    input_prep_gates = [cirq.Rx(1.276359), cirq.Rz(1.276359)]
    expected = (0.144130, 0.413217, -0.899154)

    # Set C to be the smallest eigenvalue that can be represented by the
    # circuit.
    C = 2*math.pi / (2**register_size * t)

    # Simulate circuit
    print("Expected observable outputs:")
    print("X =", expected[0])
    print("Y =", expected[1])
    print("Z =", expected[2])
    print("Actual: ")
    simulate(hhl_circuit(A, C, t, register_size, *input_prep_gates))
    def trotter_step(
            self,
            qubits: Sequence[cirq.QubitId],
            time: float,
            control_qubit: Optional[cirq.QubitId] = None) -> cirq.OP_TREE:

        n_qubits = len(qubits)

        # Apply one- and two-body interactions for the full time
        def one_and_two_body_interaction(p, q, a, b) -> cirq.OP_TREE:
            yield CRxxyy(self.hamiltonian.one_body[p, q].real * time).on(
                control_qubit, a, b)
            yield CRyxxy(self.hamiltonian.one_body[p, q].imag * time).on(
                control_qubit, a, b)
            yield rot111(-2 * self.hamiltonian.two_body[p, q] * time).on(
                control_qubit, a, b)

        yield swap_network(qubits,
                           one_and_two_body_interaction,
                           fermionic=True)
        qubits = qubits[::-1]

        # Apply one-body potential for the full time
        yield (rot11(rads=-self.hamiltonian.one_body[i, i].real * time).on(
            control_qubit, qubits[i]) for i in range(n_qubits))

        # Apply phase from constant term
        yield cirq.Rz(rads=-self.hamiltonian.constant * time).on(control_qubit)
Example #19
0
def _gaussian_basis_change(
        qubits: Sequence[cirq.QubitId], transformation_matrix: numpy.ndarray,
        initially_occupied_orbitals: Optional[Sequence[int]]) -> cirq.OP_TREE:
    n_qubits = len(qubits)

    # Rearrange the transformation matrix because the OpenFermion routine
    # expects it to describe annihilation operators rather than creation
    # operators
    left_block = transformation_matrix[:, :n_qubits]
    right_block = transformation_matrix[:, n_qubits:]
    transformation_matrix = numpy.block(
        [numpy.conjugate(right_block),
         numpy.conjugate(left_block)])

    decomposition, left_decomposition, _, left_diagonal = (
        fermionic_gaussian_decomposition(transformation_matrix))

    if (initially_occupied_orbitals is not None
            and len(initially_occupied_orbitals) == 0):
        # Starting with the vacuum state yields additional symmetry
        circuit_description = list(reversed(decomposition))
    else:
        if initially_occupied_orbitals is None:
            # The initial state is not a computational basis state so the
            # phases left on the diagonal in the Givens decomposition matter
            yield (cirq.Rz(rads=numpy.angle(left_diagonal[j])).on(qubits[j])
                   for j in range(n_qubits))
        circuit_description = list(reversed(decomposition +
                                            left_decomposition))

    yield _ops_from_givens_rotations_circuit_description(
        qubits, circuit_description)
Example #20
0
def _slater_basis_change(
        qubits: Sequence[cirq.QubitId], transformation_matrix: numpy.ndarray,
        initially_occupied_orbitals: Optional[Sequence[int]]) -> cirq.OP_TREE:
    n_qubits = len(qubits)

    if initially_occupied_orbitals is None:
        decomposition, diagonal = givens_decomposition_square(
            transformation_matrix)
        circuit_description = list(reversed(decomposition))
        # The initial state is not a computational basis state so the
        # phases left on the diagonal in the decomposition matter
        yield (cirq.Rz(rads=numpy.angle(diagonal[j])).on(qubits[j])
               for j in range(n_qubits))
    else:
        initially_occupied_orbitals = cast(Sequence[int],
                                           initially_occupied_orbitals)
        transformation_matrix = transformation_matrix[list(
            initially_occupied_orbitals)]
        n_occupied = len(initially_occupied_orbitals)
        # Flip bits so that the first n_occupied are 1 and the rest 0
        initially_occupied_orbitals_set = set(initially_occupied_orbitals)
        yield (cirq.X(qubits[j]) for j in range(n_qubits)
               if (j < n_occupied) != (j in initially_occupied_orbitals_set))
        circuit_description = slater_determinant_preparation_circuit(
            transformation_matrix)

    yield _ops_from_givens_rotations_circuit_description(
        qubits, circuit_description)
Example #21
0
def main():
    """
    HHL을 행렬 입력과 결과 큐비트 상태인 |x>의 파울리 측정 출력을 시뮬레이션하기.
    기대되는 해 |x>로 부터 기대되는 관측량을 계산합니다.
    """

    # 고유값분해 결과:
    # >>> import numpy as np
    # >>> x, y = np.linalg.eig(A)
    # >>> [z for z in zip(list(x.astype(np.float32)), list(y))]
    # [(4.537, array([ 0.9715551 +0.j        , -0.05783371-0.22964251j])),
    #  (0.349, array([0.05783391-0.22964302j, 0.97155524+0.j        ]))]
    # |b> = (0.64510-0.47848j, 0.35490-0.47848j)
    # |x> = (-0.0662724-0.214548j, 0.784392-0.578192j)
    A = np.array([[4.30213466 - 6.01593490e-08j, 0.23531802 + 9.34386156e-01j],
                  [0.23531882 - 9.34388383e-01j,
                   0.58386534 + 6.01593489e-08j]])
    t = 0.358166 * math.pi
    register_size = 4
    input_prep_gates = [cirq.Rx(1.276359), cirq.Rz(1.276359)]
    expected = (0.144130, 0.413217, -0.899154)

    # C를 회로에서 표현가능한 최소의 고유값에 맞춥니다.
    C = 2 * math.pi / (2**register_size * t)

    # 회로를 시뮬레이션합니다.
    print("Expected observable outputs:")
    print("X =", expected[0])
    print("Y =", expected[1])
    print("Z =", expected[2])
    print("Actual: ")
    simulate(hhl_circuit(A, C, t, register_size, *input_prep_gates))
Example #22
0
def test_repr():
    assert repr(cirq.X) == 'cirq.X'
    assert repr(cirq.X**0.5) == '(cirq.X**0.5)'

    assert repr(cirq.Z) == 'cirq.Z'
    assert repr(cirq.Z**0.5) == 'cirq.S'
    assert repr(cirq.Z**0.25) == 'cirq.T'
    assert repr(cirq.Z**0.125) == '(cirq.Z**0.125)'

    assert repr(cirq.S) == 'cirq.S'
    assert repr(cirq.S**-1) == '(cirq.S**-1)'
    assert repr(cirq.T) == 'cirq.T'
    assert repr(cirq.T**-1) == '(cirq.T**-1)'

    assert repr(cirq.Y) == 'cirq.Y'
    assert repr(cirq.Y**0.5) == '(cirq.Y**0.5)'

    assert repr(cirq.CNOT) == 'cirq.CNOT'
    assert repr(cirq.CNOT**0.5) == '(cirq.CNOT**0.5)'

    cirq.testing.assert_equivalent_repr(cirq.X**(sympy.Symbol('a') / 2 -
                                                 sympy.Symbol('c') * 3 + 5))
    cirq.testing.assert_equivalent_repr(cirq.Rx(rads=sympy.Symbol('theta')))
    cirq.testing.assert_equivalent_repr(cirq.Ry(rads=sympy.Symbol('theta')))
    cirq.testing.assert_equivalent_repr(cirq.Rz(rads=sympy.Symbol('theta')))

    # There should be no floating point error during initialization, and repr
    # should be using the "shortest decimal value closer to X than any other
    # floating point value" strategy, as opposed to the "exactly value in
    # decimal" strategy.
    assert repr(cirq.CZ**0.2) == '(cirq.CZ**0.2)'
Example #23
0
def test_rxyz_circuit_diagram():
    q = cirq.NamedQubit('q')

    cirq.testing.assert_has_diagram(
        cirq.Circuit.from_ops(
            cirq.Rx(np.pi).on(q),
            cirq.Rx(-np.pi).on(q),
            cirq.Rx(-np.pi + 0.00001).on(q),
            cirq.Rx(-np.pi - 0.00001).on(q),
            cirq.Rx(3*np.pi).on(q),
            cirq.Rx(7*np.pi/2).on(q),
            cirq.Rx(9*np.pi/2 + 0.00001).on(q),
        ), """
q: ───Rx(π)───Rx(-π)───Rx(-π)───Rx(-π)───Rx(-π)───Rx(-0.5π)───Rx(0.5π)───
    """)

    cirq.testing.assert_has_diagram(
        cirq.Circuit.from_ops(
            cirq.Rx(np.pi).on(q),
            cirq.Rx(np.pi/2).on(q),
            cirq.Rx(-np.pi + 0.00001).on(q),
            cirq.Rx(-np.pi - 0.00001).on(q),
        ), """
q: ---Rx(pi)---Rx(0.5pi)---Rx(-pi)---Rx(-pi)---
        """,
        use_unicode_characters=False)

    cirq.testing.assert_has_diagram(
        cirq.Circuit.from_ops(
            cirq.Ry(np.pi).on(q),
            cirq.Ry(-np.pi).on(q),
            cirq.Ry(3 * np.pi).on(q),
            cirq.Ry(9*np.pi/2).on(q),
        ), """
q: ───Ry(π)───Ry(-π)───Ry(-π)───Ry(0.5π)───
    """)

    cirq.testing.assert_has_diagram(
        cirq.Circuit.from_ops(
            cirq.Rz(np.pi).on(q),
            cirq.Rz(-np.pi).on(q),
            cirq.Rz(3 * np.pi).on(q),
            cirq.Rz(9*np.pi/2).on(q),
            cirq.Rz(9*np.pi/2 + 0.00001).on(q),
        ), """
q: ───Rz(π)───Rz(-π)───Rz(-π)───Rz(0.5π)───Rz(0.5π)───
    """)
Example #24
0
def test_deprecated_rxyz_rotations(rads):
    with capture_logging():
        assert np.all(
            cirq.unitary(cirq.Rx(rads)) == cirq.unitary(cirq.rx(rads)))
        assert np.all(
            cirq.unitary(cirq.Ry(rads)) == cirq.unitary(cirq.ry(rads)))
        assert np.all(
            cirq.unitary(cirq.Rz(rads)) == cirq.unitary(cirq.rz(rads)))
def test_with_custom_names():
    q0, q1, q2, q3 = cirq.LineQubit.range(4)
    original_op = cirq.BooleanHamiltonian(
        {
            'a': q0,
            'b': q1
        },
        ['a'],
        0.1,
    )
    assert cirq.decompose(original_op) == [cirq.Rz(rads=-0.05).on(q0)]

    renamed_op = original_op.with_qubits(q2, q3)
    assert cirq.decompose(renamed_op) == [cirq.Rz(rads=-0.05).on(q2)]

    with pytest.raises(ValueError,
                       match='Length of replacement qubits must be the same'):
        original_op.with_qubits(q2)
Example #26
0
def adjoint_integer_increment_phase(circuit, increment, target):
    """
    The adjoint version of integer_increment_phase.
    """

    d = len(target)
    for i in range(d - 1, -1, -1):
        y = math.pi * increment / (2**(d - 1 - i))
        circuit.append(cirq.Rz(-y).on(target[i]))
Example #27
0
def cphase_to_sqrt_iswap(a, b, turns):
    """Implement a C-Phase gate using two sqrt ISWAP gates and single-qubit
    operations. The circuit is equivalent to cirq.CZPowGate(exponent=turns).

    Output unitary:
    [1   0   0   0],
    [0   1   0   0],
    [0   0   1   0],
    [0   0   0   e^{i turns pi}].

    Args:
        a: the first qubit
        b: the second qubit
        turns: Exponent specifying the evolution time in number of rotations.
    """
    theta = (turns % 2) * np.pi
    if 0 <= theta <= np.pi:
        sign = 1.
        theta_prime = theta
    elif np.pi < theta < 2 * np.pi:
        sign = -1.
        theta_prime = 2 * np.pi - theta

    if np.isclose(theta, np.pi):
        # If we are close to pi, just set values manually to avoid possible
        # numerical errors with arcsin of greater than 1.0 (Ahem, Windows).
        phi = np.pi / 2
        xi = np.pi / 2
    else:
        phi = np.arcsin(np.sqrt(2) * np.sin(theta_prime / 4))
        xi = np.arctan(np.tan(phi) / np.sqrt(2))

    yield cirq.Rz(sign * 0.5 * theta_prime).on(a)
    yield cirq.Rz(sign * 0.5 * theta_prime).on(b)
    yield cirq.Rx(xi).on(a)
    yield cirq.X(b)**(-sign * 0.5)
    yield SQRT_ISWAP_INV(a, b)
    yield cirq.Rx(-2 * phi).on(a)
    yield SQRT_ISWAP(a, b)

    yield cirq.Rx(xi).on(a)
    yield cirq.X(b)**(sign * 0.5)
    # Corrects global phase
    yield cirq.GlobalPhaseOperation(np.exp(sign * theta_prime * 0.25j))
Example #28
0
    def test_apply(self):
        """Tests that the operations in the queue are correctly applied."""

        operation = CirqOperation(
            lambda a, b, c:
            [cirq.X, cirq.Ry(a),
             cirq.Rx(b), cirq.Z,
             cirq.Rz(c)])
        operation.parametrize(0.1, 0.2, 0.3)

        qubit = cirq.LineQubit(1)

        gate_applications = list(operation.apply(qubit))

        assert gate_applications[0] == cirq.X.on(qubit)
        assert gate_applications[1] == cirq.Ry(0.1).on(qubit)
        assert gate_applications[2] == cirq.Rx(0.2).on(qubit)
        assert gate_applications[3] == cirq.Z.on(qubit)
        assert gate_applications[4] == cirq.Rz(0.3).on(qubit)
Example #29
0
 def rot(qubit, params):
     """Helper function to return an arbitrary rotation of the form
     R = Rz(params[2]) * Ry(params[1]) * Rx(params[0])
     on the qubit.
     """
     rx = cirq.Rx(rads=params[0])
     ry = cirq.Ry(rads=params[1])
     rz = cirq.Rz(rads=params[2])
     
     yield (rx(qubit), ry(qubit), rz(qubit))
Example #30
0
def controlled_adjoint_integer_increment_phase(circuit, control_list,
                                               increment, target):
    """
    The adjoint version of controlled_integer_increment_phase.
    """

    d = len(target)
    for i in range(d - 1, -1, -1):
        y = math.pi * increment / (2**(d - 1 - i))
        circuit.append(cirq.Rz(-y).on(target[i]).controlled_by(*control_list))