コード例 #1
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))
コード例 #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)
コード例 #3
0
    def build_circuit(self,
                      input_1=None,
                      input_2=None,
                      input_1_transforms=None,
                      input_2_transforms=None):

        self.circuit = cirq.Circuit()
        if input_1 is not None:
            self.input_1 = input_1
        if input_2 is not None:
            self.input_2 = input_2
        if input_1_transforms is not None:
            for op in input_1_transforms:
                print(op)
                print(self.input_1)
                self.circuit.append(op.on_each(self.input_1))
        if input_2_transforms is not None:
            for op in input_2_transforms:
                self.circuit.append(op.on_each(self.input_2))

        # Ancilla in + state
        self.circuit.append(cirq.H(self.ancilla_qubit))
        # Swap states conditoned on the ancilla
        for i in range(len(self.input_1)):
            self.circuit.append(
                cirq.CSWAP(self.ancilla_qubit, self.input_1[i],
                           self.input_2[i]))
        # Hadamard Transform on Ancilla
        self.circuit.append(cirq.H(self.ancilla_qubit))
        if self.measure:
            self.circuit.append(cirq.measure(self.ancilla_qubit, key='m'))
        print(self.circuit)
コード例 #4
0
def test_fredkin():
    a, b, c = cirq.LineQubit.range(3)
    circuit = cirq.Circuit(cirq.FREDKIN(a, b, c))
    assert_links_to(circuit, """
        http://algassert.com/quirk#circuit={"cols":[["•","Swap","Swap"]]}
    """, escape_url=False)

    # Doesn't merge.
    x, y, z = cirq.LineQubit.range(3, 6)
    circuit = cirq.Circuit(cirq.CSWAP(a, b, c), cirq.CSWAP(x, y, z))
    assert_links_to(circuit, """
        http://algassert.com/quirk#circuit={"cols":[
            ["•","Swap","Swap"],
            [1,1,1,"•","Swap","Swap"]
        ]}
    """, escape_url=False)
コード例 #5
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,
    )
コード例 #6
0
ファイル: cirqSim.py プロジェクト: JanisM91/Quasim
    def buildCirqCircuit(self, qubits, circuit):
        cirqCircuit = cirq.Circuit()
        ## Instantiate a CNot Gate
        cNotGate = cirq.CNotGate()
        ## Instantiate a Swap Gate
        swapGate = cirq.SwapGate()
        control = 0
        controlFirst = False

        for j in range(len(circuit[0])):
            for i in range(len(circuit)):
                if circuit[i][j] == "Pauli-X-Gate":
                    cirqCircuit.append(cirq.X(qubits[i]))
                elif circuit[i][j] == "Pauli-Y-Gate":
                    cirqCircuit.append(cirq.Y(qubits[i]))
                elif circuit[i][j] == "Pauli-Z-Gate":
                    cirqCircuit.append(cirq.Z(qubits[i]))
                elif circuit[i][j] == "Hadamard Gate":
                    cirqCircuit.append(cirq.H(qubits[i]))
                elif circuit[i][j] == "S Gate":
                    cirqCircuit.append(cirq.S(qubits[i]))
                elif circuit[i][j] == "T Gate":
                    cirqCircuit.append(cirq.T(qubits[i]))
                elif circuit[i][j] == "Identity":
                    pass
                elif circuit[i][j] == "CNot Gate":
                    if controlFirst:
                        cirqCircuit.append(cNotGate(control, qubits[i]))
                    else:
                        cirqCircuit.append(cNotGate(qubits[i + 1], qubits[i]))
                elif circuit[i][j] == "Swap Gate":
                    cirqCircuit.append(cirq.swapGate(control, qubits[i]))
                elif circuit[i][j] == "Deutsch OracleC":
                    pass
                elif circuit[i][j] == "Deutsch Oracle":
                    if randint(0, 1) == 1:
                        cirqCircuit.append(cNotGate(qubits[i - 1], qubits[i]))
                    else:
                        pass
                elif circuit[i][j] == "Fredkin Gate":
                    cirqCircuit.append(
                        cirq.CSWAP(qubits[i], qubits[i + 1], qubits[i + 2]))
                elif circuit[i][j] == "Toffoli Gate":
                    cirqCircuit.append(
                        cirq.TOFFOLI(qubits[i - 2], qubits[i - 1], qubits[i]))
                elif "Control" in circuit[i][j]:
                    if not controlFirst:
                        control = qubits[i]
                        controlFirst = True
                elif "Measurement" in circuit[i][j]:
                    cirqCircuit.append(
                        cirq.measure(qubits[i], key=str(i) + " " + str(j)))

        if DEBUG:
            print(
                "Class: cirqSim Function: buildCirqCircuit Line: 42 Output: cirqCircuit after being completely build"
            )
            print(cirqCircuit)

        return cirqCircuit
