Beispiel #1
0
def test_simple_circuits_to_unitary_matrix():
    a = cirq.NamedQubit('a')
    b = cirq.NamedQubit('b')

    # Phase parity.
    c = Circuit.from_ops(cirq.CNOT(a, b), cirq.Z(b), cirq.CNOT(a, b))
    m = c.to_unitary_matrix()
    cirq.testing.assert_allclose_up_to_global_phase(m,
                                                    np.array([
                                                        [1, 0, 0, 0],
                                                        [0, -1, 0, 0],
                                                        [0, 0, -1, 0],
                                                        [0, 0, 0, 1],
                                                    ]),
                                                    atol=1e-8)

    # 2-qubit matrix matches when qubits in order.
    for expected in [np.diag([1, 1j, -1, -1j]), cirq.CNOT.matrix()]:

        class Passthrough(cirq.KnownMatrixGate):
            def matrix(self):
                return expected

        c = Circuit.from_ops(Passthrough()(a, b))
        m = c.to_unitary_matrix()
        cirq.testing.assert_allclose_up_to_global_phase(m, expected)
Beispiel #2
0
def test_text_diagram_jupyter():
    a = cirq.NamedQubit('a')
    b = cirq.NamedQubit('b')
    c = cirq.NamedQubit('c')
    circuit = Circuit.from_ops(
        (cirq.CNOT(a, b), cirq.CNOT(b, c), cirq.CNOT(c, a)) * 50)
    text_expected = circuit.to_text_diagram()

    # Test Jupyter console output from
    class FakePrinter:
        def __init__(self):
            self.text_pretty = ''

        def text(self, to_print):
            self.text_pretty += to_print

    p = FakePrinter()
    circuit._repr_pretty_(p, False)
    assert p.text_pretty == text_expected

    # Test cycle handling
    p = FakePrinter()
    circuit._repr_pretty_(p, True)
    assert p.text_pretty == 'Circuit(...)'

    # Test Jupyter notebook html output
    text_html = circuit._repr_html_()
    # Don't enforce specific html surrounding the diagram content
    assert text_expected in text_html
Beispiel #3
0
def test_to_text_diagram_multi_qubit_gate():
    q1 = cirq.NamedQubit('(0, 0)')
    q2 = cirq.NamedQubit('(0, 1)')
    q3 = cirq.NamedQubit('(0, 2)')
    c = Circuit.from_ops(cirq.measure(q1, q2, q3, key='msg'))
    assert c.to_text_diagram().strip() == """
(0, 0): ───M───
           │
(0, 1): ───M───
           │
(0, 2): ───M───
    """.strip()
    assert c.to_text_diagram(use_unicode_characters=False).strip() == """
(0, 0): ---M---
           |
(0, 1): ---M---
           |
(0, 2): ---M---
    """.strip()
    assert c.to_text_diagram(transpose=True).strip() == """
(0, 0) (0, 1) (0, 2)
│      │      │
M──────M──────M
│      │      │
    """.strip()
Beispiel #4
0
def test_are_all_measurements_terminal():
    a = cirq.QubitId()
    b = cirq.QubitId()

    xa = cirq.X.on(a)
    xb = cirq.X.on(b)

    ma = cirq.MeasurementGate().on(a)
    mb = cirq.MeasurementGate().on(b)

    c = Circuit()
    assert c.are_all_measurements_terminal()

    c = Circuit.from_ops(xa, xb)
    assert c.are_all_measurements_terminal()

    c = Circuit.from_ops(ma)
    assert c.are_all_measurements_terminal()

    c = Circuit.from_ops(ma, mb)
    assert c.are_all_measurements_terminal()

    c = Circuit.from_ops(xa, ma)
    assert c.are_all_measurements_terminal()

    c = Circuit.from_ops(xa, ma, xb, mb)
    assert c.are_all_measurements_terminal()

    c = Circuit.from_ops(ma, xa)
    assert not c.are_all_measurements_terminal()

    c = Circuit.from_ops(ma, xa, mb)
    assert not c.are_all_measurements_terminal()

    c = Circuit.from_ops(xa, ma, xb, xa)
    assert not c.are_all_measurements_terminal()

    c = Circuit.from_ops(ma, ma)
    assert not c.are_all_measurements_terminal()

    c = Circuit.from_ops(xa, ma, xa)
    assert not c.are_all_measurements_terminal()
Beispiel #5
0
def test_composite_gate_to_unitary_matrix():
    class CNOT_composite(cirq.CompositeGate):
        def default_decompose(self, qubits):
            q0, q1 = qubits
            return cirq.Y(q1)**-0.5, cirq.CZ(q0, q1), cirq.Y(q1)**0.5

    a = cirq.NamedQubit('a')
    b = cirq.NamedQubit('b')
    c = Circuit.from_ops(cirq.X(a),
                         CNOT_composite()(a, b), cirq.X(a), cirq.measure(a),
                         cirq.X(b), cirq.measure(b))
    mat = c.to_unitary_matrix()
    mat_expected = cirq.CNOT.matrix()

    cirq.testing.assert_allclose_up_to_global_phase(mat, mat_expected)
