Exemplo n.º 1
0
def test_diagram():
    a, b, c, d = cirq.LineQubit.range(4)
    circuit = cirq.Circuit(
        cirq.TOFFOLI(a, b, c),
        cirq.TOFFOLI(a, b, c)**0.5,
        cirq.CCX(a, c, b),
        cirq.CCZ(a, d, b),
        cirq.CCZ(a, d, b)**0.5,
        cirq.CSWAP(a, c, d),
        cirq.FREDKIN(a, b, c),
    )
    cirq.testing.assert_has_diagram(
        circuit,
        """
0: ───@───@───────@───@───@───────@───@───
      │   │       │   │   │       │   │
1: ───@───@───────X───@───@───────┼───×───
      │   │       │   │   │       │   │
2: ───X───X^0.5───@───┼───┼───────×───×───
                      │   │       │
3: ───────────────────@───@^0.5───×───────
""",
    )
    cirq.testing.assert_has_diagram(
        circuit,
        """
0: ---@---@-------@---@---@-------@------@------
      |   |       |   |   |       |      |
1: ---@---@-------X---@---@-------|------swap---
      |   |       |   |   |       |      |
2: ---X---X^0.5---@---|---|-------swap---swap---
                      |   |       |
3: -------------------@---@^0.5---swap----------
""",
        use_unicode_characters=False,
    )

    diagonal_circuit = cirq.Circuit(
        cirq.ThreeQubitDiagonalGate([2, 3, 5, 7, 11, 13, 17, 19])(a, b, c))
    cirq.testing.assert_has_diagram(
        diagonal_circuit,
        """
0: ───diag(2, 3, 5, 7, 11, 13, 17, 19)───
      │
1: ───#2─────────────────────────────────
      │
2: ───#3─────────────────────────────────
""",
    )
    cirq.testing.assert_has_diagram(
        diagonal_circuit,
        """
0: ---diag(2, 3, 5, 7, 11, 13, 17, 19)---
      |
1: ---#2---------------------------------
      |
2: ---#3---------------------------------
""",
        use_unicode_characters=False,
    )
Exemplo n.º 2
0
def test_diagram():
    a, b, c, d = cirq.LineQubit.range(4)
    circuit = cirq.Circuit.from_ops(cirq.TOFFOLI(a, b, c),
                                    cirq.TOFFOLI(a, b, c)**0.5,
                                    cirq.CCX(a, c, b), cirq.CCZ(a, d, b),
                                    cirq.CCZ(a, d, b)**0.5,
                                    cirq.CSWAP(a, c, d), cirq.FREDKIN(a, b, c))
    cirq.testing.assert_has_diagram(
        circuit, """
0: ───@───@───────@───@───@───────@───@───
      │   │       │   │   │       │   │
1: ───@───@───────X───@───@───────┼───×───
      │   │       │   │   │       │   │
2: ───X───X^0.5───@───┼───┼───────×───×───
                      │   │       │
3: ───────────────────@───@^0.5───×───────
""")
    cirq.testing.assert_has_diagram(circuit,
                                    """
0: ---@---@-------@---@---@-------@------@------
      |   |       |   |   |       |      |
1: ---@---@-------X---@---@-------|------swap---
      |   |       |   |   |       |      |
2: ---X---X^0.5---@---|---|-------swap---swap---
                      |   |       |
3: -------------------@---@^0.5---swap----------
""",
                                    use_unicode_characters=False)
def test_ccz():
    a, b, c, d = cirq.LineQubit.range(4)

    # Raw.
    circuit = cirq.Circuit(cirq.CCZ(a, b, c))
    assert_links_to(circuit, """
        http://algassert.com/quirk#circuit={"cols":[["•","•","Z"]]}
    """, escape_url=False)

    # Symbolic exponent.
    circuit = cirq.Circuit(cirq.CCZ(a, b, c)**sympy.Symbol('t'))
    assert_links_to(circuit, """
        http://algassert.com/quirk#circuit={"cols":[["•","•","Z^t"]]}
    """, escape_url=False)

    # Unknown exponent.
    circuit = cirq.Circuit(cirq.CCZ(a, b, c)**0.01)
    assert_links_to(circuit, """
        http://algassert.com/quirk#circuit={"cols":[
            ["UNKNOWN","UNKNOWN","UNKNOWN"]
        ]}
    """, escape_url=False, prefer_unknown_gate_to_failure=True)

    # With exponent. Doesn't merge with other operation.
    circuit = cirq.Circuit(cirq.CCZ(a, b, c)**0.5, cirq.H(d))
    assert_links_to(circuit, """
        http://algassert.com/quirk#circuit={"cols":[
            ["•","•","Z^½"],[1,1,1,"H"]]}
    """, escape_url=False)
