Archived
1
0
This repository has been archived on 2023-07-24. You can view files and clone it, but cannot push or open issues or pull requests.
qalg/bench-cirq/grover_algorithm.py

62 lines
1.6 KiB
Python

# https://github.com/quantumlib/Cirq/blob/master/examples/grover.py
# https://quantum-ods.github.io/qmlcourse/book/qcalgo/ru/grovers_algorithm.html
from ctypes import wstring_at
from random import randint
from cirq import Circuit,X,H,CNOT,TOFFOLI,GridQubit,measure
from cirq import Simulator
from qiskit import IBMQ
from quantum_runner import quantum_simulate,setup_IBM,cirq_qasm
def oracle(iqs,oq,bits):
yield (X(q) for (q, bit) in zip(iqs,bits) if not bit)
yield (TOFFOLI(iqs[0],iqs[1],oq))
yield (X(q) for (q,bit) in zip(iqs,bits) if not bit)
circuit = Circuit()
qb_count = 2
iqs = [GridQubit(i,0) for i in range(qb_count)]
oq = GridQubit(qb_count,0)
bits = [randint(0, 1) for _ in range(qb_count)]
circuit.append([X(oq),H(oq),H.on_each(iqs)])
circuit.append(oracle(iqs,oq,bits))
# Строим оператор Гровера
circuit.append(H.on_each(iqs))
circuit.append(X.on_each(iqs))
circuit.append(H.on(iqs[1]))
circuit.append(CNOT.on(iqs[0],iqs[1]))
circuit.append(H.on(iqs[1]))
circuit.append(X.on_each(iqs))
circuit.append(H.on_each(iqs))
circuit.append(measure(iqs, key="result"))
print(circuit)
result = Simulator().run(circuit,repetitions=10)
def bitstring(bits):
return ''.join(str(int(b)) for b in bits)
frequencies = result.histogram(key='result',fold_func=bitstring)
print(f"результат",frequencies)
print(f"наиболее распространеная битовая строка",frequencies.most_common(1)[0][0])
setup_IBM()
provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main')
quantum_simulate(
cirq_qasm(circuit),
provider.get_backend('ibmq_lima'),
True
)