Ejemplo n.º 1
0
def test_inverse_composite_diagram_info():

    class Gate(cirq.Gate):

        def _decompose_(self, qubits):
            return cirq.S.on(qubits[0])

        def num_qubits(self) -> int:
            return 1

    c = cirq.inverse(Gate())
    assert cirq.circuit_diagram_info(c, default=None) is None

    class Gate2(cirq.Gate):

        def _decompose_(self, qubits):
            return cirq.S.on(qubits[0])

        def num_qubits(self) -> int:
            return 1

        def _circuit_diagram_info_(self, args):
            return 's!'

    c = cirq.inverse(Gate2())
    assert cirq.circuit_diagram_info(c) == cirq.CircuitDiagramInfo(
        wire_symbols=('s!',), exponent=-1)
Ejemplo n.º 2
0
def obj_state(p_, A, WW):
    p, rs = p_[:15], p_[15:]
    
    B = iMPS([unitary_to_tensor(cirq.unitary(gate(p)))]).left_canonicalise()[0]
    U = Environment(tensor_to_unitary(A), 'U')
    U_ = Environment(tensor_to_unitary(B), 'U\'')
    
    R = state_gate(rs)
    #R = Environment(environment_to_unitary(r), 'R')
    L = Environment(put_env_on_right_site(environment_from_unitary(cirq.unitary(R)).conj().T), 'L')
    
    W = Environment(WW, 'W')
    
    qbs = cirq.LineQubit.range(5)
    C = cirq.Circuit.from_ops([R(*qbs[3:5]),
                               U(*qbs[2:4]),
                               U(*qbs[1:3]),
                               W(*qbs[2:4]),
                               L(*qbs[0:2]),
                               cirq.inverse(U_)(*qbs[1:3]),
                               cirq.inverse(U_)(*qbs[2:4]),
                               cirq.CNOT(*qbs[3:5]), cirq.H(qbs[3])])
    
    s = cirq.Simulator(dtype=np.complex128)
    return s.simulate(C).final_state
Ejemplo n.º 3
0
    def objective_function(self, params):        
        U_ = self.gate(params)
        U = self.u
        A = unitary_to_tensor(cirq.unitary(U))
        A_ = unitary_to_tensor(cirq.unitary(U_))
        
        _, r = Map(A,A_).right_fixed_point()
        
        R = Environment(put_env_on_left_site(r), 'R')
        L = Environment(put_env_on_right_site(r.conj().T), 'L')
        
        W = Environment(W, 'W')

        qbs = cirq.LineQubit.range(6)
        C = cirq.Circuit.from_ops([cirq.H(qbs[3]), cirq.CNOT(*qbs[3:5]),
                                   U(*qbs[2:4]),
                                   U(*qbs[1:3]),
                                   W(*qbs[2:4]),
                                   L(*qbs[0:2]),
                                   R(*qbs[4:]),
                                   cirq.inverse(U_)(*qbs[1:3]),
                                   cirq.inverse(U_)(*qbs[2:4]),
                                   cirq.CNOT(*qbs[3:5]), cirq.H(qbs[3])])

        s = cirq.Simulator(dtype=np.complex128)
        return -np.abs(s.simulate(C).final_state[0])*2
Ejemplo n.º 4
0
def obj(p_, A, WW):
    p, rs = p_[:15], p_[15:]
    
    B = iMPS([unitary_to_tensor(cirq.unitary(gate(p)))]).left_canonicalise()[0]

    U = Environment(tensor_to_unitary(A), 'U')
    U_ = Environment(tensor_to_unitary(B), 'U\'')

    E = Map(np.tensordot(WW, merge(A, A), [1, 0]), merge(B, B))
    x,r = E.right_fixed_point()
    x_,l = E.left_fixed_point()
    
    R = Environment(put_env_on_left_site(r), 'θR')
    L = Environment(put_env_on_right_site(r.conj().T), 'θL')
    
    W = Environment(WW, 'W')
    
    qbs = cirq.LineQubit.range(5)
    C = cirq.Circuit.from_ops([R(*qbs[3:5]),
                               U(*qbs[2:4]),
                               U(*qbs[1:3]),
                               W(*qbs[2:4]),
                               L(*qbs[0:2]),
                               cirq.inverse(U_)(*qbs[1:3]),
                               cirq.inverse(U_)(*qbs[2:4]),
                               cirq.CNOT(*qbs[3:5]), cirq.H(qbs[3])])
    
    s = cirq.Simulator(dtype=np.complex128)
    return -np.sqrt(np.abs(np.sqrt(2)*s.simulate(C).final_state[0]))