Exemplo n.º 4
0
def test_swap_network_gate_from_ops():
    n_qubits = 10
    qubits = cirq.LineQubit.range(n_qubits)
    part_lens = (1, 2, 1, 3, 3)
    operations = [cirq.Z(qubits[0]),
                  cirq.CZ(*qubits[1:3]),
                  cirq.CCZ(*qubits[4:7]),
                  cirq.CCZ(*qubits[7:])]
    acquaintance_size = 3
    swap_network = cca.SwapNetworkGate.from_operations(
            qubits, operations, acquaintance_size)
    assert swap_network.acquaintance_size == acquaintance_size
    assert swap_network.part_lens == part_lens

    acquaintance_size = 2
    operations = []
    qubits = qubits[:5]
    swap_network = cca.SwapNetworkGate.from_operations(qubits, operations,
                                                       acquaintance_size,
                                                       cirq.ZZ)
    circuit = cirq.Circuit.from_ops(swap_network(*qubits))
    cca.DECOMPOSE_PERMUTATION_GATES(circuit)

    expected_diagram = """
0: ───█───ZZ────────────█───ZZ────────────█───ZZ───
      │   │             │   │             │   │
1: ───█───ZZ───█───ZZ───█───ZZ───█───ZZ───█───ZZ───
               │   │             │   │
2: ───█───ZZ───█───ZZ───█───ZZ───█───ZZ───█───ZZ───
      │   │             │   │             │   │
3: ───█───ZZ───█───ZZ───█───ZZ───█───ZZ───█───ZZ───
               │   │             │   │
4: ────────────█───ZZ────────────█───ZZ────────────
""".strip()
    cirq.testing.assert_has_diagram(circuit, expected_diagram)
Exemplo n.º 5
0
def _all_operations(q0, q1, q2, q3, q4, include_measurements=True):
    class DummyOperation(cirq.Operation):
        qubits = (q0, )
        with_qubits = NotImplemented

        def _qasm_(self, args: cirq.QasmArgs) -> str:
            return '// Dummy operation\n'

        def _decompose_(self):
            # Only used by test_output_unitary_same_as_qiskit
            return ()  # coverage: ignore

    class DummyCompositeOperation(cirq.Operation):
        qubits = (q0, )
        with_qubits = NotImplemented

        def _decompose_(self):
            return cirq.X(self.qubits[0])

        def __repr__(self):
            return 'DummyCompositeOperation()'

    return (
        cirq.Z(q0),
        cirq.Z(q0)**0.625,
        cirq.Y(q0),
        cirq.Y(q0)**0.375,
        cirq.X(q0),
        cirq.X(q0)**0.875,
        cirq.H(q1),
        cirq.CZ(q0, q1),
        cirq.CZ(q0, q1)**0.25,  # Requires 2-qubit decomposition
        cirq.CNOT(q0, q1),
        cirq.CNOT(q0, q1)**0.5,  # Requires 2-qubit decomposition
        cirq.SWAP(q0, q1),
        cirq.SWAP(q0, q1)**0.75,  # Requires 2-qubit decomposition
        cirq.CCZ(q0, q1, q2),
        cirq.CCX(q0, q1, q2),
        cirq.CCZ(q0, q1, q2)**0.5,
        cirq.CCX(q0, q1, q2)**0.5,
        cirq.CSWAP(q0, q1, q2),
        cirq.IdentityGate(1).on(q0),
        cirq.IdentityGate(3).on(q0, q1, q2),
        cirq.ISWAP(q2, q0),  # Requires 2-qubit decomposition
        cirq.PhasedXPowGate(phase_exponent=0.111, exponent=0.25).on(q1),
        cirq.PhasedXPowGate(phase_exponent=0.333, exponent=0.5).on(q1),
        cirq.PhasedXPowGate(phase_exponent=0.777, exponent=-0.5).on(q1),
        (
            cirq.measure(q0, key='xX'),
            cirq.measure(q2, key='x_a'),
            cirq.measure(q1, key='x?'),
            cirq.measure(q3, key='X'),
            cirq.measure(q4, key='_x'),
            cirq.measure(q2, key='x_a'),
            cirq.measure(q1, q2, q3, key='multi', invert_mask=(False, True)),
        ) if include_measurements else (),
        DummyOperation(),
        DummyCompositeOperation(),
    )
Exemplo n.º 6
0
def _all_operations(q0, q1, q2, q3, q4, include_measurments=True):
    class DummyOperation(cirq.Operation, cirq.QasmConvertibleOperation,
                         cirq.CompositeOperation):
        qubits = (q0, )
        with_qubits = NotImplemented

        def known_qasm_output(self, args):
            return '// Dummy operation\n'

        def default_decompose(self):
            # Only used by test_output_unitary_same_as_qiskit
            return ()  # coverage: ignore

    class DummyCompositeOperation(cirq.Operation, cirq.CompositeOperation):
        qubits = (q0, )
        with_qubits = NotImplemented

        def default_decompose(self):
            return cirq.X(self.qubits[0])

        def __repr__(self):
            return 'DummyCompositeOperation()'

    return (
        cirq.Z(q0),
        cirq.Z(q0)**.625,
        cirq.Y(q0),
        cirq.Y(q0)**.375,
        cirq.X(q0),
        cirq.X(q0)**.875,
        cirq.H(q1),
        cirq.CZ(q0, q1),
        cirq.CZ(q0, q1)**0.25,  # Requires 2-qubit decomposition
        cirq.CNOT(q0, q1),
        cirq.CNOT(q0, q1)**0.5,  # Requires 2-qubit decomposition
        cirq.SWAP(q0, q1),
        cirq.SWAP(q0, q1)**0.75,  # Requires 2-qubit decomposition
        cirq.CCZ(q0, q1, q2),
        cirq.CCX(q0, q1, q2),
        cirq.CCZ(q0, q1, q2)**0.5,
        cirq.CCX(q0, q1, q2)**0.5,
        cirq.CSWAP(q0, q1, q2),
        cirq.ISWAP(q2, q0),  # Requires 2-qubit decomposition
        cirq.google.ExpWGate(axis_half_turns=0.125, half_turns=0.25)(q1),
        (
            cirq.MeasurementGate('xX')(q0),
            cirq.MeasurementGate('x_a')(q2),
            cirq.MeasurementGate('x?')(q1),
            cirq.MeasurementGate('X')(q3),
            cirq.MeasurementGate('_x')(q4),
            cirq.MeasurementGate('x_a')(q2),
            cirq.MeasurementGate('multi', (False, True))(q1, q2, q3),
        ) if include_measurments else (),
        DummyOperation(),
        DummyCompositeOperation(),
    )