Beispiel #6
0
def test_findall_operations():
    a = cirq.QubitId()
    b = cirq.QubitId()

    xa = cirq.X.on(a)
    xb = cirq.X.on(b)
    za = cirq.Z.on(a)
    zb = cirq.Z.on(b)

    is_x = lambda op: isinstance(op.gate, cirq.RotXGate)

    c = Circuit()
    assert list(c.findall_operations(is_x)) == []

    c = Circuit.from_ops(xa)
    assert list(c.findall_operations(is_x)) == [(0, xa)]

    c = Circuit.from_ops(za)
    assert list(c.findall_operations(is_x)) == []

    c = Circuit.from_ops([za, zb] * 8)
    assert list(c.findall_operations(is_x)) == []

    c = Circuit.from_ops(xa, xb)
    assert list(c.findall_operations(is_x)) == [(0, xa), (0, xb)]

    c = Circuit.from_ops(xa, zb)
    assert list(c.findall_operations(is_x)) == [(0, xa)]

    c = Circuit.from_ops(xa, za)
    assert list(c.findall_operations(is_x)) == [(0, xa)]

    c = Circuit.from_ops([xa] * 8)
    assert list(c.findall_operations(is_x)) == list(enumerate([xa] * 8))

    c = Circuit.from_ops(za, zb, xa, xb)
    assert list(c.findall_operations(is_x)) == [(1, xa), (1, xb)]

    c = Circuit.from_ops(xa, zb, za, xb)
    assert list(c.findall_operations(is_x)) == [(0, xa), (1, xb)]
Beispiel #7
0
def test_from_ops():
    a = cirq.QubitId()
    b = cirq.QubitId()

    actual = Circuit.from_ops(
        cirq.X(a),
        [cirq.Y(a), cirq.Z(b)],
        cirq.CZ(a, b),
        cirq.X(a),
        [cirq.Z(b), cirq.Y(a)],
    )

    assert actual == Circuit([
        Moment([cirq.X(a)]),
        Moment([cirq.Y(a), cirq.Z(b)]),
        Moment([cirq.CZ(a, b)]),
        Moment([cirq.X(a), cirq.Z(b)]),
        Moment([cirq.Y(a)]),
    ])
Beispiel #8
0
def test_to_text_diagram_parameterized_value():
    q = cirq.NamedQubit('cube')

    class PGate(cirq.TextDiagrammableGate):
        def __init__(self, val):
            self.val = val

        def text_diagram_wire_symbols(self,
                                      qubit_count=None,
                                      use_unicode_characters=True,
                                      precision=3):
            return 'P',

        def text_diagram_exponent(self):
            return self.val

    c = Circuit.from_ops(
        PGate(1).on(q),
        PGate(2).on(q),
        PGate(cirq.Symbol('a')).on(q),
        PGate(cirq.Symbol('%$&#*(')).on(q),
    )
    assert str(c).strip() == 'cube: ───P───P^2───P^a───P^Symbol("%$&#*(")───'
Beispiel #9
0
def test_circuit_to_unitary_matrix():
    # Single qubit gates.
    a = cirq.NamedQubit('a')
    b = cirq.NamedQubit('b')
    c = Circuit.from_ops(cirq.Z(a), cirq.X(b))
    m = c.to_unitary_matrix()
    cirq.testing.assert_allclose_up_to_global_phase(m,
                                                    np.array([
                                                        [0, 1, 0, 0],
                                                        [1, 0, 0, 0],
                                                        [0, 0, 0, -1],
                                                        [0, 0, -1, 0],
                                                    ]),
                                                    atol=1e-8)

    # Single qubit gates and two qubit gate.
    c = Circuit.from_ops(cirq.Z(a), cirq.X(b), cirq.CNOT(a, b))
    m = c.to_unitary_matrix()
    cirq.testing.assert_allclose_up_to_global_phase(m,
                                                    np.array([
                                                        [0, 1, 0, 0],
                                                        [1, 0, 0, 0],
                                                        [0, 0, -1, 0],
                                                        [0, 0, 0, -1],
                                                    ]),
                                                    atol=1e-8)

    # Measurement gate has no corresponding matrix.
    c = Circuit.from_ops(cirq.measure(a))
    with pytest.raises(TypeError):
        _ = c.to_unitary_matrix(ignore_terminal_measurements=False)

    # Ignoring terminal measurements.
    c = Circuit.from_ops(cirq.measure(a))
    cirq.testing.assert_allclose_up_to_global_phase(c.to_unitary_matrix(),
                                                    np.eye(2))

    # Ignoring terminal measurements with further cirq.
    c = Circuit.from_ops(cirq.Z(a), cirq.measure(a), cirq.Z(b))
    cirq.testing.assert_allclose_up_to_global_phase(
        c.to_unitary_matrix(),
        np.array([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]]))

    # Optionally don't ignoring terminal measurements.
    c = Circuit.from_ops(cirq.measure(a))
    with pytest.raises(TypeError, match="Terminal"):
        c.to_unitary_matrix(ignore_terminal_measurements=False),

    # Non-terminal measurements are not ignored.
    c = Circuit.from_ops(cirq.measure(a), cirq.X(a))
    with pytest.raises(TypeError):
        _ = c.to_unitary_matrix()

    # Non-terminal measurements are not ignored (multiple qubits).
    c = Circuit.from_ops(cirq.measure(a), cirq.measure(b), cirq.CNOT(a, b))
    with pytest.raises(TypeError):
        _ = c.to_unitary_matrix()

    # Gates without matrix or decomposition raise exception
    class MysteryGate(cirq.Gate):
        pass

    c = Circuit.from_ops(MysteryGate()(a, b))
    with pytest.raises(TypeError):
        _ = c.to_unitary_matrix()