Exemplo n.º 1
0
def sum_qubits(a_bit, b_bit, carry_in):
    q0, q1, q2, q3, q4, q5, q6, q7 = cirq.LineQubit.range(8)

    # q0 qubit-ийг а битд зориулж хэрэглэнэ
    # q1 qubit-ийг б битд зориулж хэрэглэнэ
    # q2 qubit-ийг carry bit-д зориулна
    def assign_bit(bit, qubit):
        if bit == 1:
            yield cirq.X(qubit)

    circuit = cirq.Circuit(
        assign_bit(a_bit, q0),
        assign_bit(b_bit, q1),
        assign_bit(carry_in, q2),
        # AND1
        cirq.TOFFOLI(q0, q1, q3),
        # XOR1
        cirq.CNOT(q0, q4),
        cirq.CNOT(q1, q4),
        # XOR2
        cirq.CNOT(q2, q5),
        cirq.CNOT(q4, q5),
        # AND2
        cirq.TOFFOLI(q2, q4, q6),
        # OR
        cirq.X(q3),
        cirq.X(q6),
        cirq.TOFFOLI(q3, q6, q7),
        cirq.X(q7),  # carry out
        cirq.measure(q5, q7, key='results'))
    simulator = cirq.Simulator()
    result = simulator.run(circuit, repetitions=10).measurements['results'][0]
    return result[0], result[1]
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)
Exemplo n.º 3
0
 def _decompose_(self, qubits):
     anc = qubits[2:]  # ancilla
     res = [qubits[0], qubits[1]]
     # Non-leaf function
     func5 = Func5(4, is_inverse=self.is_inverse)
     func5R = Func5(4, is_inverse=(not self.is_inverse))
     nq0 = [qubits[0], qubits[1], anc[1], anc[2]]
     func6 = Func6(3, is_inverse=self.is_inverse)
     func6R = Func6(3, is_inverse=(not self.is_inverse))
     nq1 = [qubits[0], anc[0], anc[3]]
     if not self.is_inverse:
         # Compute
         yield func6(*nq1)
         yield cirq.TOFFOLI(anc[0], qubits[1], qubits[0])
         yield func5(*nq0)
         yield cirq.CNOT(anc[0], qubits[0])
         yield cirq.CNOT(qubits[1], qubits[0])
         # Store
         # Note: this version does not store results.
     else:
         yield cirq.CNOT(qubits[1], qubits[0])
         yield cirq.CNOT(anc[0], qubits[0])
         yield func5R(*nq0)
         yield cirq.TOFFOLI(anc[0], qubits[1], qubits[0])
         yield func6R(*nq1)
Exemplo n.º 4
0
 def _decompose_(self, qubits):
     anc = qubits[2:]  # ancilla
     res = [qubits[1]]
     # Non-leaf function
     func2 = Func2(5, is_inverse=self.is_inverse)
     func2R = Func2(5, is_inverse=(not self.is_inverse))
     nq0 = [qubits[1], qubits[0], anc[1], anc[2], anc[3]]
     func3 = Func3(3, is_inverse=self.is_inverse)
     func3R = Func3(3, is_inverse=(not self.is_inverse))
     nq1 = [qubits[0], qubits[1], anc[4]]
     func4 = Func4(3, is_inverse=self.is_inverse)
     func4R = Func4(3, is_inverse=(not self.is_inverse))
     nq2 = [anc[0], qubits[1], anc[5]]
     if not self.is_inverse:
         # Compute
         yield func3(*nq1)
         yield func4(*nq2)
         yield func2(*nq0)
         yield cirq.CNOT(qubits[1], qubits[0])
         yield cirq.CNOT(qubits[0], anc[0])
         yield cirq.TOFFOLI(qubits[1], qubits[0], anc[0])
         yield cirq.CNOT(anc[0], qubits[0])
         # Store
         # Note: this version does not store results.
     else:
         yield cirq.CNOT(anc[0], qubits[0])
         yield cirq.TOFFOLI(qubits[1], qubits[0], anc[0])
         yield cirq.CNOT(qubits[0], anc[0])
         yield cirq.CNOT(qubits[1], qubits[0])
         yield func2R(*nq0)
         yield func4R(*nq2)
         yield func3R(*nq1)
Exemplo n.º 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,
    )