Exemplo n.º 7
0
def test_eq():
    a, b, c, d = cirq.LineQubit.range(4)
    eq = cirq.testing.EqualsTester()
    eq.add_equality_group(cirq.CCZ(a, b, c), cirq.CCZ(a, c, b),
                          cirq.CCZ(b, c, a))
    eq.add_equality_group(cirq.CCZ(a, b, d))
    eq.add_equality_group(cirq.TOFFOLI(a, b, c), cirq.CCX(a, b, c))
    eq.add_equality_group(cirq.TOFFOLI(a, c, b), cirq.TOFFOLI(c, a, b))
    eq.add_equality_group(cirq.TOFFOLI(a, b, d))
    eq.add_equality_group(cirq.CSWAP(a, b, c), cirq.FREDKIN(a, b, c))
    eq.add_equality_group(cirq.CSWAP(b, a, c), cirq.CSWAP(b, c, a))
Exemplo n.º 8
0
def test_swap_network_gate_from_ops():
    n_qubits = 10
    qubits = cirq.LineQubit.range(n_qubits)
    part_lens = (1, 2, 1, 3, 3)
    operations = [cirq.Z(qubits[0]),
                  cirq.CZ(*qubits[1:3]),
                  cirq.CCZ(*qubits[4:7]),
                  cirq.CCZ(*qubits[7:])]
    acquaintance_size = 3
    swap_network = cca.SwapNetworkGate.from_operations(
            qubits, operations, acquaintance_size)
    assert swap_network.acquaintance_size == acquaintance_size
    assert swap_network.part_lens == part_lens
Exemplo n.º 9
0
def test_decompose_unsupported_gate_deprecated():
    q0, q1, q2 = cirq.LineQubit.range(3)
    device = ionq.IonQAPIDevice(qubits=[q0, q1, q2])
    op = cirq.CCZ(q0, q1, q2)
    with pytest.raises(ValueError, match='not supported'):
        with cirq.testing.assert_deprecated('decompose_to_device', deadline='v0.15'):
            _ = device.decompose_operation(op)
Exemplo n.º 10
0
def test_is_supported():
    a = cirq.GridQubit(0, 0)
    b = cirq.GridQubit(0, 1)
    c = cirq.GridQubit(1, 0)
    assert cg.XmonGate.is_supported_op(cirq.CZ(a, b))
    assert cg.XmonGate.is_supported_op(cirq.Z(a)**1)
    assert not cg.XmonGate.is_supported_op(cirq.CCZ(a, b, c))
    assert not cg.XmonGate.is_supported_op(cirq.SWAP(a, b))
Exemplo n.º 11
0
 def _decompose_(self, qubits):
     control, a, b = qubits
     yield cirq.CNOT(a, b)
     yield cirq.H(a)
     yield cirq.CCZ(control, a, b)**self.exponent
     # Note: Clifford optimization would merge this CZ into the CCZ decomp.
     yield cirq.CZ(control, b)**(-self.exponent / 2)
     yield cirq.H(a)
     yield cirq.CNOT(a, b)
Exemplo n.º 12
0
def test_ccz():
    before = cirq.Circuit(
        cirq.CCZ(cirq.GridQubit(5, 5), cirq.GridQubit(5, 6), cirq.GridQubit(5, 7))
    )

    after = cg.optimized_for_xmon(before)

    assert len(after) <= 22
    assert_circuits_with_terminal_measurements_are_equivalent(before, after, atol=1e-4)
