Ejemplo n.º 1
0
def assert_optimizes(no_decomp, expected, actual):
    with cirq.testing.assert_deprecated("Use cirq.expand_composite",
                                        deadline='v1.0'):
        expander = cirq.ExpandComposite(
            no_decomp) if no_decomp else cirq.ExpandComposite()
        expander(expected)
        if actual:
            assert_equal_mod_empty(expected, actual)
Ejemplo n.º 2
0
def test_circular_shift_gate_decomposition():
    qubits = [cirq.NamedQubit(q) for q in 'abcdef']

    expander = cirq.ExpandComposite()
    circular_shift = cca.CircularShiftGate(2, 1, cirq.CZ)(*qubits[:2])
    circuit = cirq.Circuit(circular_shift)
    expander.optimize_circuit(circuit)
    expected_circuit = cirq.Circuit(
            (cirq.Moment((cirq.CZ(*qubits[:2]),)),))
    assert circuit == expected_circuit

    no_decomp = lambda op: (isinstance(op, cirq.GateOperation) and
                            op.gate == cirq.SWAP)
    expander = cirq.ExpandComposite(no_decomp=no_decomp)

    circular_shift = cca.CircularShiftGate(6, 3)(*qubits)
    circuit = cirq.Circuit(circular_shift)
    expander.optimize_circuit(circuit)
    actual_text_diagram = circuit.to_text_diagram().strip()
    expected_text_diagram = """
a: ───────────×───────────
              │
b: ───────×───×───×───────
          │       │
c: ───×───×───×───×───×───
      │       │       │
d: ───×───×───×───×───×───
          │       │
e: ───────×───×───×───────
              │
f: ───────────×───────────
    """.strip()
    assert actual_text_diagram == expected_text_diagram

    circular_shift = cca.CircularShiftGate(6, 2)(*qubits)
    circuit = cirq.Circuit(circular_shift)
    expander.optimize_circuit(circuit)
    actual_text_diagram = circuit.to_text_diagram().strip()
    expected_text_diagram = """
a: ───────×───────────────
          │
b: ───×───×───×───────────
      │       │
c: ───×───×───×───×───────
          │       │
d: ───────×───×───×───×───
              │       │
e: ───────────×───×───×───
                  │
f: ───────────────×───────
    """.strip()
    assert actual_text_diagram == expected_text_diagram
Ejemplo n.º 3
0
def test_decompose_with_symbol():
    q0, = _make_qubits(1)
    ps = cirq.PauliString({q0: cirq.Pauli.Y})
    op = PauliStringPhasor(ps, half_turns=cirq.Symbol('a'))
    circuit = cirq.Circuit.from_ops(op)
    cirq.ExpandComposite().optimize_circuit(circuit)
    assert circuit.to_text_diagram() == "q0: ───X^0.5───Z^a───X^-0.5───"

    ps = cirq.PauliString({q0: cirq.Pauli.Y}, True)
    op = PauliStringPhasor(ps, half_turns=cirq.Symbol('a'))
    circuit = cirq.Circuit.from_ops(op)
    cirq.ExpandComposite().optimize_circuit(circuit)
    assert circuit.to_text_diagram() == "q0: ───X^0.5───X───Z^a───X───X^-0.5───"
Ejemplo n.º 4
0
def test_decompose_with_symbol():
    (q0,) = _make_qubits(1)
    ps = cirq.PauliString({q0: cirq.Y})
    op = cirq.PauliStringPhasor(ps, exponent_neg=sympy.Symbol('a'))
    circuit = cirq.Circuit(op)
    cirq.ExpandComposite().optimize_circuit(circuit)
    cirq.testing.assert_has_diagram(circuit, "q0: ───X^0.5───Z^a───X^-0.5───")

    ps = cirq.PauliString({q0: cirq.Y}, -1)
    op = cirq.PauliStringPhasor(ps, exponent_neg=sympy.Symbol('a'))
    circuit = cirq.Circuit(op)
    cirq.ExpandComposite().optimize_circuit(circuit)
    cirq.testing.assert_has_diagram(circuit, "q0: ───X^0.5───X───Z^a───X───X^-0.5───")