コード例 #7
0
ファイル: qasm_output_test.py プロジェクト: zhoudaqing/Cirq
def _all_operations(q0, q1, q2, q3, q4, include_measurments=True):
    class DummyOperation(cirq.Operation, cirq.QasmConvertableOperation,
                         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.CSWAP(q0, q1, q2),
        cirq.ISWAP(q2, q0),  # Requires 2-qubit decomposition
        cirq.google.ExpZGate()(q3),
        cirq.google.ExpZGate(half_turns=0.75)(q3),
        cirq.google.ExpWGate(axis_half_turns=0.125, half_turns=0.25)(q1),
        cirq.google.Exp11Gate()(q0, q1),
        # Requires 2-qubit decomposition
        cirq.google.Exp11Gate(half_turns=1.25)(q0, 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(),
    )
コード例 #8
0
ファイル: qasm_output_test.py プロジェクト: wingers/Cirq
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(),
    )
コード例 #9
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)
コード例 #10
0
    def construct_circuit(self, control=None):
        """

        :param control: qubit controlling the operation
        :return: |ax%N>|0n>|0> if control is 1
                 |x>|0n>|0> otherwise
                 Note that in case a = 0 the result will be |x>|0n>|0>
        """
        # Size of x
        n = len(self.x)

        # | x > | b + ax % N > | 0 > if control is 1
        # | x > | b > | 0 > otherwise
        moments = self.multiplier(control).moments

        # SWAP operation
        if control is None:
            moments += [
                cirq.SWAP(self.x[i], self.product_register[i])
                for i in range(n)
            ]
        # Controlled SWAP
        else:
            moments += [
                cirq.CSWAP(control[0], self.x[i], self.product_register[i])
                for i in range(n)
            ]

        # Determining the inverse of x
        t1, x_inverse, t2 = extended_euclidean_alg(self.hardwired_constant,
                                                   self.N)

        # Resetting the middle register to | 0n >
        moments += ShorModularMultiplier(
            x=self.x,
            product_register=self.product_register,
            hardwired_constant=x_inverse,
            N=self.N,
            zero_qubit=self.zero_qubit).multiplier(control).moments[::-1]
        circuit = cirq.Circuit(moments)
        return circuit
コード例 #11
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)),
    )
コード例 #12
0
def controlled_modular_multiply(circuit, control, constant, modulus,
                                multiplier):
    """
    This function implements the operation (A*B mod C), where A and C are constants,
    and B is a qubit register representing a little-endian integer.

    Remarks:
        See the Q# source for the "ModularMultiplyByConstantLE" function at
        https://github.com/Microsoft/QuantumLibraries/blob/master/Canon/src/Arithmetic/Arithmetic.qs
    """

    summand = cirq.NamedQubit.range(len(multiplier), prefix="summand")

    controlled_modular_add_product(circuit, control, constant, modulus,
                                   multiplier, summand)

    for i in range(0, len(multiplier)):
        circuit.append(cirq.CSWAP(control, summand[i], multiplier[i]))

    inverse_mod_value = inverse_mod(constant, modulus)

    controlled_adjoint_modular_add_product(circuit, control, inverse_mod_value,
                                           modulus, multiplier, summand)
コード例 #13
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()
コード例 #14
0
    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,
        ),
    ],
)
def test_decomposition_cost(op: cirq.Operation, max_two_cost: int):
    ops = tuple(cirq.flatten_op_tree(cirq.decompose(op)))
    two_cost = len([e for e in ops if len(e.qubits) == 2])
    over_cost = len([e for e in ops if len(e.qubits) > 2])
    assert over_cost == 0