Exemplo n.º 13
0
    def test_default_gates_and_qbit_reorder(self):
        gcirq = cirq.Circuit()
        qreg1 = [cirq.GridQubit(i, 0) for i in range(2)]
        qreg2 = [cirq.LineQubit(0)]
        qreg3 = [cirq.LineQubit(i) for i in range(1, 3)]
        for op in gates_1qb:
            gcirq.append(op(qreg2[0])**-1.0)
        for op in gates_2qb:
            gcirq.append(op(qreg3[0], qreg1[1])**-1.0)

        gcirq.append(cirq.CCX(qreg1[0], qreg3[1], qreg2[0]))
        gcirq.append(cirq.CSWAP(qreg1[0], qreg3[1], qreg2[0]))
        gcirq.append(cirq.CCZ(qreg1[0], qreg3[1], qreg2[0]))
        # Toffoli | (qreg3[1], qreg1[0], qreg2[0])
        for qbit in qreg1 + qreg2 + qreg3:
            gcirq.append(cirq.measure(qbit))
        # Generating qlm circuit
        result = cirq_to_qlm(gcirq)

        # Generating equivalent qlm circuit
        prog = Program()
        qubits = prog.qalloc(5)
        cbits = prog.calloc(5)

        for op in pygates_1qb:
            prog.apply(op.dag(), qubits[2])

        for op in pygates_2qb:
            prog.apply(op.dag(), qubits[3], qubits[1])

        prog.apply(CCNOT, qubits[0], qubits[4], qubits[2])
        prog.apply(SWAP.ctrl(), qubits[0], qubits[4], qubits[2])
        prog.apply(Z.ctrl().ctrl(), qubits[0], qubits[4], qubits[2])

        for i in range(5):
            prog.measure(qubits[i], cbits[i])
        expected = prog.to_circ()
        self.assertEqual(len(result.ops), len(expected.ops))
        for i in range(len(result.ops)):
            res_op = result.ops[i]
            exp_op = expected.ops[i]
            if res_op.type == OpType.MEASURE:
                self.assertEqual(res_op, exp_op)
                continue
            result_gate_name, result_gate_params = extract_syntax(
                result.gateDic[res_op.gate], result.gateDic)
            # print("got gate {} with params {} on qbits {}"
            #      .format(result_gate_name, result_gate_params,
            #              res_op.qbits))
            expected_gate_name, expected_gate_params = extract_syntax(
                expected.gateDic[exp_op.gate], expected.gateDic)
            # print("expected gate {} with params {} on qbits {}"
            #      .format(expected_gate_name, expected_gate_params,
            #              exp_op.qbits))
            self.assertEqual(expected_gate_name, result_gate_name)
            self.assertEqual(expected_gate_params, result_gate_params)
Exemplo n.º 14
0
def test_two_qubit_compilation_decompose_operation_not_implemented():
    gateset = DummyCXTargetGateset()
    q = cirq.LineQubit.range(3)
    assert gateset.decompose_to_target_gateset(cirq.measure(q[0]), 1) is NotImplemented
    assert gateset.decompose_to_target_gateset(cirq.measure(*q[:2]), 1) is NotImplemented
    assert (
        gateset.decompose_to_target_gateset(cirq.X(q[0]).with_classical_controls("m"), 1)
        is NotImplemented
    )
    assert gateset.decompose_to_target_gateset(cirq.CCZ(*q), 1) is NotImplemented
Exemplo n.º 15
0
def test_ccz():
    before = cirq.Circuit(
        cirq.CCZ(cirq.GridQubit(5, 5), cirq.GridQubit(5, 6), cirq.GridQubit(5, 7))
    )

    with cirq.testing.assert_deprecated(
        'Use cirq.optimize_for_target_gateset', deadline='v0.16', count=2
    ):
        after = cg.optimized_for_xmon(before)

        assert len(after) <= 22
        assert_circuits_with_terminal_measurements_are_equivalent(before, after, atol=1e-4)
Exemplo n.º 16
0
 def controlled_sqrt_iswap(qs):
     c = cirq.Circuit()
     c.append(cirq.ControlledGate(cirq.Y**-0.5).on(qs[0], qs[2]))
     c.append(cirq.CCZ.on(qs[0], qs[1], qs[2]))
     c.append(cirq.ControlledGate(cirq.Y**0.5).on(qs[0], qs[2]))
     c.append(cirq.ControlledGate(cirq.Y**0.5).on(qs[0], qs[1]))
     c.append(cirq.CX.on(qs[0], qs[1]))
     c.append(cirq.ControlledGate(cirq.Y**-0.5).on(qs[0], qs[1]))
     c.append(cirq.CCZ(qs[0], qs[1], qs[2]))
     c.append(cirq.ControlledGate(cirq.Y**0.5).on(qs[0], qs[1]))
     c.append(cirq.ControlledGate(cirq.T).on(qs[0], qs[1]))
     c.append(cirq.ControlledGate(cirq.Y**-0.5).on(qs[0], qs[1]))
     c.append(cirq.CCZ(qs[0], qs[1], qs[2]))
     c.append(cirq.ControlledGate(cirq.Y**-0.5).on(qs[0], qs[2]))
     c.append(cirq.ControlledGate(cirq.Y**0.5).on(qs[0], qs[1]))
     c.append(cirq.ControlledGate(cirq.Z**-0.25).on(qs[0], qs[1]))
     c.append(cirq.ControlledGate(cirq.Y**0.5).on(qs[0], qs[1]))
     c.append(cirq.CX.on(qs[0], qs[1]))
     c.append(cirq.CCZ.on(qs[0], qs[1], qs[2]))
     c.append(cirq.ControlledGate(cirq.Y**0.5).on(qs[0], qs[2]))
     return c