Ejemplo n.º 5
0
def test_pow_inverse():
    assert cirq.inverse(CRestricted, None) is None
    assert cirq.inverse(SCRestricted, None) is None
    assert cirq.pow(CRestricted, 1.5, None) is None
    assert cirq.pow(SCRestricted, 1.5, None) is None
    assert cirq.pow(CY, 1.5) == cirq.ControlledGate(cirq.Y**1.5)
    assert cirq.inverse(CY) == CY**-1 == CY
    assert cirq.inverse(SCY) == SCY**-1 == SCY
Ejemplo n.º 6
0
def test_reversible():
    assert (cirq.inverse(cirq.ControlledGate(cirq.S)) ==
            cirq.ControlledGate(cirq.S**-1))
    assert (cirq.inverse(cirq.ControlledGate(cirq.S, [q])) ==
            cirq.ControlledGate(cirq.S**-1, [q]))
    assert (cirq.inverse(cirq.ControlledGate(cirq.S,
                                             [q3])) == cirq.ControlledGate(
                                                 cirq.S**-1, [q3]))
def test_gate_inverse():
    i = dps_empty
    gate1 = cirq.PauliStringPhasorGate(i, exponent_neg=0.25)
    gate2 = cirq.PauliStringPhasorGate(i, exponent_neg=-0.25)
    gate3 = cirq.PauliStringPhasorGate(i, exponent_neg=sympy.Symbol('s'))
    gate4 = cirq.PauliStringPhasorGate(i, exponent_neg=-sympy.Symbol('s'))
    assert cirq.inverse(gate1) == gate2
    assert cirq.inverse(gate3, None) == gate4
Ejemplo n.º 8
0
def test_inverse():
    i = cirq.PauliString({})
    op1 = cirq.PauliStringPhasor(i, exponent_neg=0.25)
    op2 = cirq.PauliStringPhasor(i, exponent_neg=-0.25)
    op3 = cirq.PauliStringPhasor(i, exponent_neg=sympy.Symbol('s'))
    op4 = cirq.PauliStringPhasor(i, exponent_neg=-sympy.Symbol('s'))
    assert cirq.inverse(op1) == op2
    assert cirq.inverse(op3, None) == op4
Ejemplo n.º 9
0
def test_inverse():
    i = cirq.PauliString({})
    op1 = PauliStringPhasor(i, half_turns=0.25)
    op2 = PauliStringPhasor(i, half_turns=-0.25)
    op3 = PauliStringPhasor(i, half_turns=sympy.Symbol('s'))
    op4 = PauliStringPhasor(i, half_turns=-sympy.Symbol('s'))
    assert cirq.inverse(op1) == op2
    assert cirq.inverse(op3, None) == op4
Ejemplo n.º 10
0
def test_inverse():
    a, b, c = cirq.LineQubit.range(3)
    m = cirq.Moment([cirq.S(a), cirq.CNOT(b, c)])
    assert m**1 is m
    assert m**-1 == cirq.Moment([cirq.S(a)**-1, cirq.CNOT(b, c)])
    assert m**0.5 == cirq.Moment([cirq.T(a), cirq.CNOT(b, c)**0.5])
    assert cirq.inverse(m) == m**-1
    assert cirq.inverse(cirq.inverse(m)) == m
    assert cirq.inverse(cirq.Moment([cirq.measure(a)]), default=None) is None