Ejemplo n.º 5
0
def test_decompose_with_symbol():
    q0, = _make_qubits(1)
    ps = cirq.PauliString({q0: cirq.Y})
    op = PauliStringPhasor(ps, half_turns=sympy.Symbol('a'))
    circuit = cirq.Circuit.from_ops(op)
    cirq.ExpandComposite().optimize_circuit(circuit)
    cirq.testing.assert_has_diagram(circuit, "q0: ───X^0.5───Z^a───X^-0.5───")

    ps = cirq.PauliString({q0: cirq.Y}, -1)
    op = PauliStringPhasor(ps, half_turns=sympy.Symbol('a'))
    circuit = cirq.Circuit.from_ops(op)
    cirq.ExpandComposite().optimize_circuit(circuit)
    cirq.testing.assert_has_diagram(
        circuit, "q0: ───X^0.5───Z^(-a)───X^-0.5───")
Ejemplo n.º 6
0
def test_swap_permutation_gate():
    no_decomp = lambda op: (isinstance(op, cirq.GateOperation) and op.gate ==
                            cirq.SWAP)
    a, b = cirq.NamedQubit('a'), cirq.NamedQubit('b')
    expander = cirq.ExpandComposite(no_decomp=no_decomp)
    circuit = cirq.Circuit.from_ops(SwapPermutationGate()(a, b))
    expander(circuit)
    assert tuple(circuit.all_operations()) == (cirq.SWAP(a, b), )

    no_decomp = lambda op: (isinstance(op, cirq.GateOperation) and op.gate ==
                            cirq.CZ)
    expander = cirq.ExpandComposite(no_decomp=no_decomp)
    circuit = cirq.Circuit.from_ops(SwapPermutationGate(cirq.CZ)(a, b))
    expander(circuit)
    assert tuple(circuit.all_operations()) == (cirq.CZ(a, b), )
Ejemplo n.º 7
0
def test_decompose_returns_deep_op_tree():
    class DummyGate(cirq.Gate, cirq.CompositeGate):
        def default_decompose(self, qubits):
            q0, q1 = qubits
            # Yield a tuple
            yield ((X(q0), Y(q0)), Z(q0))
            # Yield nested lists
            yield [X(q0), [Y(q0), Z(q0)]]
            def generator(depth):
                if depth <= 0:
                    yield CZ(q0, q1), Y(q0)
                else:
                    yield X(q0), generator(depth - 1)
                    yield Z(q0)
            # Yield nested generators
            yield generator(2)

    q0, q1 = QubitId(), QubitId()
    circuit = cirq.Circuit.from_ops(DummyGate()(q0, q1))

    opt = cirq.ExpandComposite()
    opt.optimize_circuit(circuit)
    expected = cirq.Circuit().from_ops(X(q0), Y(q0), Z(q0),  # From tuple
                                       X(q0), Y(q0), Z(q0),  # From nested lists
                                       # From nested generators
                                       X(q0), X(q0),
                                       CZ(q0, q1), Y(q0),
                                       Z(q0), Z(q0))
    assert_equal_mod_empty(expected, circuit)
Ejemplo n.º 8
0
def test_cirq_qsim_simulate_random_unitary(mode: str):

    q0, q1 = cirq.LineQubit.range(2)
    qsimSim = qsimcirq.QSimSimulator(qsim_options={"t": 16, "v": 0})
    for iter in range(10):
        random_circuit = cirq.testing.random_circuit(
            qubits=[q0, q1], n_moments=8, op_density=0.99, random_state=iter
        )

        cirq.ConvertToCzAndSingleGates().optimize_circuit(
            random_circuit
        )  # cannot work with params
        cirq.ExpandComposite().optimize_circuit(random_circuit)
        if mode == "noisy":
            random_circuit.append(NoiseTrigger().on(q0))

        result = qsimSim.simulate(random_circuit, qubit_order=[q0, q1])
        assert result.state_vector().shape == (4,)

        cirqSim = cirq.Simulator()
        cirq_result = cirqSim.simulate(random_circuit, qubit_order=[q0, q1])
        # When using rotation gates such as S, qsim may add a global phase relative
        # to other simulators. This is fine, as the result is equivalent.
        assert cirq.linalg.allclose_up_to_global_phase(
            result.state_vector(), cirq_result.state_vector(), atol=1.0e-6
        )