Exemplo n.º 6
0
 def _decompose_(self, qubits):
     [ctrl, x, y, z] = qubits
     if self.is_inverse:
         yield cirq.TOFFOLI(x, y, z)
         yield cirq.CNOT(z, x)
         yield cirq.TOFFOLI(ctrl, x, y)
     else:
         yield cirq.TOFFOLI(ctrl, z, y)
         yield cirq.CNOT(z, x)
         yield cirq.TOFFOLI(x, y, z)
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 _decompose_(self, qubits):
     anc = qubits[2:]  # ancilla
     res = [qubits[1], qubits[0]]
     # Leaf function
     if not self.is_inverse:
         # Compute
         yield cirq.TOFFOLI(qubits[0], qubits[1], anc[0])
         # Store
         # Note: this version does not store results.
     else:
         # Uncompute
         yield cirq.TOFFOLI(qubits[0], qubits[1], anc[0])
Exemplo n.º 9
0
def test_from_moment():
    q_00, q_01, q_02, q_03 = [cirq.GridQubit(0, index) for index in range(4)]
    m = cirq.Moment(cirq.ISWAP(q_00, q_01) ** 0.5, cirq.ISWAP(q_02, q_03) ** 0.5)
    options = FloquetPhasedFSimCalibrationOptions(
        characterize_theta=True,
        characterize_zeta=True,
        characterize_chi=False,
        characterize_gamma=False,
        characterize_phi=True,
    )
    request = FloquetPhasedFSimCalibrationRequest.from_moment(m, options)
    assert request == FloquetPhasedFSimCalibrationRequest(
        gate=cirq.ISWAP ** 0.5, pairs=((q_00, q_01), (q_02, q_03)), options=options
    )

    non_identical = cirq.Moment(cirq.ISWAP(q_00, q_01) ** 0.5, cirq.ISWAP(q_02, q_03))
    with pytest.raises(ValueError, match='must be identical'):
        _ = FloquetPhasedFSimCalibrationRequest.from_moment(non_identical, options)

    sq = cirq.Moment(cirq.X(q_00))
    with pytest.raises(ValueError, match='must be two qubit gates'):
        _ = FloquetPhasedFSimCalibrationRequest.from_moment(sq, options)

    threeq = cirq.Moment(cirq.TOFFOLI(q_00, q_01, q_02))
    with pytest.raises(ValueError, match='must be two qubit gates'):
        _ = FloquetPhasedFSimCalibrationRequest.from_moment(threeq, options)

    not_gate = cirq.Moment(cirq.CircuitOperation(cirq.FrozenCircuit()))
    with pytest.raises(ValueError, match='must be two qubit gates'):
        _ = FloquetPhasedFSimCalibrationRequest.from_moment(not_gate, options)

    empty = cirq.Moment()
    with pytest.raises(ValueError, match='No gates found'):
        _ = FloquetPhasedFSimCalibrationRequest.from_moment(empty, options)
Exemplo n.º 10
0
    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
def BitFlipDecode(circuit, qubits, indices):
    circuit.append([
        cirq.CNOT(qubits[indices[0]], qubits[indices[1]]),
        cirq.CNOT(qubits[indices[0]], qubits[indices[2]]),
        cirq.TOFFOLI(qubits[indices[2]], qubits[indices[1]],
                     qubits[indices[0]])
    ])
    def controlled_swap_multiple_target(self, control, targets, decomposition_type):
        """
        :param control: control qubit
        :param targets: target qubits
        :return:
        """
        index = len(targets) // 2
        print(index)
        swap_moments = []
        swap_moments += [cirq.TOFFOLI(control, targets[i], targets[index + i]) for i in range(index)]

        swap_moments += [cirq.TOFFOLI(control, targets[index+i], targets[i]) for i in range(index)]

        swap_moments += [cirq.TOFFOLI(control, targets[i], targets[index + i]) for i in range(index)]

        return swap_moments
