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.

252 lines
7.5 KiB

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