-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquantum.py
71 lines (61 loc) · 1.83 KB
/
quantum.py
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
import random
import operator
import copy
import math
from functools import reduce
from pyquil.quil import Program
from pyquil.api import QVMConnection
from pyquil.gates import *
qvm = QVMConnection()
currentBest = []
def generateInitialPopulation(sizePopulation, nBits):
population = []
for i in range(sizePopulation):
p = Program()
for i in range(nBits):
p += H(i)
population.append(p)
return population
def fitness(password, testWord):
if len(password) == len(testWord):
score = 0
i = 0
while i < len(password):
if password[i] == testWord[i]:
score += 1
i += 1
return score / len(password) * 100
def gradePopulation(qPop, password):
population = copy.deepcopy(qPop)
measuredPopulation = []
for individual in population:
runMeasurement = individual.measure_all()
measurement = qvm.run(runMeasurement)
measuredPopulation.append(''.join(map(str,measurement[0])))
populationGrades = []
for individual in measuredPopulation:
populationGrades.append((individual, fitness(password, individual)))
return sorted(populationGrades, key=lambda tup: tup[1], reverse=True)
def evolve(qPop, currentBest, theta):
gates = []
for i, bit in enumerate(currentBest):
if bit == "0":
gates.append(RY(-1 * theta, i))
elif bit == "1":
gates.append(RY(theta, i))
for individual in qPop:
for gate in gates:
individual += gate
return qPop
def runQuantumTrial(target, popSize, theta):
qPop = generateInitialPopulation(popSize, len(target))
p = gradePopulation(qPop, target)
count = 0
while p[0][0] != target:
currentBest = p[0][0]
qPop = evolve(qPop, currentBest, theta)
p = gradePopulation(qPop, target)
count += 1
if p[0][0] == target:
break
return count