Exemplo n.º 13
0
 def optimization_at(
         self, circuit: cirq.Circuit, index: int,
         op: cirq.Operation) -> Optional[cirq.PointOptimizationSummary]:
     if len(op.qubits) > 3:
         raise ValueError(f'Four qubit ops not yet supported: {op}')
     new_ops = None
     if op.gate == cirq.SWAP or op.gate == cirq.CNOT:
         new_ops = cirq.google.optimized_for_sycamore(cirq.Circuit(op))
     if isinstance(op, cirq.ControlledOperation):
         qubits = op.sub_operation.qubits
         if op.gate.sub_gate == cirq.ISWAP:
             new_ops = controlled_iswap.controlled_iswap(
                 *qubits, *op.controls)
         if op.gate.sub_gate == cirq.ISWAP**-1:
             new_ops = controlled_iswap.controlled_iswap(*qubits,
                                                         *op.controls,
                                                         inverse=True)
         if op.gate.sub_gate == cirq.ISWAP**0.5:
             new_ops = controlled_iswap.controlled_sqrt_iswap(
                 *qubits, *op.controls)
         if op.gate.sub_gate == cirq.ISWAP**-0.5:
             new_ops = controlled_iswap.controlled_inv_sqrt_iswap(
                 *qubits, *op.controls)
         if op.gate.sub_gate == cirq.X:
             if len(op.qubits) == 2:
                 new_ops = cirq.google.optimized_for_sycamore(
                     cirq.Circuit(cirq.CNOT(*op.controls, *qubits)))
             if len(op.qubits) == 3:
                 new_ops = cirq.google.optimized_for_sycamore(
                     cirq.Circuit(cirq.TOFFOLI(*op.controls, *qubits)))
     if new_ops:
         return cirq.PointOptimizationSummary(clear_span=1,
                                              clear_qubits=op.qubits,
                                              new_operations=new_ops)
def build_4qbits_circuit():
    num_qbits = 4

    qbits = [
        cirq.GridQubit(x, y) for x in range(num_qbits)
        for y in range(num_qbits)
    ]
    print(qbits)

    circuit = cirq.Circuit()

    # all gates applied to the circuit
    h1 = cirq.H(qbits[2])
    toffoli = cirq.TOFFOLI(qbits[2], qbits[3], qbits[4])
    h2 = cirq.H(qbits[1])
    h3 = cirq.H(qbits[2])
    h4 = cirq.H(qbits[3])
    cz1 = cirq.CZ(qbits[2], qbits[1])
    cz2 = cirq.CZ(qbits[2], qbits[3])

    # moments of gates to apply on circuit
    moment1 = cirq.Moment([h1])
    moment2 = cirq.Moment([toffoli])
    moment3 = cirq.Moment([h1])
    moment4 = cirq.Moment([h2, h3, h4])
    moment5 = cirq.Moment([cz1])
    moment6 = cirq.Moment([cz2])
    moment7 = cirq.Moment([h2, h3, h4])

    circuit = cirq.Circuit(
        (moment1, moment2, moment3, moment4, moment5, moment6, moment7))

    print(circuit)

    return circuit
def QNPU2B(l_old,l_new,n):
    ctrl,q0,q1 = [cirq.GridQubit(0, 0), cirq.GridQubit(0, 1), cirq.GridQubit(0, 2)]
    
    U1=cirq.ControlledGate(U(l_old))
    U2=cirq.ControlledGate(cirq.inverse(U(l_new)))
    
    circuit = cirq.Circuit(cirq.H(ctrl), cirq.S(ctrl),U1.on(ctrl,q0,q1),
                           cirq.CNOT(ctrl,q1),
                           cirq.TOFFOLI(ctrl,q1,q0),
                           U2.on(ctrl,q0,q1),
                           cirq.H(ctrl),
                           cirq.measure(ctrl,key='c'),
                           strategy=cirq.InsertStrategy.EARLIEST)
    
    
    simulator = cirq.Simulator()
    result=simulator.run(circuit, repetitions=n)
    m=result.histogram(key='c')
    
    for i,j in m.items():
        if i==0:
            term=2*(j/n)-1
        elif i==1:
            term=1-2*(j/n)
    
    return term
Exemplo n.º 16
0
def test_nonoptimal_toffoli_circuit():
    q0, q1, q2 = cirq.LineQubit.range(3)
    cirq.testing.assert_allclose_up_to_global_phase(
        cirq.testing.nonoptimal_toffoli_circuit(q0, q1,
                                                q2).to_unitary_matrix(),
        cirq.unitary(cirq.TOFFOLI(q0, q1, q2)),
        atol=1e-7)