Exemplo n.º 17
0
def _all_operations(q0, q1, q2, q3, q4, include_measurements=True):
    return (
        cirq.Z(q0),
        cirq.Z(q0)**0.625,
        cirq.Y(q0),
        cirq.Y(q0)**0.375,
        cirq.X(q0),
        cirq.X(q0)**0.875,
        cirq.H(q1),
        cirq.CZ(q0, q1),
        cirq.CZ(q0, q1)**0.25,  # Requires 2-qubit decomposition
        cirq.CNOT(q0, q1),
        cirq.CNOT(q0, q1)**0.5,  # Requires 2-qubit decomposition
        cirq.SWAP(q0, q1),
        cirq.SWAP(q1, q0)**-1,
        cirq.SWAP(q0, q1)**0.75,  # Requires 2-qubit decomposition
        cirq.CCZ(q0, q1, q2),
        cirq.CCX(q0, q1, q2),
        cirq.CCZ(q0, q1, q2)**0.5,
        cirq.CCX(q0, q1, q2)**0.5,
        cirq.CSWAP(q0, q1, q2),
        cirq.XX(q0, q1),
        cirq.XX(q0, q1)**0.75,
        cirq.YY(q0, q1),
        cirq.YY(q0, q1)**0.75,
        cirq.ZZ(q0, q1),
        cirq.ZZ(q0, q1)**0.75,
        cirq.IdentityGate(1).on(q0),
        cirq.IdentityGate(3).on(q0, q1, q2),
        cirq.ISWAP(q2, q0),  # Requires 2-qubit decomposition
        cirq.PhasedXPowGate(phase_exponent=0.111, exponent=0.25).on(q1),
        cirq.PhasedXPowGate(phase_exponent=0.333, exponent=0.5).on(q1),
        cirq.PhasedXPowGate(phase_exponent=0.777, exponent=-0.5).on(q1),
        cirq.wait(q0, nanos=0),
        cirq.measure(q0, key='xX'),
        cirq.measure(q2, key='x_a'),
        cirq.measure(q3, key='X'),
        cirq.measure(q2, key='x_a'),
        cirq.measure(q1, q2, q3, key='multi', invert_mask=(False, True)),
    )
Exemplo n.º 18
0
def test_is_supported():
    a = cirq.GridQubit(0, 0)
    b = cirq.GridQubit(0, 1)
    c = cirq.GridQubit(1, 0)
    assert cg.is_native_xmon_op(cirq.CZ(a, b))
    assert cg.is_native_xmon_op(cirq.X(a)**0.5)
    assert cg.is_native_xmon_op(cirq.Y(a)**0.5)
    assert cg.is_native_xmon_op(cirq.Z(a)**0.5)
    assert cg.is_native_xmon_op(
        cirq.PhasedXPowGate(phase_exponent=0.2).on(a)**0.5)
    assert cg.is_native_xmon_op(cirq.Z(a)**1)
    assert not cg.is_native_xmon_op(cirq.CCZ(a, b, c))
    assert not cg.is_native_xmon_op(cirq.SWAP(a, b))
Exemplo n.º 19
0
def test_router_bad_args():
    circuit = cirq.Circuit()
    device_graph = ccr.get_linear_device_graph(5)
    with pytest.raises(ValueError):
        ccr.route_circuit(circuit, device_graph)

    algo_name = 'greedy'
    with pytest.raises(ValueError):
        ccr.route_circuit(circuit,
                          device_graph,
                          algo_name=algo_name,
                          router=ccr.ROUTERS[algo_name])

    circuit = cirq.Circuit(cirq.CCZ(*cirq.LineQubit.range(3)))
    with pytest.raises(ValueError):
        ccr.route_circuit(circuit, device_graph, algo_name=algo_name)

    circuit = cirq.Circuit(
        cirq.CZ(cirq.LineQubit(i), cirq.LineQubit(i + 1)) for i in range(5))
    with pytest.raises(ValueError):
        ccr.route_circuit(circuit, device_graph, algo_name=algo_name)
Exemplo n.º 20
0
def test_diagram():
    a, b, c, d = cirq.LineQubit.range(4)
    circuit = cirq.Circuit.from_ops(cirq.TOFFOLI(a, b, c), cirq.CCX(a, c, b),
                                    cirq.CCZ(a, d, b), cirq.CSWAP(a, c, d),
                                    cirq.FREDKIN(a, b, c))
    assert circuit.to_text_diagram() == """
0: ───@───@───@───@───@───
      │   │   │   │   │
1: ───@───X───@───┼───×───
      │   │   │   │   │
2: ───X───@───┼───×───×───
              │   │
3: ───────────@───×───────
""".strip()
    assert circuit.to_text_diagram(use_unicode_characters=False) == """
0: ---@---@---@---@------@------
      |   |   |   |      |
1: ---@---X---@---|------swap---
      |   |   |   |      |
2: ---X---@---|---swap---swap---
              |   |
3: -----------@---swap----------
""".strip()
Exemplo n.º 21
0
                          cirq.CCNotPowGate())
    eq.add_equality_group(cirq.CCZPowGate(), cirq.CCZPowGate())


def test_identity_multiplication():
    a, b, c = cirq.LineQubit.range(3)
    assert cirq.CCX(a, b, c) * cirq.I(a) == cirq.CCX(a, b, c)
    assert cirq.CCX(a, b, c) * cirq.I(b) == cirq.CCX(a, b, c)
    assert cirq.CCX(a, b, c)**0.5 * cirq.I(c) == cirq.CCX(a, b, c)**0.5
    assert cirq.I(c) * cirq.CCZ(a, b, c)**0.5 == cirq.CCZ(a, b, c)**0.5