コード例 #15
0
def matrix_to_sycamore_operations(
        target_qubits: List[cirq.GridQubit],
        matrix: np.ndarray) -> Tuple[cirq.OP_TREE, List[cirq.GridQubit]]:
    """A method to convert a unitary matrix to a list of Sycamore operations.

    This method will return a list of `cirq.Operation`s using the qubits and (optionally) ancilla
    qubits to implement the unitary matrix `matrix` on the target qubits `qubits`.
    The operations are also supported by `cirq.google.gate_sets.SYC_GATESET`.

    Args:
        target_qubits: list of qubits the returned operations will act on. The qubit order defined by the list
            is assumed to be used by the operations to implement `matrix`.
        matrix: a matrix that is guaranteed to be unitary and of size (2**len(qs), 2**len(qs)).
    Returns:
        A tuple of operations and ancilla qubits allocated.
            Operations: In case the matrix is supported, a list of operations `ops` is returned.
                `ops` acts on `qs` qubits and for which `cirq.unitary(ops)` is equal to `matrix` up
                to certain tolerance. In case the matrix is not supported, it might return NotImplemented to
                reduce the noise in the judge output.
            Ancilla qubits: In case ancilla qubits are allocated a list of ancilla qubits. Otherwise
                an empty list.
        .
    """
    def optimize_circuit(circ):
        ouut = []
        converter = cirq.google.ConvertToSycamoreGates()
        for _ in circ.all_operations():
            ouut.append(converter.convert(_))
        return cirq.google.optimized_for_sycamore(
            cirq.Circuit(ouut), optimizer_type="sycamore"), []

    if np.trace(matrix) == len(matrix):
        return [], []

    if len(matrix) == 2:
        try:
            comparison = matrix == cirq.unitary(cirq.Z)
            if (comparison.all()): return cirq.Z(target_qubits[0]), []

            comparison = matrix == cirq.unitary(cirq.X)
            if (comparison.all()): return cirq.X(target_qubits[0]), []

            comparison = matrix == cirq.unitary(cirq.Y)
            if (comparison.all()): return cirq.Y(target_qubits[0]), []

            comparison = matrix == cirq.unitary(cirq.H)
            if (comparison.all()): return cirq.H.on(target_qubits[0]), []

            comparison = matrix == cirq.unitary(cirq.S)
            if (comparison.all()): return cirq.S(target_qubits[0]), []

            comparison = matrix == cirq.unitary(cirq.T)
            if (comparison.all()): return cirq.T(target_qubits[0]), []

        except [TypeError, ValueError]:
            return NotImplemented, []

    if len(matrix) == 4:
        try:
            comparison = matrix == cirq.unitary(cirq.CNOT)
            if (comparison.all()):
                return optimize_circuit(
                    cirq.Circuit(cirq.CNOT(target_qubits[0],
                                           target_qubits[1])))

            comparison = matrix == cirq.unitary(cirq.XX)
            if (comparison.all()):
                return optimize_circuit(
                    cirq.Circuit(cirq.XX(target_qubits[0], target_qubits[1])))

            comparison = matrix == cirq.unitary(cirq.YY)
            if (comparison.all()):
                return optimize_circuit(
                    cirq.Circuit(cirq.YY(target_qubits[0], target_qubits[1])))

            comparison = matrix == cirq.unitary(cirq.ZZ)
            if (comparison.all()):
                return optimize_circuit(
                    cirq.Circuit(cirq.ZZ(target_qubits[0], target_qubits[1])))

            comparison = matrix == cirq.unitary(cirq.google.SYC)
            if (comparison.all()):
                return optimize_circuit(
                    cirq.Circuit(
                        cirq.google.SYC(target_qubits[0], target_qubits[1])))

        except TypeError:
            return NotImplemented, []

    if len(matrix) == 8:
        try:
            comparison = matrix == cirq.unitary(cirq.CCX)
            if (comparison.all()):
                return optimize_circuit(
                    cirq.Circuit(
                        cirq.CCX(target_qubits[0], target_qubits[1],
                                 target_qubits[2])))

            comparison = matrix == cirq.unitary(cirq.CSWAP)
            if (comparison.all()):
                return optimize_circuit(
                    cirq.Circuit(
                        cirq.CSWAP(target_qubits[0], target_qubits[1],
                                   target_qubits[2])))

            comparison = matrix == cirq.unitary(cirq.CCZ)
            if (comparison.all()):
                return optimize_circuit(
                    cirq.Circuit(
                        cirq.CCZ(target_qubits[0], target_qubits[1],
                                 target_qubits[2])))

            comparison = matrix == cirq.unitary(
                cirq.ControlledGate(cirq.ISWAP**0.5, 1))
            if (comparison.all()):
                return cirq.ControlledGate(cirq.ISWAP**0.5, 1)

        except TypeError:
            return NotImplemented, []

    if len(matrix) == 16:
        try:
            comparison = matrix == cirq.unitary(
                cirq.ControlledGate(cirq.ISWAP**0.5, 2))
            if (comparison.all()):
                return optimize_circuit(
                    cirq.Circuit(
                        cirq.ControlledGate(sub_gate=cirq.ISWAP**0.5).on(
                            target_qubits[2], target_qubits[0],
                            target_qubits[1])))

        except TypeError:
            return NotImplemented, []

    return NotImplemented, []