Ejemplo n.º 11
0
def _apply_fold_mask(
    circuit: Circuit,
    num_folds_mask: List[int],
    squash_moments: Optional[bool] = True,
) -> Circuit:
    r"""Applies local unitary folding to the gates of the input circuit
    according to the input num_folds_mask.

    More precicely, G_j^\dag G_j is applied after the j_th gate G_j of
    the input circuit an integer number of times given by num_folds_mask[j].

    The gate ordering is equal to the one used in the `all_operations()`
    method of the :class:`cirq.Circuit` class: gates from earlier moments
    come first and gates within the same moment follow the order in which
    they were given to the moment's constructor.

    Args:
        circuit: The quantum circuit to fold.
        num_folds_mask: The list of integers indicating how many times
            the corresponding gates of 'circuit' should be folded.
        squash_moments: If True or None, all gates (including folded gates) are
            placed as early as possible in the circuit. If False, new moments
            are created for folded gates. This option only applies to QPROGRAM
            types which have a "moment" or "time" structure. Default is True.

    Returns: The folded quantum circuit.
    """
    _check_foldable(circuit)
    circ_copy = deepcopy(circuit)
    measurements = _pop_measurements(circ_copy)

    num_gates = len(list(circ_copy.all_operations()))
    if num_gates != len(num_folds_mask):
        raise ValueError(
            "The circuit and the folding mask have incompatible sizes."
            f" The number of gates is {num_gates}"
            f" but len(num_folds_mask) is {len(num_folds_mask)}.")

    folded_circuit = circ_copy[:0]
    if squash_moments:
        for op, num_folds in zip(circ_copy.all_operations(), num_folds_mask):
            folded_circuit.append([op] + num_folds * [inverse(op), op])
    else:
        mask_index = 0
        for moment in circ_copy:
            folded_moment = Circuit(moment)
            for op in moment:
                num_folds = num_folds_mask[mask_index]
                folded_moment.append(num_folds * [inverse(op), op])
                mask_index += 1
            # New folded gates are only squashed with respect to folded_moment
            # while folded_circuit is not squashed.
            folded_circuit.append(folded_moment)

    _append_measurements(folded_circuit, measurements)
    return folded_circuit
Ejemplo n.º 12
0
def test_inverse():
    q = cirq.NamedQubit('q')

    # If the gate isn't reversible, you get a type error.
    op0 = cirq.GateOperation(cirq.SingleQubitGate(), [q])
    assert cirq.inverse(op0, None) is None

    op1 = cirq.GateOperation(cirq.S, [q])
    assert cirq.inverse(op1) == op1**-1 == cirq.GateOperation(cirq.S**-1, [q])
    assert cirq.inverse(cirq.S).on(q) == cirq.inverse(cirq.S.on(q))
Ejemplo n.º 13
0
def test_default_qudit_inverse():
    class TestGate(cirq.Gate):
        def _qid_shape_(self):
            return (1, 2, 3)

        def _decompose_(self, qubits):
            return (cirq.X ** 0.1).on(qubits[1])

    assert cirq.qid_shape(cirq.inverse(TestGate(), None)) == (1, 2, 3)
    cirq.testing.assert_has_consistent_qid_shape(cirq.inverse(TestGate()))
Ejemplo n.º 14
0
def test_reversible():
    assert cirq.inverse(cirq.ControlledGate(cirq.S)) == cirq.ControlledGate(cirq.S ** -1)
    assert cirq.inverse(cirq.ControlledGate(cirq.S, num_controls=4)) == cirq.ControlledGate(
        cirq.S ** -1, num_controls=4
    )
    assert cirq.inverse(cirq.ControlledGate(cirq.S, control_values=[1])) == cirq.ControlledGate(
        cirq.S ** -1, control_values=[1]
    )
    assert cirq.inverse(cirq.ControlledGate(cirq.S, control_qid_shape=(3,))) == cirq.ControlledGate(
        cirq.S ** -1, control_qid_shape=(3,)
    )