@pytest.mark.parametrize(
    'op,max_two_cost',
    [
        (cirq.CCZ(*cirq.LineQubit.range(3)), 8),
        (cirq.CCX(*cirq.LineQubit.range(3)), 8),
        (cirq.CCZ(cirq.LineQubit(0), cirq.LineQubit(2), cirq.LineQubit(1)), 8),
        (cirq.CCZ(cirq.LineQubit(0), cirq.LineQubit(2), cirq.LineQubit(1))**
         sympy.Symbol("s"), 8),
        (cirq.CSWAP(*cirq.LineQubit.range(3)), 9),
        (cirq.CSWAP(*reversed(cirq.LineQubit.range(3))), 9),
        (cirq.CSWAP(cirq.LineQubit(1), cirq.LineQubit(0),
                    cirq.LineQubit(2)), 12),
        (
            cirq.ThreeQubitDiagonalGate([2, 3, 5, 7, 11, 13, 17, 19])(
                cirq.LineQubit(1), cirq.LineQubit(2), cirq.LineQubit(3)),
            8,
        ),
    ],
)
Exemplo n.º 22
0
 ])),
 ({
     cirq.X(q0): 2,
     cirq.Y(q1): 3
 }, np.array([
     [0, -3j, 2, 0],
     [3j, 0, 0, 2],
     [2, 0, 0, -3j],
     [0, 2, 3j, 0],
 ])),
 ({
     cirq.XX(q0, q1): 0.5,
     cirq.YY(q0, q1): -0.5
 }, np.rot90(np.diag([1, 0, 0, 1]))),
 ({
     cirq.CCZ(q0, q1, q2): 3j
 }, np.diag([3j, 3j, 3j, 3j, 3j, 3j, 3j, -3j])),
 ({
     cirq.I(q0): 0.1,
     cirq.CNOT(q1, q2): 1
 },
  np.array([
      [1.1, _, _, _, _, _, _, _],
      [_, 1.1, _, _, _, _, _, _],
      [_, _, 0.1, 1, _, _, _, _],
      [_, _, 1, 0.1, _, _, _, _],
      [_, _, _, _, 1.1, _, _, _],
      [_, _, _, _, _, 1.1, _, _],
      [_, _, _, _, _, _, 0.1, 1],
      [_, _, _, _, _, _, 1, 0.1],
  ])),
Exemplo n.º 23
0
@pytest.mark.parametrize(
    "op,expected",
    [
        (cirq.H(Q), True),
        (cirq.HPowGate(exponent=0.5)(Q), False),
        (cirq.PhasedXPowGate(exponent=0.25, phase_exponent=0.125)(Q), True),
        (cirq.XPowGate(exponent=0.5)(Q), True),
        (cirq.YPowGate(exponent=0.25)(Q), True),
        (cirq.ZPowGate(exponent=0.125)(Q), True),
        (cirq.CZPowGate(exponent=0.5)(Q, Q2), False),
        (cirq.CZ(Q, Q2), True),
        (cirq.CNOT(Q, Q2), True),
        (cirq.SWAP(Q, Q2), False),
        (cirq.ISWAP(Q, Q2), False),
        (cirq.CCNOT(Q, Q2, Q3), True),
        (cirq.CCZ(Q, Q2, Q3), True),
        (cirq.ParallelGate(cirq.X, num_copies=3)(Q, Q2, Q3), True),
        (cirq.ParallelGate(cirq.Y, num_copies=3)(Q, Q2, Q3), True),
        (cirq.ParallelGate(cirq.Z, num_copies=3)(Q, Q2, Q3), True),
        (cirq.X(Q).controlled_by(Q2, Q3), True),
        (cirq.Z(Q).controlled_by(Q2, Q3), True),
        (cirq.ZPowGate(exponent=0.5)(Q).controlled_by(Q2, Q3), False),
    ],
)
def test_gateset(op: cirq.Operation, expected: bool):
    gs = cirq_pasqal.PasqalGateset()
    assert gs.validate(op) == expected
    assert gs.validate(cirq.Circuit(op)) == expected