コード例 #16
0
qubits = cirq.LineQubit.range(10)
c = cirq.Circuit()

q_qft = [qubits[0], qubits[1], qubits[2], qubits[3], qubits[4]]
c.append(cirq.H(qubits[0]))
c.append(cirq.H(qubits[1]))
c.append(cirq.H(qubits[2]))
c.append(cirq.H(qubits[3]))
c.append(cirq.H(qubits[4]))
c.append(cirq.X(qubits[5]))

c.append(cirq.CX(qubits[0], qubits[7]))

c.append(cirq.CCX(qubits[1], qubits[8], qubits[9]))
c.append(cirq.CCX(qubits[8], qubits[1], qubits[6]))
c.append(cirq.CSWAP(qubits[1], qubits[6], qubits[8]))
c.append(cirq.CSWAP(qubits[1], qubits[7], qubits[9]))
c.append(cirq.CSWAP(qubits[1], qubits[5], qubits[7]))

c.append(cirq.CSWAP(qubits[2], qubits[5], qubits[7]))
c.append(cirq.CSWAP(qubits[2], qubits[7], qubits[9]))
c.append(cirq.CSWAP(qubits[2], qubits[6], qubits[8]))
c.append(cirq.CCX(qubits[2], qubits[6], qubits[8]))
c.append(cirq.CCX(qubits[2], qubits[8], qubits[9]))

c.append(cirq.CCX(qubits[3], qubits[8], qubits[9]))
c.append(cirq.CCX(qubits[6], qubits[3], qubits[8]))
c.append(cirq.CSWAP(qubits[3], qubits[6], qubits[8]))
c.append(cirq.CSWAP(qubits[3], qubits[7], qubits[9]))
c.append(cirq.CSWAP(qubits[3], qubits[5], qubits[7]))
コード例 #17
0
    def dist_circuit(self, input_1_norm=1, input_2_norm=1, input_1=None,
                input_2=None, input_1_transforms=None, input_2_transforms=None,
                input_1_circuit=None,
                input_2_circuit=None):

        self.input_1_norm = input_1_norm
        self.input_2_norm = input_2_norm
        self.input_1_circuit = input_1_circuit
        self.input_2_circuit = input_2_circuit

        if input_1 is not None:
            self.input_1 = input_1

        if input_2 is not None:
            self.input_2 = input_2
        
            
        if input_1_transforms is not None:
            
            self.input_1_circuit = []
            
            for op in input_1_transforms:
                #print(op)
                #print(self.input_1)
                self.circuit.append(op.on_each(self.input_1))
                self.input_1_circuit.append(op.on_each(self.input_1))
        if input_2_transforms is not None:
            self.input_2_circuit = []
            for op in input_2_transforms:
                self.circuit.append(op.on_each(self.input_2))
                self.input_2_circuit.append(op.on_each(self.input_2))

        self.input_1_uncompute = cirq.inverse(self.input_1_circuit)
        self.input_2_uncompute = cirq.inverse(self.input_2_circuit)

        # Create the required state 1

        self.circuit.append(cirq.H(self.control_qubit))
        print("length",len(self.input_2))
        for i in range(len(self.input_2)):
            self.circuit.append(cirq.CSWAP(self.control_qubit, self.state_store_qubits[i], self.input_2[i]))
        #for c in self.input_1_uncompute:
        #    self.circuit.append(c[0].controlled_by(self.control_qubit))
        #self.circuit.append(cirq.X(self.input_1[0]).controlled_by(self.control_qubit))
        self.circuit.append(cirq.X(self.control_qubit))

        for i in range(len(self.input_1)):
            self.circuit.append(cirq.CSWAP(self.control_qubit, self.state_store_qubits[i], self.input_1[i]))
        #self.circuit.append(cirq.ControlledGate(self.input_2_uncompute)(self.control_qubit, *self.input_1))
        for c in self.input_2_uncompute:
            self.circuit.append(c[0].controlled_by(self.control_qubit))
        #self.circuit.append(cirq.X(self.input_1[0]).controlled_by(self.control_qubit))
        self.circuit.append(cirq.X(self.control_qubit))
        for c in self.input_1_uncompute:
            self.circuit.append(c[0].controlled_by(self.control_qubit))

        # Prepare the other state qubit 
        self.Z = self.input_1_norm**2 + self.input_2_norm**2
        print(self.Z) 
        theta = 2*math.acos(self.input_1_norm/np.sqrt(self.Z))
        print(theta)
        self.circuit.append(cirq.ry(theta)(self.other_state_qubits[0]))
        self.circuit.append(cirq.Z(self.other_state_qubits[0]))

        self.st = SwapTest(prepare_input_states=False, input_state_dim=4,nq=self.nq,measure=False)

        print(self.other_state_qubits)
        self.state = [self.control_qubit] + self.state_store_qubits
        self.st.build_circuit(input_1=self.state,input_2=self.other_state_qubits)
        self.circuit += self.st.circuit
        #print(self.circuit)
        #self.circuit.append(cirq.measure(*(self.input_1 + self.input_2), key='k'))
        self.circuit.append(cirq.measure(self.st.ancilla_qubit, key='k'))
        
        print(self.circuit)