Ejemplo n.º 15
0
def test_extrapolate():
    h = CExpZinGate(2)
    assert cirq.pow(h, 1.5) is not None
    assert cirq.inverse(h, None) is not None

    p = CExpZinGate(0.1)
    assert cirq.pow(p, 1.5) is not None
    assert cirq.inverse(p) is not None

    s = CExpZinGate(sympy.Symbol('a'))
    assert cirq.pow(s, 1.5) == CExpZinGate(sympy.Symbol('a') * 1.5)
    assert cirq.inverse(s) == CExpZinGate(-sympy.Symbol('a'))
Ejemplo n.º 16
0
def test_default_inverse():
    class TestGate(cirq.Gate):
        def _num_qubits_(self):
            return 3

        def _decompose_(self, qubits):
            return (cirq.X**0.1).on_each(*qubits)

    assert cirq.inverse(TestGate(), None) is not None
    cirq.testing.assert_has_consistent_qid_shape(cirq.inverse(TestGate()))
    cirq.testing.assert_has_consistent_qid_shape(
        cirq.inverse(TestGate().on(*cirq.LineQubit.range(3))))
Ejemplo n.º 17
0
def fold_global(
    circuit: QPROGRAM, scale_factor: float, **kwargs: Any
) -> QPROGRAM:
    """Returns a new circuit obtained by folding the global unitary of the
    input circuit.

    The returned folded circuit has a number of gates approximately equal to
    scale_factor * len(circuit).

    Args:
        circuit: Circuit to fold.
        scale_factor: Factor to scale the circuit by.

    Keyword Args:
        squash_moments (bool): If True, all gates (including folded gates) are
            placed as early as possible in the circuit. If False, new moments
            are created for folded gates. This option only applies to QPROGRAM
            types which have a "moment" or "time" structure. Default is True.
        return_mitiq (bool): If True, returns a mitiq circuit instead of
            the input circuit type (if different). Default is False.

    Returns:
        folded: the folded quantum circuit as a QPROGRAM.
    """
    _check_foldable(circuit)

    if not (scale_factor >= 1):
        raise ValueError("The scale factor must be a real number >= 1.")

    folded = deepcopy(circuit)
    measurements = _pop_measurements(folded)
    base_circuit = deepcopy(folded)

    # Determine the number of global folds and the final fractional scale
    num_global_folds, fraction_scale = divmod(scale_factor - 1, 2)
    # Do the global folds
    for _ in range(int(num_global_folds)):
        folded += Circuit(inverse(base_circuit), base_circuit)

    # Fold remaining gates until the scale is reached
    operations = list(base_circuit.all_operations())
    num_to_fold = int(round(fraction_scale * len(operations) / 2))

    if num_to_fold > 0:
        folded += Circuit(
            [inverse(operations[-num_to_fold:])], [operations[-num_to_fold:]]
        )

    _append_measurements(folded, measurements)
    if not (kwargs.get("squash_moments") is False):
        folded = squash_moments(folded)
    return folded
Ejemplo n.º 18
0
def test_runtime_types_of_rot_gates():
    for gate_type in [
            cirq.Rot11Gate, cirq.RotXGate, cirq.RotYGate, cirq.RotZGate
    ]:
        p = gate_type(half_turns=cirq.Symbol('a'))
        assert cirq.unitary(p, None) is None
        assert cirq.pow(p, 2, None) is None
        assert cirq.inverse(p, None) is None

        c = gate_type(half_turns=0.5)
        assert cirq.unitary(c, None) is not None
        assert cirq.pow(c, 2) is not None
        assert cirq.inverse(c) is not None