Exemplo n.º 17
0
def test_toffoli():
    a, b, c, d = cirq.LineQubit.range(4)

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

    # With exponent. Doesn't merge with other operation.
    circuit = cirq.Circuit.from_ops(cirq.CCX(a, b, c)**0.5, cirq.H(d))
    assert_links_to(circuit,
                    """
        http://algassert.com/quirk#circuit={"cols":[
            ["•","•","X^½"],[1,1,1,"H"]]}
    """,
                    escape_url=False)

    # Unknown exponent.
    circuit = cirq.Circuit.from_ops(cirq.CCX(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)
Exemplo n.º 18
0
def make_oracle(input_qubits, output_qubit, x_bits):
    """Implement function {f(x) = 1 if x==x', f(x) = 0 if x!= x'}."""
    # Make oracle.
    # for (1, 1) it's just a Toffoli gate
    # otherwise negate the zero-bits.
    yield(cirq.X(q) for (q, bit) in zip(input_qubits, x_bits) if not bit)
    yield(cirq.TOFFOLI(input_qubits[0], input_qubits[1], output_qubit))
    yield(cirq.X(q) for (q, bit) in zip(input_qubits, x_bits) if not bit)
Exemplo n.º 19
0
def make_oracle(input_qubits, output_qubit, x_bits):
    """함수 {f(x) = 1 if x==x', f(x) = 0 if x!= x'}를 구현합니다."""
    # 양자 오라클을 생성합니다.
    # 입력 큐비트와 입력 x 비트가 (1, 1)인 경우 토폴리(Toffoli)게이트 입니다.
    # 그외의 모든 경우는 0 비트를 반전합니다.
    yield(cirq.X(q) for (q, bit) in zip(input_qubits, x_bits) if not bit)
    yield(cirq.TOFFOLI(input_qubits[0], input_qubits[1], output_qubit))
    yield(cirq.X(q) for (q, bit) in zip(input_qubits, x_bits) if not bit)
Exemplo n.º 20
0
    def _decompose_(self, qubits):
        n = int(len(qubits) / 5)
        # c = qubits[0:n*3:3]
        a = qubits[1:n * 3:3]
        # b = qubits[2::3]
        y = qubits[n * 3:n * 4]
        x = qubits[n * 4:]

        for i, x_i in enumerate(x):
            # a = (y*(2**i))*x_i
            for a_qubit, y_qubit in zip(a[i:], y[:n - i]):
                yield cirq.TOFFOLI(x_i, y_qubit, a_qubit)
            # b += a
            yield Adder(3 * n).on(*qubits[:3 * n])
            # a = 0
            for a_qubit, y_qubit in zip(a[i:], y[:n - i]):
                yield cirq.TOFFOLI(x_i, y_qubit, a_qubit)
Exemplo n.º 21
0
def controlled_inv_sqrt_iswap(a: cirq.Qid, b: cirq.Qid, c: cirq.Qid):
    """Performs (ISWAP(a,b)i**0.5).controlled_by(c)"""
    return cirq.google.optimized_for_sycamore(
        cirq.Circuit(
            cirq.CNOT(a, b),
            cirq.TOFFOLI(c, b, a)**0.5,
            cirq.CZ(c, b)**-0.25,
            cirq.CNOT(a, b),
        ))
Exemplo n.º 22
0
    def construct_circuit(self):
        circuit = cirq.Circuit()
        cnotcount = 0
        toffcount = 0

        # step 1
        for i in range(1, self.size):
            circuit.append(cirq.CNOT(self.A[i], self.B[i]))
            cnotcount += 1

        # step 2:
        circuit.append(cirq.decompose(cirq.TOFFOLI(self.ctrl, self.A[self.size - 1], self.B[self.size])))
        toffcount += 1
        for i in range(self.size - 2, 0, -1):
            circuit.append(cirq.CNOT(self.A[i], self.A[i + 1]))
            cnotcount += 1

        # step 3:
        for i in range(0, self.size - 1):
            circuit.append(cirq.decompose(cirq.TOFFOLI(self.A[i], self.B[i], self.A[i + 1])))
            toffcount += 1

        # step 4:
        circuit.append(cirq.decompose(cirq.TOFFOLI(self.A[self.size - 1], self.B[self.size - 1], self.B[self.size+1])))
        circuit.append(cirq.decompose(cirq.TOFFOLI(self.ctrl, self.B[self.size+1], self.B[self.size])))
        circuit.append(cirq.decompose(cirq.TOFFOLI(self.A[self.size - 1], self.B[self.size - 1], self.B[self.size+1])))
        circuit.append(cirq.decompose(cirq.TOFFOLI(self.ctrl, self.A[self.size - 1], self.B[self.size - 1])))
        toffcount += 4

        # step 5:
        for i in range(self.size - 2, -1, -1):
            circuit.append(cirq.decompose(cirq.TOFFOLI(self.A[i], self.B[i], self.A[i + 1])))
            circuit.append(cirq.decompose(cirq.TOFFOLI(self.ctrl, self.A[i], self.B[i])))
            toffcount += 2

        # step 6:
        for i in range(1, self.size - 1):
            circuit.append(cirq.CNOT(self.A[i], self.A[i + 1]))
            cnotcount += 1

        # step 7:
        for i in range(1, self.size):
            circuit.append(cirq.CNOT(self.A[i], self.B[i]))
            cnotcount += 1

        print("toffoli count in adder")
        print(toffcount)
        print("cnot count in adder")
        print(cnotcount)

        return circuit

    # Toff: n + 4 + 2(n-1)
    # CNOT:
Exemplo n.º 23
0
def test_nonoptimal_toffoli_circuit_device_deprecated():
    q0, q1, q2 = cirq.LineQubit.range(3)
    with cirq.testing.assert_deprecated('no longer include a device',
                                        deadline='v0.15'):
        cirq.testing.assert_allclose_up_to_global_phase(
            cirq.testing.nonoptimal_toffoli_circuit(
                q0, q1, q2, cirq.UNCONSTRAINED_DEVICE).unitary(),
            cirq.unitary(cirq.TOFFOLI(q0, q1, q2)),
            atol=1e-7,
        )
Exemplo n.º 24
0
def test_extra_cell_makers():
    assert (cirq.quirk_url_to_circuit(
        'http://algassert.com/quirk#circuit={"cols":[["iswap"]]}',
        extra_cell_makers=[
            cirq.interop.quirk.cells.CellMaker(
                identifier='iswap',
                size=2,
                maker=lambda args: cirq.ISWAP(*args.qubits))
        ],
    ) == cirq.Circuit(cirq.ISWAP(*cirq.LineQubit.range(2))))

    assert (cirq.quirk_url_to_circuit(
        'http://algassert.com/quirk#circuit={"cols":[["iswap"]]}',
        extra_cell_makers={'iswap': cirq.ISWAP},
    ) == cirq.Circuit(cirq.ISWAP(*cirq.LineQubit.range(2))))

    assert cirq.quirk_url_to_circuit(
        'http://algassert.com/quirk#circuit={"cols":[["iswap"], ["toffoli"]]}',
        extra_cell_makers=[
            cirq.interop.quirk.cells.CellMaker(
                identifier='iswap',
                size=2,
                maker=lambda args: cirq.ISWAP(*args.qubits)),
            cirq.interop.quirk.cells.CellMaker(
                identifier='toffoli',
                size=3,
                maker=lambda args: cirq.TOFFOLI(*args.qubits)),
        ],
    ) == cirq.Circuit([
        cirq.ISWAP(*cirq.LineQubit.range(2)),
        cirq.TOFFOLI(*cirq.LineQubit.range(3))
    ])

    assert cirq.quirk_url_to_circuit(
        'http://algassert.com/quirk#circuit={"cols":[["iswap"], ["toffoli"]]}',
        extra_cell_makers={
            'iswap': cirq.ISWAP,
            'toffoli': cirq.TOFFOLI
        },
    ) == cirq.Circuit([
        cirq.ISWAP(*cirq.LineQubit.range(2)),
        cirq.TOFFOLI(*cirq.LineQubit.range(3))
    ])
Exemplo n.º 25
0
    def test_decompose_complicated_circuit(self, apollo):
        """Can handle even 3-qubit gates.
        """
        q0, q1, q2 = cirq.NamedQubit.range(0, 3, prefix='qubit_')
        circuit = cirq.Circuit(cirq.H(q0), cirq.X(q1),
                               cirq.TOFFOLI(q0, q2, q1),
                               cirq.measure(q0, q1, q2, key='mk'))
        new = apollo.decompose_circuit(circuit)

        # still uses the original qubits, not device qubits
        assert circuit.all_qubits() == new.all_qubits()
        assert len(new) == 31
Exemplo n.º 26
0
 def construct_circuit(self):
     n = len(self.a)
     b = bin(self.c)[2:].zfill(n)[::-1]
     circuit = cirq.Circuit()
     moment1 = [cirq.CNOT(self.g[-1], self.ancilla)]
     moments, moment3 = [cirq.TOFFOLI(self.a[0], self.a[1], self.g[0])], []
     if b[1] == '1':
         moments += [cirq.X(self.a[1]), cirq.CNOT(self.a[1], self.g[0])]
     for i in range(2, n):
         moments += [cirq.TOFFOLI(self.g[i - 2], self.a[i], self.g[i - 1])]
         moment3 += [cirq.TOFFOLI(self.g[i - 2], self.a[i], self.g[i - 1])]
         if b[i] == '1':
             moments += [
                 cirq.X(self.a[i]),
                 cirq.CNOT(self.a[i], self.g[i - 1])
             ]
     circuit.append(moment1)
     circuit.append(moments[::-1])
     circuit.append(moment3)
     circuit.append(moment1)
     return circuit
Exemplo n.º 27
0
def main():
    a = cirq.NamedQubit('a')
    b = cirq.NamedQubit('b')
    c = cirq.NamedQubit('c')
    d = cirq.NamedQubit('d')
    e = cirq.NamedQubit('e')
    f = cirq.NamedQubit('f')

    m = cirq.T(a)
    circuit = cirq.Circuit()

    circuit.append(cirq.TOFFOLI(a, b, c))
    circuit.append(cirq.TOFFOLI(d, e, f))
    circuit.append(cirq.TOFFOLI(a, e, d))
    circuit.append(cirq.TOFFOLI(d, e, f))
    circuit.append(cirq.TOFFOLI(a, c, d))
    circuit.append(cirq.TOFFOLI(a, c, d))

    print(circuit)
    print(len(circuit))

    look = LookAheadAnalysis()
    analysis = look.lookahead(circuit, 3,
                              LookAheadAnalysis.find_parallel_Toffolis)

    print(analysis)
Exemplo n.º 28
0
def test_decompose_general():
    a, b, c = cirq.LineQubit.range(3)
    no_method = NoMethod()
    assert cirq.decompose(no_method) == [no_method]

    # Flattens iterables.
    assert cirq.decompose([cirq.SWAP(a, b), cirq.SWAP(a, b)]) == 2 * cirq.decompose(cirq.SWAP(a, b))

    # Decomposed circuit should be equivalent. The ordering should be correct.
    ops = cirq.TOFFOLI(a, b, c), cirq.H(a), cirq.CZ(a, c)
    cirq.testing.assert_circuits_with_terminal_measurements_are_equivalent(
        cirq.Circuit(ops), cirq.Circuit(cirq.decompose(ops)), atol=1e-8
    )
Exemplo n.º 29
0
def oracle(input_qubits, target_qubit, circuit, secret_element='01'):
    print(f"Element to be searched: {secret_element}")
    
    # Flip the qubits corresponding to the bits containing 0 
    for i, bit in enumerate(secret_element):
        if int(bit) == 0:
            circuit.append(cirq.X(input_qubits[i]))
    # Do a Conditional NOT using all input qubits as control
    circuit.append(cirq.TOFFOLI(*input_qubits, target_qubit))
    # Revert the input qubits to the state prior to Flipping 
    for i, bit in enumerate(secret_element):
        if int(bit) == 0:
            circuit.append(cirq.X(input_qubits[i]))
    return circuit
Exemplo n.º 30
0
def cucarroAdder(qubits, N, num_anc, j, with_inverse=False):
    ctrl = qubits[0]
    a = qubits[1:N + 1]
    b = qubits[N + 2:]
    cmaj = CMaj(4)

    anc = [
        cirq.GridQubit(i + j * num_anc + len(qubits), 0)
        for i in range(num_anc)
    ]
    cin = anc[0]
    cout = anc[1]
    for i in range(N):
        if (i == 0):
            x = cin
            y = a[0]
            z = b[0]
        else:
            x = b[i - 1]
            y = a[i]
            z = b[i]
        yield cmaj(*[ctrl, x, y, z])
    if with_inverse:
        # Copy
        yield cirq.TOFFOLI(ctrl, b[N - 1], cout)
        yield cirq.TOFFOLI(ctrl, cout, qubits[N + 1])
        # Uncompute
        for i in range(N - 1, -1, -1):
            if (i == 0):
                x = cin
                y = a[0]
                z = b[0]
            else:
                x = b[i - 1]
                y = a[i]
                z = b[i]
            yield cirq.inverse(cmaj(*[ctrl, x, y, z]))