Ejemplo n.º 9
0
def main():
    """Demonstrates Quantum Fourier transform.
    """
    # Create circuit
    qft_circuit = generate_2x2_grid_qft_circuit()
    cirq.ConvertToCzAndSingleGates().optimize_circuit(
        qft_circuit)  # cannot work with params
    cirq.ExpandComposite().optimize_circuit(qft_circuit)

    print('Circuit:')
    print(qft_circuit)
    qsim_circuit = qsimcirq.QSimCircuit(cirq_circuit=qft_circuit,
                                        allow_decomposition=True)

    # Simulate and collect final_state
    sv_simulator = cirq.Simulator()
    qs_simulator = qsimcirq.QSimSimulator(qsim_options={'t': 16, 'v': 2})
    sv_result = sv_simulator.simulate(qft_circuit)
    qs_result = qs_simulator.simulate(qsim_circuit)
    assert sv_result.state_vector().shape == (16, )
    assert qs_result.state_vector().shape == (16, )
    assert cirq.linalg.allclose_up_to_global_phase(sv_result.state_vector(),
                                                   qs_result.state_vector())

    kc_simulator = cirq.KnowledgeCompilationSimulator(qft_circuit,
                                                      intermediate=False)
    kc_result = kc_simulator.simulate(qft_circuit)
    print()
    print('FinalState')
    assert cirq.linalg.allclose_up_to_global_phase(sv_result.state_vector(),
                                                   kc_result.state_vector())
    print(kc_result.state_vector())
    print(np.around(kc_result.final_state_vector, 3))
Ejemplo n.º 10
0
def test_ignore_non_composite():
    q0, q1 = cirq.LineQubit.range(2)
    circuit = cirq.Circuit()
    circuit.append([cirq.X(q0), cirq.Y(q1), cirq.CZ(q0, q1), cirq.Z(q0)])
    expected = circuit.copy()
    opt = cirq.ExpandComposite()
    opt.optimize_circuit(circuit)
    assert_equal_mod_empty(expected, circuit)
Ejemplo n.º 11
0
def test_ignore_non_composite():
    q0, q1 = QubitId(), QubitId()
    circuit = cirq.Circuit()
    circuit.append([X(q0), Y(q1), CZ(q0, q1), Z(q0)])
    expected = circuit.copy()
    opt = cirq.ExpandComposite()
    opt.optimize_circuit(circuit)
    assert_equal_mod_empty(expected, circuit)
Ejemplo n.º 12
0
def test_decompose(gate):
    q0, q1 = cirq.NamedQubit('q0'), cirq.NamedQubit('q1')
    circuit = cirq.Circuit.from_ops(
                    gate(q0, q1))
    cirq.ExpandComposite().optimize_circuit(circuit)
    decompose_mat = circuit.to_unitary_matrix()
    gate_mat = cirq.unitary(gate)
    cirq.testing.assert_allclose_up_to_global_phase(
        decompose_mat, gate_mat, rtol=1e-7, atol=1e-7)
Ejemplo n.º 13
0
def test_composite_default():
    q0, q1 = cirq.LineQubit.range(2)
    cnot = cirq.CNOT(q0, q1)
    circuit = cirq.Circuit()
    circuit.append(cnot)
    opt = cirq.ExpandComposite()
    opt.optimize_circuit(circuit)
    expected = cirq.Circuit()
    expected.append([cirq.Y(q1) ** -0.5, cirq.CZ(q0, q1), cirq.Y(q1) ** 0.5])
    assert_equal_mod_empty(expected, circuit)
Ejemplo n.º 14
0
def test_composite_default():
    q0, q1 = QubitId(), QubitId()
    cnot = CNOT(q0, q1)
    circuit = cirq.Circuit()
    circuit.append(cnot)
    opt = cirq.ExpandComposite()
    opt.optimize_circuit(circuit)
    expected = cirq.Circuit()
    expected.append([Y(q1) ** -0.5, CZ(q0, q1), Y(q1) ** 0.5])
    assert_equal_mod_empty(expected, circuit)
Ejemplo n.º 15
0
def test_composite_extension_overrides():
    q0, q1 = QubitId(), QubitId()
    cnot = CNOT(q0, q1)
    circuit = cirq.Circuit()
    circuit.append(cnot)
    ext = cirq.Extensions()
    ext.add_cast(cirq.CompositeGate, cirq.CNotGate, lambda _: OtherCNot())
    opt = cirq.ExpandComposite(composite_gate_extension=ext)
    opt.optimize_circuit(circuit)
    expected = cirq.Circuit()
    expected.append([Z(q0), Y(q1) ** -0.5, CZ(q0, q1), Y(q1) ** 0.5, Z(q0)])
    assert_equal_mod_empty(expected, circuit)
