-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsearch.py
More file actions
174 lines (147 loc) · 5.89 KB
/
search.py
File metadata and controls
174 lines (147 loc) · 5.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
#
# Grover's Search algorithm in quantum computing.
# Brute-force password cracking by taking an n-bit code and checking against an oracle function until the correct code is found.
# Unlike a traditional computer that would require 2^n-1 calls in the worst-case scenario, a quantum algorithm can solve this task in sqrt(2^n) calls.
# A code of 64 bits could take a classical computer hundreds of years to solve, while a quantum computer could solve it in just a few seconds.
#
# This example uses a simple code of just 2 bits: 00, 01, 10, 11
# In this case, we'll choose 01 as our secret code.
# The oracle function knows the code. How fast can your algorithm break it?
#
# Reference: http://kth.diva-portal.org/smash/get/diva2:1214481/FULLTEXT01.pdf
# Appendix A.2
#
# export PYTHONWARNINGS="ignore:Unverified HTTPS request"
# python3 search.py
#
import qiskit
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
from qiskit import IBMQ
import numpy as np
import operator
import time
import ast
import sys
from configparser import RawConfigParser
type = 'sim' # Run program on the simulator or real quantum machine.
shots = 1024 # Number of measurements (shots) per program execution.
trials = 10 # Number of trials to run the experiment in performing Grover's search on a secret key.
def run(program, type, shots = 1):
if type == 'real':
if not run.isInit:
# Setup the API key for the real quantum computer.
parser = RawConfigParser()
parser.read('config.ini')
# Read configuration values.
proxies = ast.literal_eval(parser.get('IBM', 'proxies')) if parser.has_option('IBM', 'proxies') else None
verify = (True if parser.get('IBM', 'verify') == 'True' else False) if parser.has_option('IBM', 'verify') else True
token = parser.get('IBM', 'key')
IBMQ.enable_account(token = token, proxies = proxies, verify = verify)
run.isInit = True
# Set the backend server.
backend = qiskit.providers.ibmq.least_busy(qiskit.IBMQ.backends(simulator=False))
# Execute the program on the quantum machine.
print("Running on", backend.name())
start = time.time()
job = qiskit.execute(program, backend)
result = job.result().get_counts()
stop = time.time()
print("Request completed in " + str(round((stop - start) / 60, 2)) + "m " + str(round((stop - start) % 60, 2)) + "s")
return result
else:
# Execute the program in the simulator.
print("Running on the simulator.")
start = time.time()
job = qiskit.execute(program, qiskit.Aer.get_backend('qasm_simulator'), shots=shots)
result = job.result().get_counts()
stop = time.time()
print("Request completed in " + str(round((stop - start) / 60, 2)) + "m " + str(round((stop - start) % 60, 2)) + "s")
return result
run.isInit = False
def generatePassword():
# Choose a random code for the oracle function.
password = np.random.randint(2, size=4)
# Convert the password array into an array of strings.
passwordStrArr = np.char.mod('%d', password)
# Convert the array of strings into a single string for display.
passwordStr = ''.join(passwordStrArr)
return password, passwordStr;
def oracle(program, qr, password):
# Find all bits with a value of 0.
indices = np.where(password == 0)[0]
# Invert the bits associated with a value of 0.
for i in range(len(indices)):
# We want to read bits, starting with the right-most value as index 0.
index = int(len(password) - 1 - indices[i])
# Invert the qubit.
program.x(qr[index])
def search(password):
# Grover's search algorithm on a 4-bit secret key.
# Create 2 qubits for the input array.
qr = QuantumRegister(4)
# Create 2 registers for the output.
cr = ClassicalRegister(4)
program = QuantumCircuit(qr, cr)
# Place the qubits into superposition to represent all possible values.
program.h(qr)
# Run oracle on key. Invert the 0-value bits.
oracle(program, qr, password)
# Apply Grover's algorithm with a triple controlled Pauli Z-gate (cccZ).
program.cu1(np.pi / 4, qr[0], qr[3])
program.cx(qr[0], qr[1])
program.cu1(-np.pi / 4, qr[1], qr[3])
program.cx(qr[0], qr[1])
program.cu1(np.pi/4, qr[1], qr[3])
program.cx(qr[1], qr[2])
program.cu1(-np.pi/4, qr[2], qr[3])
program.cx(qr[0], qr[2])
program.cu1(np.pi/4, qr[2], qr[3])
program.cx(qr[1], qr[2])
program.cu1(-np.pi/4, qr[2], qr[3])
program.cx(qr[0], qr[2])
program.cu1(np.pi/4, qr[2], qr[3])
# Reverse the inversions by the oracle.
oracle(program, qr, password)
# Amplification.
program.h(qr)
program.x(qr)
# Apply Grover's algorithm with a triple controlled Pauli Z-gate (cccZ).
program.cu1(np.pi/4, qr[0], qr[3])
program.cx(qr[0], qr[1])
program.cu1(-np.pi/4, qr[1], qr[3])
program.cx(qr[0], qr[1])
program.cu1(np.pi/4, qr[1], qr[3])
program.cx(qr[1], qr[2])
program.cu1(-np.pi/4, qr[2], qr[3])
program.cx(qr[0], qr[2])
program.cu1(np.pi/4, qr[2], qr[3])
program.cx(qr[1], qr[2])
program.cu1(-np.pi/4, qr[2], qr[3])
program.cx(qr[0], qr[2])
program.cu1(np.pi/4, qr[2], qr[3])
# Reverse the amplification.
program.x(qr)
program.h(qr)
# Measure the result.
program.barrier(qr)
program.measure(qr, cr)
return run(program, type, shots)
for i in range(trials):
# Generate a random password consisting of 4 bits.
password, passwordStr = generatePassword()
# Display the password.
print("The oracle password is " + passwordStr + ".")
sys.stdout.flush()
# Ask the quantum computer to guess the password.
computerResult = []
count = 0
while computerResult != passwordStr:
# Obtain a measurement and check if it matches the password (without error).
results = search(password)
print(results)
computerResult = max(results.items(), key=operator.itemgetter(1))[0]
print("The quantum computer guesses ")
print(computerResult)
count = count + 1
sys.stdout.flush()
print("Solved " + passwordStr + " in " + str(count) + " measurements.")