@pytest.mark.parametrize(
Exemplo n.º 24
0
def grover(error_correct=False):

    # initialize qubits with architecture in mind
    qubits = [cirq.GridQubit(1, 4), cirq.GridQubit(2, 4),\
              cirq.GridQubit(3, 4)]

    if error_correct:
        error_qubits = [cirq.GridQubit(3, 4), cirq.GridQubit(3, 3),\
                           cirq.GridQubit(3, 2), cirq.GridQubit(4, 3)]

    # construct circuit
    circuit = cirq.Circuit()

    # error correction setup. error correct qubit (2,3)
    if error_correct:
        circuit.append([cirq.CNOT(qubits[2], error_qubits[1])])
        circuit.append([cirq.SWAP(error_qubits[0], error_qubits[1])])
        circuit.append([cirq.CNOT(qubits[2], error_qubits[1])])
        circuit.append([cirq.SWAP(error_qubits[0], error_qubits[1])])

    # hadamards
    circuit.append([cirq.H(q) for q in qubits])

    # Grover's algorithm repetitions; O(sqrt(2^n)) = 2
    for _ in range(2):

        circuit.append([cirq.CCZ(*qubits)])

        circuit.append([cirq.H(q) for q in qubits])
        circuit.append([cirq.X(q) for q in qubits])
        circuit.append([cirq.CCZ(*qubits)])
        circuit.append([cirq.X(q) for q in qubits])
        circuit.append([cirq.H(q) for q in qubits])

    # error detection and correction
    if error_correct:
        circuit.append([cirq.SWAP(error_qubits[2], error_qubits[1])])
        circuit.append([cirq.CNOT(qubits[2], error_qubits[1])])
        circuit.append([cirq.SWAP(error_qubits[2], error_qubits[1])])
        circuit.append([cirq.CNOT(error_qubits[1], error_qubits[2])])
        circuit.append([cirq.SWAP(error_qubits[3], error_qubits[1])])
        circuit.append([cirq.CNOT(qubits[2], error_qubits[1])])
        circuit.append([cirq.CNOT(error_qubits[0], error_qubits[1])])
        circuit.append([cirq.SWAP(error_qubits[1], error_qubits[3])])
        circuit.append(
            [cirq.measure(error_qubits[2]),
             cirq.measure(error_qubits[3])])
        circuit.append(
            [cirq.CCNOT(qubits[2], error_qubits[1], error_qubits[0])])

    circuit.append([cirq.measure(q) for q in qubits])

    # check for sycamore
    cirq.google.optimized_for_sycamore(circuit=circuit,
                                       new_device=cirq.google.Sycamore,
                                       optimizer_type='sycamore')

    url = 'http://quant-edu-scalability-tools.wl.r.appspot.com/send'
    job_payload = {"circuit":cirq.to_json(circuit),\
        "email":"*****@*****.**",\
        "repetitions":1000,\
        "student_id":204929264}

    return requests.post(url, json=job_payload)
Exemplo n.º 25
0
def test_decompose_unsupported_gate():
    q0, q1, q2 = cirq.LineQubit.range(3)
    device = ionq.IonQAPIDevice(qubits=[q0, q1, q2])
    op = cirq.CCZ(q0, q1, q2)
    with pytest.raises(ValueError, match='not supported'):
        _ = device.decompose_operation(op)
Exemplo n.º 26
0
 cirq.Duration(picos=6),
 'DensePauliString':
 cirq.DensePauliString('XYZI', coefficient=1j),
 'DepolarizingChannel':
 cirq.DepolarizingChannel(0.5),
 'MutableDensePauliString':
 cirq.MutableDensePauliString('XXZZ', coefficient=-2),
 'FREDKIN':
 cirq.FREDKIN,
 'FSimGate':
 cirq.FSimGate(theta=0.123, phi=.456),
 'Foxtail':
 cirq.google.Foxtail,
 'GateOperation': [
     cirq.CCNOT(*cirq.LineQubit.range(3)),
     cirq.CCZ(*cirq.LineQubit.range(3)),
     cirq.CNOT(*cirq.LineQubit.range(2)),
     cirq.CSWAP(*cirq.LineQubit.range(3)),
     cirq.CZ(*cirq.LineQubit.range(2))
 ],
 'GeneralizedAmplitudeDampingChannel':
 cirq.GeneralizedAmplitudeDampingChannel(0.1, 0.2),
 'GlobalPhaseOperation':
 cirq.GlobalPhaseOperation(-1j),
 'GridQubit':
 cirq.GridQubit(10, 11),
 'H':
 cirq.H,
 'HPowGate': [cirq.HPowGate(exponent=-8), cirq.H**0.123],
 'I':
 cirq.I,
Exemplo n.º 27
0
    yield cirq.CCX(c1, c2, c3)
    yield (p**(-1))(t)
    yield cirq.CNOT(c3, t)
    # yield cirq.H(t)


bit_count = 4
qubits = [cirq.GridQubit(i, 0) for i in range(bit_count)]

c1, c2, c3, t = qubits

circuit = cirq.Circuit()
circuit.append(cirq.X(c1))
circuit.append(cirq.X(c2))
circuit.append(cirq.X(c3))
circuit.append(cirq.CCZ(c1, c2, c3))
result = cirq.Simulator().simulate(circuit)
for index, state in enumerate(result.final_state):
    print(index, state, abs(state))
print('----------------')
# circuit.append(cirq.measure(*qubits, key='m'))

circuit = cirq.Circuit()

circuit.append(cirq.X(c1))
circuit.append(cirq.X(c2))
circuit.append(cirq.X(c3))
circuit.append(cirq.X(t))

result = cirq.Simulator().simulate(circuit)
# for index, state in enumerate(result.final_state):
Exemplo n.º 28
0
def test_identity_multiplication():
    a, b, c = cirq.LineQubit.range(3)
    assert cirq.CCX(a, b, c) * cirq.I(a) == cirq.CCX(a, b, c)
    assert cirq.CCX(a, b, c) * cirq.I(b) == cirq.CCX(a, b, c)
    assert cirq.CCX(a, b, c)**0.5 * cirq.I(c) == cirq.CCX(a, b, c)**0.5
    assert cirq.I(c) * cirq.CCZ(a, b, c)**0.5 == cirq.CCZ(a, b, c)**0.5
Exemplo n.º 29
0
    undiagrammable_op = UndiagrammableGate()(qbits[1])

    c_op = cirq.ControlledOperation(qbits[:1], undiagrammable_op)
    assert cirq.circuit_diagram_info(c_op, default=None) is None


@pytest.mark.parametrize('gate', [
    cirq.X(cirq.NamedQubit('q1')),
    cirq.X(cirq.NamedQubit('q1'))**0.5,
    cirq.rx(np.pi)(cirq.NamedQubit('q1')),
    cirq.rx(np.pi / 2)(cirq.NamedQubit('q1')),
    cirq.Z(cirq.NamedQubit('q1')),
    cirq.H(cirq.NamedQubit('q1')),
    cirq.CNOT(cirq.NamedQubit('q1'), cirq.NamedQubit('q2')),
    cirq.SWAP(cirq.NamedQubit('q1'), cirq.NamedQubit('q2')),
    cirq.CCZ(cirq.NamedQubit('q1'), cirq.NamedQubit('q2'),
             cirq.NamedQubit('q3')),
    cirq.ControlledGate(cirq.ControlledGate(
        cirq.CCZ))(*cirq.LineQubit.range(5)),
    GateUsingWorkspaceForApplyUnitary()(cirq.NamedQubit('q1')),
    GateAllocatingNewSpaceForResult()(cirq.NamedQubit('q1')),
])
def test_controlled_operation_is_consistent(gate: cirq.GateOperation):
    cb = cirq.NamedQubit('ctr')
    cgate = cirq.ControlledOperation([cb], gate)
    cirq.testing.assert_implements_consistent_protocols(cgate)

    cgate = cirq.ControlledOperation([cb], gate, control_values=[0])
    cirq.testing.assert_implements_consistent_protocols(cgate)

    cb3 = cb.with_dimension(3)
    cgate = cirq.ControlledOperation([cb3], gate, control_values=[(0, 2)])
Exemplo n.º 30
0
def grover(error_correct=False):

	API_TOKEN = '7cf33cd2f0d7044af8518c33321fa74d7380d3ba58d08b271404e8226aa1f5490818ba86e1635f89e6c3cfbf10aa091ff04c1f5ff61f0f391ed780b4484e0b18'

	# initialize qiskit
	IBMQ.save_account(API_TOKEN)
	provider = IBMQ.load_account()
	print(provider.backends())
	backend = provider.backends.ibmq_16_melbourne
	
	# initialize qubits with architecture in mind
	qubits = [cirq.GridQubit(1, 4), cirq.GridQubit(2, 4),\
	          cirq.GridQubit(3, 4)]

	if error_correct:
		error_qubits = [cirq.GridQubit(3, 4), cirq.GridQubit(3, 3),\
	                    cirq.GridQubit(3, 2), cirq.GridQubit(4, 3)]

	# construct circuit
	circuit = cirq.Circuit()

	# error correction setup. error correct qubit (2,3)
	if error_correct:
		circuit.append([cirq.CNOT(qubits[2], error_qubits[1])])
		circuit.append([cirq.SWAP(error_qubits[0], error_qubits[1])])
		circuit.append([cirq.CNOT(qubits[2], error_qubits[1])])
		circuit.append([cirq.SWAP(error_qubits[0], error_qubits[1])])

	# hadamards
	circuit.append([cirq.H(q) for q in qubits])

	# Grover's algorithm repetitions; O(sqrt(2^n)) = 2
	for _ in range(2):

		circuit.append([cirq.CCZ(*qubits)])

		circuit.append([cirq.H(q) for q in qubits])
		circuit.append([cirq.X(q) for q in qubits])
		circuit.append([cirq.CCZ(*qubits)])
		circuit.append([cirq.X(q) for q in qubits])
		circuit.append([cirq.H(q) for q in qubits])

	# error detection and correction
	if error_correct:
		circuit.append([cirq.SWAP(error_qubits[2], error_qubits[1])])
		circuit.append([cirq.CNOT(qubits[2], error_qubits[1])])
		circuit.append([cirq.SWAP(error_qubits[2], error_qubits[1])])
		circuit.append([cirq.CNOT(error_qubits[1], error_qubits[2])])
		circuit.append([cirq.SWAP(error_qubits[3], error_qubits[1])])
		circuit.append([cirq.CNOT(qubits[2], error_qubits[1])])
		circuit.append([cirq.CNOT(error_qubits[0], error_qubits[1])])
		circuit.append([cirq.SWAP(error_qubits[1], error_qubits[3])])
		circuit.append([cirq.measure(error_qubits[2]), cirq.measure(error_qubits[3])])
		circuit.append([cirq.CCNOT(qubits[2], error_qubits[1], error_qubits[0])])

	circuit.append([cirq.measure(q) for q in qubits])

	# export to qasm
	qasm_str = circuit.to_qasm()

	# import qiskit from qasm
	qiskit_circuit = qiskitqc.from_qasm_str(qasm_str)

	# run qiskit
	transpiled = transpile(qiskit_circuit, backend)
	qobj = assemble(transpiled, backend, shots=100)
	job = backend.run(qobj)
	print(job.job_id())
	result = job.result()
	counts = result.get_counts()
	delayed_result = backend.retrieve_job(job.job_id()).result()
	delayed_counts = delayed_result.get_counts()
	print(counts)
	print(delayed_counts)