Ejemplo n.º 16
0
def test_swap_permutation_gate():
    no_decomp = lambda op: (isinstance(op, cirq.GateOperation) and op.gate ==
                            cirq.SWAP)
    a, b = cirq.NamedQubit('a'), cirq.NamedQubit('b')
    expander = cirq.ExpandComposite(no_decomp=no_decomp)
    gate = cca.SwapPermutationGate()
    assert gate.num_qubits() == 2
    circuit = cirq.Circuit(gate(a, b))
    expander(circuit)
    assert tuple(circuit.all_operations()) == (cirq.SWAP(a, b), )

    no_decomp = lambda op: (isinstance(op, cirq.GateOperation) and op.gate ==
                            cirq.CZ)
    expander = cirq.ExpandComposite(no_decomp=no_decomp)
    circuit = cirq.Circuit(cca.SwapPermutationGate(cirq.CZ)(a, b))
    expander(circuit)
    assert tuple(circuit.all_operations()) == (cirq.CZ(a, b), )

    assert cirq.commutes(gate, cirq.ZZ)
    with pytest.raises(TypeError):
        cirq.commutes(gate, cirq.CCZ)
Ejemplo n.º 17
0
def test_circuit_diagrams(part_size, subgraph):
    qubits = cirq.LineQubit.range(2 * part_size)
    gate = cca.BipartiteSwapNetworkGate(subgraph, part_size)
    circuit = cirq.Circuit.from_ops(gate(*qubits))
    diagram = circuit_diagrams['undecomposed', subgraph, part_size]
    cirq.testing.assert_has_diagram(circuit, diagram)

    no_decomp = (lambda op: isinstance(op.gate, (
        cca.AcquaintanceOpportunityGate, cca.SwapPermutationGate)))
    expander = cirq.ExpandComposite(no_decomp=no_decomp)
    expander(circuit)
    diagram = circuit_diagrams['decomposed', subgraph, part_size]
    cirq.testing.assert_has_diagram(circuit, diagram)
Ejemplo n.º 18
0
def test_decompose_returns_not_flat_op_tree():
    class DummyGate(cirq.SingleQubitGate):
        def _decompose_(self, qubits):
            (q0,) = qubits
            # Yield a tuple of gates instead of yielding a gate
            yield cirq.X(q0),

    q0 = cirq.NamedQubit('q0')
    circuit = cirq.Circuit(DummyGate()(q0))

    opt = cirq.ExpandComposite()
    opt.optimize_circuit(circuit)
    expected = cirq.Circuit(cirq.X(q0))
    assert_equal_mod_empty(expected, circuit)
Ejemplo n.º 19
0
def test_mix_composite_non_composite():
    q0, q1 = cirq.LineQubit.range(2)

    actual = cirq.Circuit(cirq.X(q0), cirq.CNOT(q0, q1), cirq.X(q1))
    opt = cirq.ExpandComposite()
    opt.optimize_circuit(actual)

    expected = cirq.Circuit(cirq.X(q0),
                            cirq.Y(q1)**-0.5,
                            cirq.CZ(q0, q1),
                            cirq.Y(q1)**0.5,
                            cirq.X(q1),
                            strategy=cirq.InsertStrategy.NEW)
    assert_equal_mod_empty(expected, actual)
Ejemplo n.º 20
0
def test_non_recursive_expansion():
    qubits = [cirq.NamedQubit(s) for s in 'xy']
    no_decomp = lambda op: (isinstance(op, cirq.GateOperation) and op.gate ==
                            cirq.ISWAP)
    expander = cirq.ExpandComposite(no_decomp=no_decomp)
    unexpanded_circuit = cirq.Circuit(cirq.ISWAP(*qubits))

    circuit = unexpanded_circuit.__copy__()
    expander.optimize_circuit(circuit)
    assert circuit == unexpanded_circuit

    no_decomp = lambda op: (isinstance(op, cirq.GateOperation) and isinstance(
        op.gate, (cirq.CNotPowGate, cirq.HPowGate)))
    expander = cirq.ExpandComposite(no_decomp=no_decomp)
    circuit = unexpanded_circuit.__copy__()
    expander.optimize_circuit(circuit)
    actual_text_diagram = circuit.to_text_diagram().strip()
    expected_text_diagram = """
x: ───@───H───X───S───X───S^-1───H───@───
      │       │       │              │
y: ───X───────@───────@──────────────X───
    """.strip()
    assert actual_text_diagram == expected_text_diagram