Ejemplo n.º 19
0
    def test_daggers_are_converted_to_inverses(self):
        # NOTE: We don't add this test case to EQUIVALENT_CIRCUITS, because
        # only Zquantum -> cirq conversion is supported.
        zquantum_circuit = _circuit.Circuit(
            [_builtin_gates.X.dagger(2),
             _builtin_gates.T.dagger(1)])
        cirq_circuit = cirq.Circuit(
            [cirq.inverse(cirq.X)(lq(2)),
             cirq.inverse(cirq.T)(lq(1))])
        converted = export_to_cirq(zquantum_circuit)

        assert converted == cirq_circuit, (
            f"Converted circuit:\n{converted}\n isn't equal "
            f"to\n{cirq_circuit}")
Ejemplo n.º 20
0
def test_runtime_types_of_rot_gates():
    for gate_type in [lambda p: cirq.CZPowGate(exponent=p),
                      lambda p: cirq.XPowGate(exponent=p),
                      lambda p: cirq.YPowGate(exponent=p),
                      lambda p: cirq.ZPowGate(exponent=p)]:
        p = gate_type(sympy.Symbol('a'))
        assert cirq.unitary(p, None) is None
        assert cirq.pow(p, 2, None) == gate_type(2 * sympy.Symbol('a'))
        assert cirq.inverse(p, None) == gate_type(-sympy.Symbol('a'))

        c = gate_type(0.5)
        assert cirq.unitary(c, None) is not None
        assert cirq.pow(c, 2) == gate_type(1)
        assert cirq.inverse(c) == gate_type(-0.5)
Ejemplo n.º 21
0
def evo_state(params, which, old_params, H, dt):
    assert len(params) == 30
    p2, p1 = np.split(params, 2)
    p2_, p1_ = np.split(old_params, 2)
    if which == 'energy':
        qbs = cirq.LineQubit.range(4)
        C = cirq.Circuit.from_ops([
            gate(p1_)(*qbs[2:]),
            gate(p2_)(*qbs[1:3]),
            gate(p2_)(*qbs[:2]),
            FullStateTensor(expm(-1j * H * dt / 2))(*qbs[1:3]),
            cirq.inverse(gate(p2))(*qbs[:2]),
            cirq.inverse(gate(p2))(*qbs[1:3]),
            cirq.inverse(gate(p1))(*qbs[2:])
        ])
        s = cirq.Simulator()
        return s.simulate(C).final_state
    elif which == 'v_purity':
        qbs = [[cirq.GridQubit(y, x) for x in range(2)] for y in range(2)]
        C = cirq.Circuit.from_ops([
            gate(p1)(*qbs[0][:2]),
            gate(p1)(*qbs[1][:2]),
            cirq.SWAP(*qbs[0][:2])
        ])
        s = cirq.Simulator()
        return s.simulate(C).final_state
    elif which == 'u_purity':
        qbs = [[cirq.GridQubit(y, x) for x in range(3)] for y in range(2)]
        C = cirq.Circuit.from_ops([
            gate(p1)(*qbs[0][1:]),
            gate(p2)(*qbs[0][:2]),
            gate(p1)(*qbs[1][1:]),
            gate(p2)(*qbs[1][:2]),
            cirq.SWAP(*qbs[0][:2]),
            cirq.SWAP(*qbs[0][1:])
        ])
        s = cirq.Simulator()
        return s.simulate(C).final_state
    elif which == 'uv_purity':
        qbs = cirq.LineQubit.range(5)
        C = cirq.Circuit.from_ops([
            gate(p1)(*qbs[3:]),
            gate(p2)(*qbs[2:4]),
            gate(p1)(*qbs[:2]),
            cirq.SWAP(*qbs[:2])
        ])
        s = cirq.Simulator()
        return s.simulate(C).final_state