コード例 #18
0
 def __call__(self, qubits):
     c, q0, q1 = qubits
     return cirq.decompose(cirq.CSWAP(c, q0, q1))
コード例 #19
0
ファイル: gateFredkin.py プロジェクト: JanisM91/test_cirq
def main():
    # Pick a qubit.
    q0 = cirq.GridQubit(0, 0)
    q1 = cirq.GridQubit(0, 1)
    q2 = cirq.GridQubit(0, 2)

    q3 = cirq.GridQubit(1, 0)
    q4 = cirq.GridQubit(1, 1)
    q5 = cirq.GridQubit(1, 2)

    q6 = cirq.GridQubit(2, 0)
    q7 = cirq.GridQubit(2, 1)
    q8 = cirq.GridQubit(2, 2)

    q9 = cirq.GridQubit(3, 0)
    q10 = cirq.GridQubit(3, 1)
    q11 = cirq.GridQubit(3, 2)

    q12 = cirq.GridQubit(4, 0)
    q13 = cirq.GridQubit(4, 1)
    q14 = cirq.GridQubit(4, 2)

    # Create a circuit
    circuit = cirq.Circuit.from_ops(
        cirq.CSWAP(q0, q1, q2),
        cirq.measure(q0, key='q0'),
        cirq.measure(q1, key='q1'),
        cirq.measure(q2, key='q2'),
        cirq.X(q3),
        cirq.CSWAP(q3, q4, q5),
        cirq.measure(q3, key='q3'),
        cirq.measure(q4, key='q4'),
        cirq.measure(q5, key='q5'),
        cirq.X(q6),
        cirq.X(q7),
        cirq.CSWAP(q6, q7, q8),
        cirq.measure(q6, key='q6'),
        cirq.measure(q7, key='q7'),
        cirq.measure(q8, key='q8'),
        cirq.X(q9),
        cirq.X(q10),
        cirq.X(q11),
        cirq.CSWAP(q9, q10, q11),
        cirq.measure(q9, key='q9'),
        cirq.measure(q10, key='q10'),
        cirq.measure(q11, key='q11'),
        cirq.X(q13),
        cirq.X(q14),
        cirq.CSWAP(q12, q13, q14),
        cirq.measure(q12, key='q12'),
        cirq.measure(q13, key='q13'),
        cirq.measure(q14, key='q14'),
    )
    print("Circuit:")
    print(circuit)

    # Simulate the circuit 50 times.
    simulator = cirq.google.XmonSimulator()
    result = simulator.run(circuit, repetitions=50)
    print("Results of simulation:")
    print(result)

    # Run the simulator with direct access to the wave function of the quantum processor
    resultw = simulator.simulate(circuit)
    print("Result from wave function:")
    print(resultw)
