forked from rigetti/pyquil
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquantum_die.py
76 lines (67 loc) · 2.11 KB
/
quantum_die.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
72
73
74
75
76
#!/usr/bin/env python
##############################################################################
# Copyright 2016-2017 Rigetti Computing
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
##############################################################################
import math
from functools import reduce
import pyquil.quil as pq
from pyquil import api
from pyquil.gates import H
from six.moves import range
def qubits_needed(n):
"""
The number of qubits needed for a die of n faces.
"""
return int(math.ceil(math.log(n, 2)))
def die_program(n):
"""
Generate a quantum program to roll a die of n faces.
"""
prog = pq.Program()
qubits = qubits_needed(n)
# Hadamard initialize.
for q in range(qubits):
prog.inst(H(q))
# Measure everything.
for q in range(qubits):
prog.measure(q, [q])
return prog
def process_result(r):
"""
Convert a list of measurements to a die value.
"""
return reduce(lambda s, x: 2*s + x, r, 0)
BATCH_SIZE = 10
dice = {}
qvm = api.QVMConnection()
def roll_die(n):
"""
Roll an n-sided quantum die.
"""
addresses = list(range(qubits_needed(n)))
if not n in dice:
dice[n] = die_program(n)
die = dice[n]
# Generate results and do rejection sampling.
while True:
results = qvm.run(die, addresses, BATCH_SIZE)
for r in results:
x = process_result(r)
if 0 < x <= n:
return x
if __name__ == '__main__':
number_of_sides = int(input("Please enter number of sides: "))
while True:
print(roll_die(number_of_sides))