Ejemplo n.º 22
0
def obj(p, A, WW):
    B = iMPS([unitary_to_tensor(cirq.unitary(gate(p)))]).left_canonicalise()[0]
    WW_ = np.eye(WW.shape[0])

    E = Map(np.tensordot(WW, merge(A, A), [1, 0]), merge(B, B))

    x, r = E.right_fixed_point()
    x_, l = E.left_fixed_point()
    l = r

    U = Environment(tensor_to_unitary(A), 'U')
    U_ = Environment(tensor_to_unitary(B), 'U\'')

    R = Environment(put_env_on_left_site(r), 'θR')
    left = put_env_on_right_site(l.conj().T)
    L = Environment(left, 'θL')

    W = Environment(WW, 'W')

    qbs = cirq.LineQubit.range(6)
    C = cirq.Circuit([
        cirq.H(qbs[3]),
        cirq.CNOT(*qbs[3:5]),
        U(*qbs[2:4]),
        U(*qbs[1:3]),
        W(*qbs[2:4]),
        L(*qbs[0:2]),
        R(*qbs[4:]),
        cirq.inverse(U_)(*qbs[1:3]),
        cirq.inverse(U_)(*qbs[2:4]),
        cirq.CNOT(*qbs[3:5]),
        cirq.H(qbs[3])
    ])
    #qbs = cirq.LineQubit.range(4)
    #normC = cirq.Circuit.from_ops([cirq.H(qbs[1]),
    #                               cirq.CNOT(*qbs[1:3]),
    #                               L(*qbs[:2]),
    #                               R(*qbs[-2:]),
    #                               cirq.CNOT(*qbs[1:3]),
    #                               cirq.H(qbs[1])
    #                               ])
    s = cirq.Simulator(dtype=np.complex128)
    ff = np.sqrt(
        2 * np.abs(s.simulate(C).final_state[0])
    )  #/np.abs(s.simulate(normC).final_state[0])), np.sqrt(np.abs(x[0]))
    #print(ff[0]-ff[1])
    #print(ff[0], ff[1])
    return -ff
Ejemplo n.º 23
0
def test_bogoliubov_transform_quadratic_hamiltonian_inverse_is_dagger(
        n_qubits, real, particle_conserving, atol):
    quad_ham = random_quadratic_hamiltonian(
        n_qubits,
        real=real,
        conserves_particle_number=particle_conserving,
        seed=46533)
    _, transformation_matrix, _ = quad_ham.diagonalizing_bogoliubov_transform()

    qubits = cirq.LineQubit.range(n_qubits)

    if transformation_matrix.shape == (n_qubits, n_qubits):
        daggered_transformation_matrix = transformation_matrix.T.conj()
    else:
        left_block = transformation_matrix[:, :n_qubits]
        right_block = transformation_matrix[:, n_qubits:]
        daggered_transformation_matrix = numpy.block(
            [left_block.T.conj(), right_block.T])

    circuit1 = cirq.Circuit(
        cirq.inverse(bogoliubov_transform(qubits, transformation_matrix)))

    circuit2 = cirq.Circuit(
        bogoliubov_transform(qubits, daggered_transformation_matrix))

    cirq.testing.assert_allclose_up_to_global_phase(circuit1.unitary(),
                                                    circuit2.unitary(),
                                                    atol=atol)
def test_inverse():
    with pytest.raises(TypeError):
        _ = cirq.inverse(cirq.measure(cirq.NamedQubit('q')))

    def rev_freeze(root):
        return cirq.freeze_op_tree(cirq.inverse(root))

    operations = [
        cirq.GateOperation(_FlipGate(i), [cirq.NamedQubit(str(i))])
        for i in range(10)
    ]
    expected = [
        cirq.GateOperation(_FlipGate(~i), [cirq.NamedQubit(str(i))])
        for i in range(10)
    ]

    # Just an item.
    assert rev_freeze(operations[0]) == expected[0]

    # Flat list.
    assert rev_freeze(operations) == tuple(expected[::-1])

    # Tree.
    assert (rev_freeze(
        (operations[1:5], operations[0],
         operations[5:])) == (tuple(expected[5:][::-1]), expected[0],
                              tuple(expected[1:5][::-1])))

    # Flattening after reversing is equivalent to reversing then flattening.
    t = (operations[1:5], operations[0], operations[5:])
    assert (tuple(cirq.flatten_op_tree(rev_freeze(t))) == tuple(
        rev_freeze(cirq.flatten_op_tree(t))))