Ejemplo n.º 21
0
def test_mix_composite_non_composite():
    q0, q1 = QubitId(), QubitId()

    actual = cirq.Circuit.from_ops(X(q0), CNOT(q0, q1), X(q1))
    opt = cirq.ExpandComposite()
    opt.optimize_circuit(actual)

    expected = cirq.Circuit.from_ops(X(q0),
                                     Y(q1) ** -0.5,
                                     CZ(q0, q1),
                                     Y(q1) ** 0.5,
                                     X(q1),
                                     strategy=cirq.InsertStrategy.NEW)
    assert_equal_mod_empty(expected, actual)
Ejemplo n.º 22
0
def test_decompose_returns_not_flat_op_tree():
    class DummyGate(cirq.Gate, cirq.CompositeGate):
        def default_decompose(self, qubits):
            q0, = qubits
            # Yield a tuple of gates instead of yielding a gate
            yield X(q0),

    q0 = QubitId()
    circuit = cirq.Circuit.from_ops(DummyGate()(q0))

    opt = cirq.ExpandComposite()
    opt.optimize_circuit(circuit)
    expected = cirq.Circuit().from_ops(X(q0))
    assert_equal_mod_empty(expected, circuit)
Ejemplo n.º 23
0
def test_recursive_composite():
    q0, q1 = cirq.LineQubit.range(2)
    swap = cirq.SWAP(q0, q1)
    circuit = cirq.Circuit()
    circuit.append(swap)

    opt = cirq.ExpandComposite()
    opt.optimize_circuit(circuit)
    expected = cirq.Circuit(
        cirq.Y(q1)**-0.5, cirq.CZ(q0, q1),
        cirq.Y(q1)**0.5,
        cirq.Y(q0)**-0.5, cirq.CZ(q1, q0),
        cirq.Y(q0)**0.5,
        cirq.Y(q1)**-0.5, cirq.CZ(q0, q1),
        cirq.Y(q1)**0.5)
    assert_equal_mod_empty(expected, circuit)
Ejemplo n.º 24
0
def test_recursive_composite_extension_overrides():
    q0, q1 = QubitId(), QubitId()
    swap = SWAP(q0, q1)
    circuit = cirq.Circuit()
    circuit.append(swap)
    ext = cirq.Extensions()
    ext.add_cast(cirq.CompositeGate, cirq.CNotGate, lambda _: OtherCNot())
    opt = cirq.ExpandComposite(composite_gate_extension=ext)
    opt.optimize_circuit(circuit)
    expected = cirq.Circuit()
    expected.append([Z(q0), Y(q1) ** -0.5, CZ(q0, q1), Y(q1) ** 0.5, Z(q0)])
    expected.append([Z(q1), Y(q0) ** -0.5, CZ(q1, q0), Y(q0) ** 0.5, Z(q1)],
                    strategy=cirq.InsertStrategy.INLINE)
    expected.append([Z(q0), Y(q1) ** -0.5, CZ(q0, q1), Y(q1) ** 0.5, Z(q0)],
                    strategy=cirq.InsertStrategy.INLINE)
    assert_equal_mod_empty(expected, circuit)
Ejemplo n.º 25
0
def test_recursive_composite():
    q0, q1 = QubitId(), QubitId()
    swap = SWAP(q0, q1)
    circuit = cirq.Circuit()
    circuit.append(swap)

    opt = cirq.ExpandComposite()
    opt.optimize_circuit(circuit)
    expected = cirq.Circuit().from_ops(Y(q1) ** -0.5,
                                       CZ(q0, q1),
                                       Y(q1) ** 0.5,
                                       Y(q0) ** -0.5,
                                       CZ(q1, q0),
                                       Y(q0) ** 0.5,
                                       Y(q1) ** -0.5,
                                       CZ(q0, q1),
                                       Y(q1) ** 0.5)
    assert_equal_mod_empty(expected, circuit)
Ejemplo n.º 26
0
def test_decompose_returns_deep_op_tree():
    class DummyGate(cirq.testing.TwoQubitGate):
        def _decompose_(self, qubits):
            q0, q1 = qubits
            # Yield a tuple
            yield ((cirq.X(q0), cirq.Y(q0)), cirq.Z(q0))
            # Yield nested lists
            yield [cirq.X(q0), [cirq.Y(q0), cirq.Z(q0)]]

            def generator(depth):
                if depth <= 0:
                    yield cirq.CZ(q0, q1), cirq.Y(q0)
                else:
                    yield cirq.X(q0), generator(depth - 1)
                    yield cirq.Z(q0)

            # Yield nested generators
            yield generator(2)

    q0, q1 = cirq.LineQubit.range(2)
    circuit = cirq.Circuit(DummyGate()(q0, q1))

    opt = cirq.ExpandComposite()
    opt.optimize_circuit(circuit)
    expected = cirq.Circuit(
        cirq.X(q0),
        cirq.Y(q0),
        cirq.Z(q0),  # From tuple
        cirq.X(q0),
        cirq.Y(q0),
        cirq.Z(q0),  # From nested lists
        # From nested generators
        cirq.X(q0),
        cirq.X(q0),
        cirq.CZ(q0, q1),
        cirq.Y(q0),
        cirq.Z(q0),
        cirq.Z(q0),
    )
    assert_equal_mod_empty(expected, circuit)
