-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfactorize.py
More file actions
135 lines (124 loc) · 4.32 KB
/
factorize.py
File metadata and controls
135 lines (124 loc) · 4.32 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
from synthesis import *
from qiskit_ibm_runtime import (
QiskitRuntimeService,
SamplerV2,
RuntimeEncoder,
RuntimeDecoder,
)
from qiskit import qpy
from qiskit.transpiler import generate_preset_pass_manager
from qiskit.primitives import BitArray
import os
import json
from fractions import Fraction
a = 2
m = 1147
semi_classical = False # IBM seems to fail at compiling dynamic circuits
n : int = math.ceil(math.log2(m))
shots = 1024
optimization_level = 3
sampler_options = {
# "dynamical_decoupling": {
# "enable": True,
# "sequence_type": "XpXm",
# },
# "twirling": {
# "enable_gates": True,
# },
}
backend_name = "ibm_marrakesh"
print("fetching backend...")
if backend_name is None:
min_num_qubits = 2*n+incr_ancilla(n//2+1)+3 if semi_classical else 4*n+incr_ancilla(n//2+1)+2
backend = QiskitRuntimeService().least_busy(min_num_qubits=min_num_qubits)
else:
backend = QiskitRuntimeService().backend(backend_name)
print(f"{backend.name}, {backend.num_qubits} qubits")
filename_postfix = "semi" if semi_classical else "full"
raw_circuit_filename = f"circuits/{a}_mod_{m}_{filename_postfix}.qpy"
transpiled_circuit_filename = f"circuits/{a}_mod_{m}_{filename_postfix}_{backend.name}.qpy"
result_filename = f"results/{a}_mod_{m}_{filename_postfix}_{shots}.json"
def log_qc(qc : QuantumCircuit):
print(f"size: {qc.size()}, depth: {qc.depth()}, qubits: {qc.num_qubits}")
print(dict(qc.count_ops()))
def get_raw(filename = raw_circuit_filename) -> QuantumCircuit:
if os.path.exists(filename):
print(f"'{filename}' exists, loading...")
with open(filename, "rb") as fd:
qc = qpy.load(fd)[0]
log_qc(qc)
return qc
else:
print("building circuits...")
if semi_classical:
qc = shor_semiclassical(a, m)
else:
qc = shor_qft(a, m)
log_qc(qc)
print(f"dumping to '{filename}'...")
with open(filename, "wb") as fd:
qpy.dump(qc, fd)
return qc
def get_transpiled(filename = transpiled_circuit_filename) -> QuantumCircuit:
if os.path.exists(filename):
print(f"'{filename}' exists, loading...")
with open(filename, "rb") as fd:
transpiled = qpy.load(fd)[0]
log_qc(transpiled)
return transpiled
else:
qc = get_raw()
pm = generate_preset_pass_manager(optimization_level=optimization_level, backend=backend)
print("transpiling...")
transpiled = pm.run(qc)
log_qc(transpiled)
print(f"dumping to '{filename}'...")
with open(filename, "wb") as fd:
qpy.dump(transpiled, fd)
return transpiled
def get_result(filename = result_filename) -> BitArray:
if os.path.exists(filename):
print(f"'{filename}' exists, loading...")
with open(filename, "r") as fd:
return json.load(fd, cls=RuntimeDecoder)
else:
transpiled = get_transpiled()
sampler = SamplerV2(mode=backend, options=sampler_options)
print("submitting job...")
job = sampler.run([transpiled], shots=shots)
print("fetching result...")
result : BitArray = job.result()[0].data["res"]
print("dumping to '{filename}...'")
with open(filename, "w") as fd:
json.dump(result, fd, cls=RuntimeEncoder)
return result
def analyze_result(result : BitArray):
counts = result.get_int_counts()
checked = set()
ord_multiples = set()
for k, v in counts.items():
frac = Fraction(k, 2**(2*n))
r = frac.limit_denominator(m).denominator
if r in checked:
continue
checked.add(r)
pow = pow_mod(a, r, m)
if pow == 1:
print(f"{a}^{r} = 1 mod {m}!")
ord_multiples.add(r)
if len(ord_multiples) == 0:
print(f"could not find the order. maybe shots ({shots}) is too low?")
return
min_ord = min(ord_multiples)
print(f"the minimum candidate is {min_ord}.")
if min_ord % 2 == 1:
print(f"{min_ord} is odd. try changing a.")
exit()
_, _, d = bezout(a**(min_ord//2) - 1, m)
if d == 1 or d == m:
print("produced factor is trivial. try changing a.")
else:
print(f"found a non-trivial factor {d}!")
if __name__ == "__main__":
result = get_result()
analyze_result(result)