Ejemplo n.º 25
0
    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))
Ejemplo n.º 26
0
def qft(*qubits: 'cirq.Qid',
        without_reverse: bool = False,
        inverse: bool = False) -> 'cirq.Operation':
    """The quantum Fourier transform.

    Transforms a qubit register from the computational basis to the frequency
    basis.

    The inverse quantum Fourier transform is `cirq.qft(*qubits)**-1` or
    equivalently `cirq.inverse(cirq.qft(*qubits))`.

    Args:
        qubits: The qubits to apply the qft to.
        without_reverse: When set, swap gates at the end of the qft are omitted.
            This reverses the qubit order relative to the standard qft effect,
            but makes the gate cheaper to apply.
        inverse: If set, the inverse qft is performed instead of the qft.
            Equivalent to calling `cirq.inverse` on the result, or raising it
            to the -1.

    Returns:
        A `cirq.Operation` applying the qft to the given qubits.
    """
    result = QuantumFourierTransformGate(
        len(qubits), without_reverse=without_reverse).on(*qubits)
    if inverse:
        result = cirq.inverse(result)
    return result
Ejemplo n.º 27
0
    def trotter_step(self,
                     qubits: Sequence[cirq.Qid],
                     time: float,
                     control_qubit: Optional[cirq.Qid] = None) -> cirq.OP_TREE:

        n_qubits = len(qubits)

        if not isinstance(control_qubit, cirq.Qid):
            raise TypeError('Control qudit must be specified.')

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

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

        # Rotate 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 the full time
        yield (rot11(rads=-self.orbital_energies[i] * time).on(
            control_qubit, qubits[i]) for i in range(n_qubits))

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

        # Apply phase from constant term
        yield cirq.rz(rads=-self.hamiltonian.constant * time).on(control_qubit)
def test_inverse():
    with pytest.raises(TypeError):
        _ = cirq.inverse(
            cirq.measure(cirq.NamedQubit('q')))

    def rev_freeze(root):
        return cirq.freeze_op_tree(cirq.inverse(root))

    operations = [
        cirq.GateOperation(_FlipGate(i), [cirq.NamedQubit(str(i))])
        for i in range(10)
    ]
    expected = [
        cirq.GateOperation(_FlipGate(~i), [cirq.NamedQubit(str(i))])
        for i in range(10)
    ]

    # Just an item.
    assert rev_freeze(operations[0]) == expected[0]

    # Flat list.
    assert rev_freeze(operations) == tuple(expected[::-1])

    # Tree.
    assert (
        rev_freeze((operations[1:5], operations[0], operations[5:])) ==
        (tuple(expected[5:][::-1]), expected[0],
         tuple(expected[1:5][::-1])))

    # Flattening after reversing is equivalent to reversing then flattening.
    t = (operations[1:5], operations[0], operations[5:])
    assert (
        tuple(cirq.flatten_op_tree(rev_freeze(t))) ==
        tuple(rev_freeze(cirq.flatten_op_tree(t))))
Ejemplo n.º 29
0
def sampled_bloch_vector_of(qubit, circuit, reps=1000000):
    """sampled_bloch_vector_of: get bloch vector of a 
    specified qubit by sampling. 

    :param qubit: qubit to sample bloch vector of 
    :param circuit: circuit to evaluate before sampling
    :param reps: number of measurements on each qubit
    """
    sim = cirq.Simulator()
    C = circuit.copy()
    C.append([cirq.measure(qubit, key='z')])
    meas = sim.run(C, repetitions=reps).measurements['z']
    z = array(list(map(int, meas))).mean()

    C = circuit.copy()
    C.append([
        cirq.inverse(cirq.S(qubit)),
        cirq.H(qubit),
        cirq.measure(qubit, key='y')
    ])
    meas = sim.run(C, repetitions=reps).measurements['y']
    y = array(list(map(int, meas))).mean()

    C = circuit.copy()
    C.append([cirq.H(qubit), cirq.measure(qubit, key='x')])
    meas = sim.run(C, repetitions=reps).measurements['x']
    x = array(list(map(int, meas))).mean()

    return -2 * array([x, y, z]) + 1
