You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

289 lines
8.8 KiB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
  1. #!/usr/bin/env python3
  2. from util.kSAT import kSAT
  3. import util.randomSAT as rand_sat
  4. import util.SAT2QUBO as SAT2QUBO
  5. import util.script as script
  6. import util.queries as queries
  7. import util.graph as graph
  8. from dwave.system.composites import FixedEmbeddingComposite
  9. import dimod
  10. from neal import SimulatedAnnealingSampler
  11. import minorminer
  12. import networkx as nx
  13. import dwave_networkx as dnx
  14. import dwave.embedding
  15. from dwave.cloud import Client
  16. from dwave.cloud import Future
  17. from dwave.system.samplers import DWaveSampler
  18. from dwave_qbsolv import QBSolv
  19. import numpy as np
  20. import random
  21. from tqdm import tqdm
  22. def main():
  23. #__wmis()
  24. #__pqubo()
  25. __wmis3()
  26. def __qubo_to_nx_graph(qubo):
  27. graph = nx.Graph()
  28. for coupler, energy in qubo.items():
  29. if coupler[0] != coupler[1]:
  30. graph.add_edge(coupler[0], coupler[1], weight=energy)
  31. return graph
  32. def __wmis2():
  33. db = script.connect_to_instance_pool("dbc")
  34. target_graph = dnx.chimera_graph(16, 16, 4)
  35. target_graph_id = queries.get_id_of_solver_graph(db["solver_graphs"],
  36. nx.node_link_data(target_graph))
  37. instance_id = "5c9ccb998c6fe61926458351"
  38. qubo, wmis_id = queries.load_WMIS_qubo_of_instance(db["wmis_qubos"], instance_id)
  39. emb = queries.load_embedding(db["embeddings"], wmis_id, target_graph_id)
  40. chimera_sampler = dimod.StructureComposite(SimulatedAnnealingSampler(),
  41. target_graph.nodes(),
  42. target_graph.edges())
  43. sampler = FixedEmbeddingComposite(chimera_sampler, emb)
  44. res = sampler.sample_qubo(__negate_qubo(qubo))
  45. print(res.first)
  46. def __wmis3():
  47. db = script.connect_to_instance_pool()
  48. target_graph = dnx.chimera_graph(16, 16, 4)
  49. target_graph_id = queries.get_id_of_solver_graph(db["solver_graphs"],
  50. nx.node_link_data(target_graph))
  51. solver_input_query = queries.WMIS_solver_input_scope_query(db)
  52. solver_input_query.query("c42_vLogistic_6", target_graph_id)
  53. base_sampler = SimulatedAnnealingSampler()
  54. #base_sampler = QBSolv()
  55. chimera_sampler = dimod.StructureComposite(base_sampler,
  56. target_graph.nodes(),
  57. target_graph.edges())
  58. for solver_input in tqdm(solver_input_query):
  59. sampler = FixedEmbeddingComposite(chimera_sampler, solver_input["embeddings"][0])
  60. #res = sampler.sample_qubo(solver_input["qubo"], solver_limit=2048)
  61. res = sampler.sample_qubo(solver_input["qubo"])
  62. script.save_result(db["wmis_siman_results"],
  63. res,
  64. solver_input,
  65. 0,
  66. 1)
  67. def __wmis_qpu():
  68. db = script.connect_to_instance_pool()
  69. base_solver = DWaveSampler()
  70. solver_graph = graph.create_qpu_solver_nxgraph(base_solver)
  71. solver_graph_id = queries.get_id_of_solver_graph(db["solver_graphs"],
  72. nx.node_link_data(solver_graph))
  73. solver_input_query = queries.WMIS_solver_input_scope_query(db)
  74. solver_input_query.query("c42_vLogistic_6", solver_graph_id)
  75. for solver_input in tqdm(solver_input_query):
  76. embedding = solver_input["embeddings"][0]
  77. qubo = solver_input["qubo"]
  78. solver = FixedEmbeddingComposite(base_solver, embedding)
  79. res = solver.sample_qubo(qubo, annealing_time=5)
  80. script.save_result(db["wmis_qpu_results"],
  81. res,
  82. solver_input,
  83. emb_list_index = 0,
  84. run = 1)
  85. def __wmis():
  86. sat = rand_sat.generateRandomKSAT(25, 6, 3)
  87. qubo = __negate_qubo(SAT2QUBO.WMISdictQUBO(sat))
  88. #qubo = SAT2QUBO.WMISdictQUBO(sat)
  89. nx_qubo = __qubo_to_nx_graph(qubo)
  90. target_graph = dnx.chimera_graph(16, 16, 4)
  91. emb = minorminer.find_embedding(nx_qubo.edges(),
  92. target_graph.edges(),
  93. return_overlap=True)
  94. if emb[1] != 1:
  95. print("no embedding found")
  96. return
  97. print(emb[0])
  98. chimera_sampler = dimod.StructureComposite(SimulatedAnnealingSampler(),
  99. target_graph.nodes(),
  100. target_graph.edges())
  101. sampler = FixedEmbeddingComposite(chimera_sampler, emb[0])
  102. res = sampler.sample_qubo(qubo)
  103. #res = SimulatedAnnealingSampler().sample_qubo(qubo)
  104. #dwave.embedding.chain_breaks.majority_vote(res, emb[0])
  105. first = res.first
  106. print("chain_break_fraction={}".format(first.chain_break_fraction))
  107. for lit, spin in first.sample.items():
  108. print(lit, spin)
  109. print("true count: {}".format(np.count_nonzero(list(first.sample.values()))))
  110. assignments = {}
  111. for coupler, energy in first.sample.items():
  112. var = abs(coupler[1])
  113. if var not in assignments:
  114. assignments[var] = {"all": []}
  115. if energy == 1:
  116. assignments[var]["all"].append(1 if coupler[1] > 0 else 0)
  117. __majority_vote(assignments)
  118. #for var, a in assignments.items():
  119. ##print(var, np.sort(a["all"]), __majority_percentage(a["all"]))
  120. #print(var, a)
  121. final = __extract_assignment(assignments)
  122. print(final)
  123. print("satisfies sat: {}".format(sat.checkAssignment(final)))
  124. def __optimize_assignment(sat, assignment, consistencies):
  125. rnd = random.Random()
  126. max_steps = 4000
  127. steps = 0
  128. while not sat.checkAssignment(assignment) and steps < max_steps:
  129. steps += 1
  130. for i in range(len(assignment)):
  131. if 0.9 * rnd.random() > consistencies[i]:
  132. assignment[i] = (1 + assignment[i]) % 2
  133. consistencies[i] = 1 - consistencies[i]
  134. print("steps: {}".format(steps))
  135. return assignment
  136. def __random_assignment(number_of_variables):
  137. rnd = random.Random()
  138. assignment = [rnd.choice([0, 1]) for i in range(number_of_variables)]
  139. consistencies = [0.5 for i in range(number_of_variables)]
  140. return assignment, consistencies
  141. def __extract_assignment(assignments):
  142. assignment = [0 for i in range(len(assignments))]
  143. for var, a in assignments.items():
  144. assignment[var - 1] = a["major"]
  145. return assignment
  146. def __extract_consistencies(assignments) :
  147. consistencies = [0.0 for i in range(len(assignments))]
  148. for var, a in assignments.items():
  149. consistencies[var - 1] = a["consistency"]
  150. return consistencies
  151. def __majority_vote(assignments):
  152. for var, a in assignments.items():
  153. assignments[var]["major"] = 1 if __true_percentage(a["all"]) >= 0.5 else 0
  154. assignments[var]["consistency"] = __majority_percentage(a["all"])
  155. def __true_percentage(a):
  156. if len(a) == 0:
  157. return 0
  158. return np.count_nonzero(a) / len(a)
  159. def __majority_percentage(a):
  160. true_perc = __true_percentage(a)
  161. return true_perc if true_perc >= 0.5 else 1 - true_perc
  162. def __pqubo():
  163. sat = rand_sat.generateRandomKSAT(25, 6, 3)
  164. ising = SAT2QUBO.primitiveQUBO(sat)
  165. nx_qubo = __qubo_to_nx_graph(ising)
  166. target_graph = dnx.chimera_graph(16, 16, 4)
  167. emb = minorminer.find_embedding(nx_qubo.edges(),
  168. target_graph.edges(),
  169. return_overlap=True)
  170. if emb[1] != 1:
  171. print("no embedding found")
  172. return
  173. chimera_sampler = dimod.StructureComposite(SimulatedAnnealingSampler(),
  174. target_graph.nodes(),
  175. target_graph.edges())
  176. sampler = FixedEmbeddingComposite(chimera_sampler, emb[0])
  177. h, J = __split_ising(ising)
  178. res = sampler.sample_ising(h, J)
  179. #res = QBSolv().sample_qubo(qubo, find_max=True)
  180. print(res.first)
  181. def __split_ising(ising):
  182. h = {}
  183. J = {}
  184. for coupler, energy in ising.items():
  185. if coupler[0] == coupler[1]:
  186. h[coupler[0]] = energy
  187. else:
  188. J[coupler] = energy
  189. return h, J
  190. def __negate_qubo(qubo):
  191. negative_qubo = {}
  192. for coupler, energy in qubo.items():
  193. negative_qubo[coupler] = -1 * energy
  194. return negative_qubo
  195. if __name__ == "__main__":
  196. main()