Ejemplo n.º 27
0
def test_swap_network_gate():
    qubits = tuple(cirq.NamedQubit(s) for s in alphabet)

    acquaintance_size = 3
    n_parts = 3
    part_lens = (acquaintance_size - 1, ) * n_parts
    n_qubits = sum(part_lens)
    swap_network_op = SwapNetworkGate(
        part_lens, acquaintance_size=acquaintance_size)(*qubits[:n_qubits])
    swap_network = cirq.Circuit.from_ops(swap_network_op)
    actual_text_diagram = swap_network.to_text_diagram().strip()
    expected_text_diagram = """
a: ───×(0,0)───
      │
b: ───×(0,1)───
      │
c: ───×(1,0)───
      │
d: ───×(1,1)───
      │
e: ───×(2,0)───
      │
f: ───×(2,1)───
    """.strip()
    assert actual_text_diagram == expected_text_diagram

    no_decomp = lambda op: isinstance(op.gate, (CircularShiftGate,
                                                LinearPermutationGate))
    expander = cirq.ExpandComposite(no_decomp=no_decomp)
    expander(swap_network)
    actual_text_diagram = swap_network.to_text_diagram().strip()
    expected_text_diagram = """
a: ───█───────╲0╱───█─────────────────█───────────╲0╱───█───────0↦1───
      │       │     │                 │           │     │       │
b: ───█───█───╲1╱───█───█─────────────█───█───────╲1╱───█───█───1↦0───
      │   │   │     │   │             │   │       │     │   │
c: ───█───█───╱2╲───█───█───█───╲0╱───█───█───█───╱2╲───█───█───0↦1───
          │   │         │   │   │         │   │   │         │   │
d: ───────█───╱3╲───█───█───█───╲1╱───█───█───█───╱3╲───────█───1↦0───
                    │       │   │     │       │
e: ─────────────────█───────█───╱2╲───█───────█───0↦1─────────────────
                    │           │     │           │
f: ─────────────────█───────────╱3╲───█───────────1↦0─────────────────
    """.strip()
    assert actual_text_diagram == expected_text_diagram

    no_decomp = lambda op: isinstance(op.gate, CircularShiftGate)
    expander = cirq.ExpandComposite(no_decomp=no_decomp)

    acquaintance_size = 3
    n_parts = 6
    part_lens = (1, ) * n_parts
    n_qubits = sum(part_lens)
    swap_network_op = SwapNetworkGate(
        part_lens, acquaintance_size=acquaintance_size)(*qubits[:n_qubits])
    swap_network = cirq.Circuit.from_ops(swap_network_op)

    expander(swap_network)
    actual_text_diagram = swap_network.to_text_diagram().strip()
    expected_text_diagram = """
a: ───╲0╱─────────╲0╱─────────╲0╱─────────
      │           │           │
b: ───╱1╲───╲0╱───╱1╲───╲0╱───╱1╲───╲0╱───
            │           │           │
c: ───╲0╱───╱1╲───╲0╱───╱1╲───╲0╱───╱1╲───
      │           │           │
d: ───╱1╲───╲0╱───╱1╲───╲0╱───╱1╲───╲0╱───
            │           │           │
e: ───╲0╱───╱1╲───╲0╱───╱1╲───╲0╱───╱1╲───
      │           │           │
f: ───╱1╲─────────╱1╲─────────╱1╲─────────
    """.strip()
    assert actual_text_diagram == expected_text_diagram
Ejemplo n.º 28
0
def test_empty_moment():
    circuit = cirq.Circuit([])
    opt = cirq.ExpandComposite()
    opt.optimize_circuit(circuit)
    assert_equal_mod_empty(cirq.Circuit([]), circuit)