Ejemplo n.º 30
0
def test_frequency_space_gates():
    a, b, c = cirq.LineQubit.range(3)

    assert_url_to_circuit_returns('{"cols":[["QFT3"]]}',
                                  cirq.Circuit(cirq.QFT(a, b, c),))
    assert_url_to_circuit_returns(
        '{"cols":[["QFT†3"]]}', cirq.Circuit(cirq.inverse(cirq.QFT(a, b, c)),))

    assert_url_to_circuit_returns(
        '{"cols":[["PhaseGradient3"]]}',
        cirq.Circuit(
            cirq.PhaseGradientGate(num_qubits=3, exponent=0.5)(a, b, c),))
    assert_url_to_circuit_returns(
        '{"cols":[["PhaseUngradient3"]]}',
        cirq.Circuit(
            cirq.PhaseGradientGate(num_qubits=3, exponent=-0.5)(a, b, c),))

    t = sympy.Symbol('t')
    assert_url_to_circuit_returns(
        '{"cols":[["grad^t2"]]}',
        cirq.Circuit(
            cirq.PhaseGradientGate(num_qubits=2, exponent=2 * t)(a, b),))
    assert_url_to_circuit_returns(
        '{"cols":[["grad^t3"]]}',
        cirq.Circuit(
            cirq.PhaseGradientGate(num_qubits=3, exponent=4 * t)(a, b, c),))
    assert_url_to_circuit_returns(
        '{"cols":[["grad^-t3"]]}',
        cirq.Circuit(
            cirq.PhaseGradientGate(num_qubits=3, exponent=-4 * t)(a, b, c),))
Ejemplo n.º 31
0
def test_simplify_circuit_exponents():
    qreg = LineQubit.range(2)
    circuit = Circuit([H.on(qreg[0]), CNOT.on(*qreg), Z.on(qreg[1])])

    # Invert circuit
    inverse_circuit = cirq.inverse(circuit)
    inverse_repr = inverse_circuit.__repr__()
    inverse_qasm = inverse_circuit._to_qasm_output().__str__()

    # Expected circuit after simplification
    expected_inv = Circuit([Z.on(qreg[1]), CNOT.on(*qreg), H.on(qreg[0])])
    expected_repr = expected_inv.__repr__()
    expected_qasm = expected_inv._to_qasm_output().__str__()

    # Check inverse_circuit is logically equivalent to expected_inverse
    # but they have a different representation
    assert inverse_circuit == expected_inv
    assert inverse_repr != expected_repr
    assert inverse_qasm != expected_qasm

    # Simplify the circuit
    _simplify_circuit_exponents(inverse_circuit)

    # Check inverse_circuit has the expected simplified representation
    simplified_repr = inverse_circuit.__repr__()
    simplified_qasm = inverse_circuit._to_qasm_output().__str__()
    assert inverse_circuit == expected_inv
    assert simplified_repr == expected_repr
    assert simplified_qasm == expected_qasm
def test_works_with_basic_gates():
    a = cirq.NamedQubit('a')
    b = cirq.NamedQubit('b')

    basics = [cirq.X(a),
              cirq.Y(a)**0.5,
              cirq.Z(a),
              cirq.CZ(a, b)**-0.25,
              cirq.CNOT(a, b),
              cirq.H(b),
              cirq.SWAP(a, b)]
    assert list(cirq.inverse(basics)) == [
        cirq.SWAP(a, b),
        cirq.H(b),
        cirq.CNOT(a, b),
        cirq.CZ(a, b)**0.25,
        cirq.Z(a),
        cirq.Y(a)**-0.5,
        cirq.X(a),
    ]
 def rev_freeze(root):
     return cirq.freeze_op_tree(cirq.inverse(root))