-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfactoring_4x4.py
More file actions
73 lines (52 loc) · 2.5 KB
/
factoring_4x4.py
File metadata and controls
73 lines (52 loc) · 2.5 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
### Use this file only to make 3x3->6 bit mutliplication. For other multiplications use another file
# Constrain satisfaction problem
import dwavebinarycsp as dbc
# Set an integer to factor
P = 49
# A binary representation of P ("{:06b}" formats for 6-bit binary)
bP = "{:06b}".format(P)
## Obtains a multiplication circuit of 3 bits
csp = dbc.factories.multiplication_circuit(3)
## Convert the problem from CSP to BQM (min_classical_gap - gap between energies of wrong results)
bqm = dbc.stitch(csp, min_classical_gap=.1)
## This is the result of multiplication
p_vars = ['p0','p1','p2','p3','p4','p5']
## Make a dictionary of p_vars and P in binary
fixed_variables = dict(zip(reversed(p_vars),"{:06b}".format(P)))
fixed_variables = {var: int(x) for (var,x) in fixed_variables.items()}
## Fix the result of the product (kind of making a constrain).
## As a resul all 'p0',...,'p5' will be removed from the bqm.
for var, value in fixed_variables.items():
bqm.fix_variable(var, value)
## SETTING UP A SOLVER
from helpers.solvers import default_solver
#my_solver, my_token = default_solver()
from dwave.system.samplers import DWaveSampler
#sampler = DWaveSampler(solver={'qpu': True}) # Some accounts need to replace this line with the next:
sampler = DWaveSampler(solver={'qpu': True}, token='DEV-7201bbe105379663905954b7ed302eed2bd97866')
_, target_edgelist, target_adjacency = sampler.structure
## embedding
from dwave.embedding import embed_bqm, unembed_sampleset
from helpers.embedding import embeddings
## Embedding logical qubits to physical ones
embedding = embeddings[sampler.solver.id]
## Set connections betweeen physical qubits
bqm_embedded = embed_bqm(bqm, embedding, target_adjacency, 4.0)
#print(bqm_embedded)
# Return num_reads solutions (responses are in the D-Wave's graph of indexed qubits)
kwargs = {}
if 'num_reads' in sampler.parameters:
kwargs['num_reads'] = 50
if 'answer_mode' in sampler.parameters:
kwargs['answer_mode'] = 'histogram'
response = sampler.sample(bqm_embedded, **kwargs)
print("A solution indexed by qubits: \n", next(response.data(fields=['sample'])))
# Map back to the BQM's graph (nodes labeled "a0", "b0" etc,)
response = unembed_sampleset(response, embedding, source_bqm=bqm)
print("\nThe solution in problem variables: \n",next(response.data(fields=['sample'])))
from helpers.convert import to_base_ten
# Select just the first sample.
sample = next(response.samples(n=1))
dict(sample)
a, b = to_base_ten(sample)
print("Given integer P={}, found factors a={} and b={}".format(P, a, b))