Ejemplo n.º 29
0
def test_swap_network_gate():
    qubits = tuple(cirq.NamedQubit(s) for s in alphabet)

    acquaintance_size = 3
    n_parts = 3
    part_lens = (acquaintance_size - 1, ) * n_parts
    n_qubits = sum(part_lens)
    swap_network_op = cca.SwapNetworkGate(
        part_lens, acquaintance_size=acquaintance_size)(*qubits[:n_qubits])
    swap_network = cirq.Circuit(swap_network_op)
    expected_text_diagram = """
a: ───×(0,0)───
      │
b: ───×(0,1)───
      │
c: ───×(1,0)───
      │
d: ───×(1,1)───
      │
e: ───×(2,0)───
      │
f: ───×(2,1)───
    """.strip()
    ct.assert_has_diagram(swap_network, expected_text_diagram)

    no_decomp = lambda op: isinstance(op.gate, (cca.CircularShiftGate, cca.
                                                LinearPermutationGate))
    expander = cirq.ExpandComposite(no_decomp=no_decomp)
    expander(swap_network)
    expected_text_diagram = """
a: ───█───────╲0╱───█─────────────────█───────────╲0╱───█───────0↦1───
      │       │     │                 │           │     │       │
b: ───█───█───╲1╱───█───█─────────────█───█───────╲1╱───█───█───1↦0───
      │   │   │     │   │             │   │       │     │   │   │
c: ───█───█───╱2╲───█───█───█───╲0╱───█───█───█───╱2╲───█───█───2↦3───
          │   │         │   │   │         │   │   │         │   │
d: ───────█───╱3╲───█───█───█───╲1╱───█───█───█───╱3╲───────█───3↦2───
                    │       │   │     │       │                 │
e: ─────────────────█───────█───╱2╲───█───────█─────────────────4↦5───
                    │           │     │                         │
f: ─────────────────█───────────╱3╲───█─────────────────────────5↦4───
    """.strip()
    ct.assert_has_diagram(swap_network, expected_text_diagram)

    no_decomp = lambda op: isinstance(op.gate, cca.CircularShiftGate)
    expander = cirq.ExpandComposite(no_decomp=no_decomp)

    acquaintance_size = 3
    n_parts = 6
    part_lens = (1, ) * n_parts
    n_qubits = sum(part_lens)
    swap_network_op = cca.SwapNetworkGate(
        part_lens, acquaintance_size=acquaintance_size)(*qubits[:n_qubits])
    swap_network = cirq.Circuit(swap_network_op)

    expander(swap_network)
    expected_text_diagram = """
a: ───╲0╱─────────╲0╱─────────╲0╱─────────
      │           │           │
b: ───╱1╲───╲0╱───╱1╲───╲0╱───╱1╲───╲0╱───
            │           │           │
c: ───╲0╱───╱1╲───╲0╱───╱1╲───╲0╱───╱1╲───
      │           │           │
d: ───╱1╲───╲0╱───╱1╲───╲0╱───╱1╲───╲0╱───
            │           │           │
e: ───╲0╱───╱1╲───╲0╱───╱1╲───╲0╱───╱1╲───
      │           │           │
f: ───╱1╲─────────╱1╲─────────╱1╲─────────
    """.strip()
    ct.assert_has_diagram(swap_network, expected_text_diagram)