コード例 #20
0
def test_cirq_to_circuit() -> None:
    q0 = cq.LineQubit(0)
    q1 = cq.LineQubit(1)
    q2 = cq.LineQubit(2)

    gate = cirq_to_circuit(cq.Circuit(cq.X(q0)))[0]
    assert isinstance(gate, qf.X)
    assert gate.qubits == (0, )

    gate = cirq_to_circuit(cq.Circuit(cq.X(q1)**0.4))[0]
    assert isinstance(gate, qf.XPow)
    assert gate.qubits == (1, )

    gate = cirq_to_circuit(cq.Circuit(cq.CZ(q1, q0)))[0]
    assert isinstance(gate, qf.CZ)
    assert gate.qubits == (1, 0)

    gate = cirq_to_circuit(cq.Circuit(cq.CZ(q1, q0)**0.3))[0]
    assert isinstance(gate, qf.CZPow)
    assert gate.qubits == (1, 0)
    assert gate.param("t") == 0.3

    gate = cirq_to_circuit(cq.Circuit(cq.CNOT(q0, q1)))[0]
    assert isinstance(gate, qf.CNot)
    assert gate.qubits == (0, 1)

    gate = cirq_to_circuit(cq.Circuit(cq.CNOT(q0, q1)**0.25))[0]
    assert isinstance(gate, qf.CNotPow)
    assert gate.qubits == (0, 1)
    assert gate.param("t") == 0.25

    gate = cirq_to_circuit(cq.Circuit(cq.SWAP(q0, q1)))[0]
    assert isinstance(gate, qf.Swap)

    gate = cirq_to_circuit(cq.Circuit(cq.ISWAP(q0, q1)))[0]
    assert isinstance(gate, qf.ISwap)

    gate = cirq_to_circuit(cq.Circuit(cq.CSWAP(q0, q1, q2)))[0]
    assert isinstance(gate, qf.CSwap)

    gate = cirq_to_circuit(cq.Circuit(cq.CCX(q0, q1, q2)))[0]
    assert isinstance(gate, qf.CCNot)

    gate = cirq_to_circuit(cq.Circuit(cq.CCZ(q0, q1, q2)))[0]
    assert isinstance(gate, qf.CCZ)

    gate = cirq_to_circuit(cq.Circuit(cq.I(q0)))[0]
    assert isinstance(gate, qf.I)

    gate = cirq_to_circuit(cq.Circuit(cq.XX(q0, q2)))[0]
    assert isinstance(gate, qf.XX)
    assert gate.param("t") == 1.0

    gate = cirq_to_circuit(cq.Circuit(cq.XX(q0, q2)**0.3))[0]
    assert isinstance(gate, qf.XX)
    assert gate.param("t") == 0.3

    gate = cirq_to_circuit(cq.Circuit(cq.YY(q0, q2)))[0]
    assert isinstance(gate, qf.YY)
    assert gate.param("t") == 1.0

    gate = cirq_to_circuit(cq.Circuit(cq.YY(q0, q2)**0.3))[0]
    assert isinstance(gate, qf.YY)
    assert gate.param("t") == 0.3

    gate = cirq_to_circuit(cq.Circuit(cq.ZZ(q0, q2)))[0]
    assert isinstance(gate, qf.ZZ)
    assert gate.param("t") == 1.0

    gate = cirq_to_circuit(cq.Circuit(cq.ZZ(q0, q2)**0.3))[0]
    assert isinstance(gate, qf.ZZ)
    assert gate.param("t") == 0.3

    # Check that cirq's parity gates are the same as QF's XX, YY, ZZ
    # up to parity
    U = (cq.XX(q0, q2)**0.8)._unitary_()
    gate0 = qf.Unitary(U, [0, 1])
    assert qf.gates_close(gate0, qf.XX(0.8, 0, 1))

    U = (cq.YY(q0, q2)**0.3)._unitary_()
    gate0 = qf.Unitary(U, [0, 1])
    assert qf.gates_close(gate0, qf.YY(0.3, 0, 1))

    U = (cq.ZZ(q0, q2)**0.2)._unitary_()
    gate0 = qf.Unitary(U, [0, 1])
    assert qf.gates_close(gate0, qf.ZZ(0.2, 0, 1))
コード例 #21
0
ファイル: json_test.py プロジェクト: c-poole/Cirq
 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,
 'ISWAP':
 cirq.ISWAP,