Ejemplo n.º 30
0
def test_complete_acquaintance_strategy():
    qubits = [cirq.NamedQubit(s) for s in alphabet]

    with pytest.raises(ValueError):
        _ = cca.complete_acquaintance_strategy(qubits, -1)

    empty_strategy = cca.complete_acquaintance_strategy(qubits)
    assert empty_strategy._moments == []

    trivial_strategy = cca.complete_acquaintance_strategy(qubits[:4], 1)
    actual_text_diagram = trivial_strategy.to_text_diagram().strip()
    expected_text_diagram = """
a: ───█───

b: ───█───

c: ───█───

d: ───█───
    """.strip()
    assert actual_text_diagram == expected_text_diagram
    assert cca.get_acquaintance_size(trivial_strategy) == 1

    is_shift_or_lin_perm = lambda op: isinstance(op.gate, (
        cca.CircularShiftGate, cca.LinearPermutationGate))
    expand = cirq.ExpandComposite(no_decomp=is_shift_or_lin_perm)

    quadratic_strategy = cca.complete_acquaintance_strategy(qubits[:8], 2)
    actual_text_diagram = quadratic_strategy.to_text_diagram().strip()
    expected_text_diagram = """
a: ───×(0,0)───
      │
b: ───×(1,0)───
      │
c: ───×(2,0)───
      │
d: ───×(3,0)───
      │
e: ───×(4,0)───
      │
f: ───×(5,0)───
      │
g: ───×(6,0)───
      │
h: ───×(7,0)───
    """.strip()
    assert actual_text_diagram == expected_text_diagram
    assert cca.get_acquaintance_size(quadratic_strategy) == 2

    expand(quadratic_strategy)
    actual_text_diagram = quadratic_strategy.to_text_diagram(
        transpose=True).strip()
    expected_text_diagram = '\n'.join(
        ("a   b   c   d   e   f   g   h        ".strip(),
         "│   │   │   │   │   │   │   │        ".strip(),
         "█───█   █───█   █───█   █───█        ".strip(),
         "│   │   │   │   │   │   │   │        ".strip(),
         "╲0╱─╱1╲ ╲0╱─╱1╲ ╲0╱─╱1╲ ╲0╱─╱1╲      ".strip(),
         "│   │   │   │   │   │   │   │        ".strip(),
         "│   █───█   █───█   █───█   │        ".strip(),
         "│   │   │   │   │   │   │   │        ".strip(),
         "│   ╲0╱─╱1╲ ╲0╱─╱1╲ ╲0╱─╱1╲ │        ".strip(),
         "│   │   │   │   │   │   │   │        ".strip(),
         "█───█   █───█   █───█   █───█        ".strip(),
         "│   │   │   │   │   │   │   │        ".strip(),
         "╲0╱─╱1╲ ╲0╱─╱1╲ ╲0╱─╱1╲ ╲0╱─╱1╲      ".strip(),
         "│   │   │   │   │   │   │   │        ".strip(),
         "│   █───█   █───█   █───█   │        ".strip(),
         "│   │   │   │   │   │   │   │        ".strip(),
         "│   ╲0╱─╱1╲ ╲0╱─╱1╲ ╲0╱─╱1╲ │        ".strip(),
         "│   │   │   │   │   │   │   │        ".strip(),
         "█───█   █───█   █───█   █───█        ".strip(),
         "│   │   │   │   │   │   │   │        ".strip(),
         "╲0╱─╱1╲ ╲0╱─╱1╲ ╲0╱─╱1╲ ╲0╱─╱1╲      ".strip(),
         "│   │   │   │   │   │   │   │        ".strip(),
         "│   █───█   █───█   █───█   │        ".strip(),
         "│   │   │   │   │   │   │   │        ".strip(),
         "│   ╲0╱─╱1╲ ╲0╱─╱1╲ ╲0╱─╱1╲ │        ".strip(),
         "│   │   │   │   │   │   │   │        ".strip(),
         "█───█   █───█   █───█   █───█        ".strip(),
         "│   │   │   │   │   │   │   │        ".strip(),
         "╲0╱─╱1╲ ╲0╱─╱1╲ ╲0╱─╱1╲ ╲0╱─╱1╲      ".strip(),
         "│   │   │   │   │   │   │   │        ".strip(),
         "│   █───█   █───█   █───█   │        ".strip(),
         "│   │   │   │   │   │   │   │        ".strip(),
         "│   ╲0╱─╱1╲ ╲0╱─╱1╲ ╲0╱─╱1╲ │        ".strip(),
         "│   │   │   │   │   │   │   │        ".strip()))
    assert actual_text_diagram == expected_text_diagram
    assert cca.get_acquaintance_size(quadratic_strategy) == 2

    cubic_strategy = cca.complete_acquaintance_strategy(qubits[:4], 3)
    actual_text_diagram = cubic_strategy.to_text_diagram(
        transpose=True).strip()
    expected_text_diagram = """
a      b      c      d
│      │      │      │
×(0,0)─×(0,1)─×(1,0)─×(1,1)
│      │      │      │
╱1╲────╲0╱    ╱1╲────╲0╱
│      │      │      │
×(0,0)─×(1,0)─×(1,1)─×(2,0)
│      │      │      │
│      ╲0╱────╱1╲    │
│      │      │      │
×(0,0)─×(0,1)─×(1,0)─×(1,1)
│      │      │      │
╱1╲────╲0╱    ╱1╲────╲0╱
│      │      │      │
×(0,0)─×(1,0)─×(1,1)─×(2,0)
│      │      │      │
│      ╲0╱────╱1╲    │
│      │      │      │
    """.strip()
    assert actual_text_diagram == expected_text_diagram
    assert cca.get_acquaintance_size(cubic_strategy) == 3