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.

452 lines
15 KiB

6 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
6 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
5 years ago
5 years ago
5 years ago
5 years ago
  1. import configparser
  2. import os
  3. import argparse
  4. import pymongo
  5. import ssl
  6. import mysql.connector
  7. import networkx as nx
  8. from . import queries
  9. from . import graph
  10. from . import SAT2QUBO
  11. import minorminer
  12. from tqdm import tqdm
  13. import numpy as np
  14. import random
  15. import sys
  16. def readConfig(configFilePath):
  17. config = configparser.ConfigParser()
  18. if os.path.isfile(configFilePath):
  19. config.read(configFilePath)
  20. return config
  21. class ArgParser:
  22. def __init__(self):
  23. self.__flags = {}
  24. self.__parser = argparse.ArgumentParser()
  25. self.__instanceDirArgSet = False
  26. self.__config = None
  27. self.__parsedArgs = {}
  28. def addArg(self, alias,
  29. shortFlag,
  30. longFlag,
  31. help,
  32. type,
  33. default=None,
  34. ignoreDatabaseConfig=False):
  35. self.__flags[alias] = {"longFlag": longFlag,
  36. "hasDefault": False,
  37. "ignoreDatabaseConfig": ignoreDatabaseConfig,
  38. "type": type}
  39. if default != None:
  40. self.__flags[alias]["hasDefault"] = True
  41. self.__parser.add_argument("-%s" % shortFlag,
  42. "--%s" % longFlag,
  43. help=help,
  44. type=type,
  45. default=default)
  46. def addInstanceDirArg(self):
  47. self.__instanceDirArgSet = True
  48. self.addArg(alias="datasetDir", shortFlag="d", longFlag="dataset_dir",
  49. help="the base direcotry of the dataset; if this flag is given the others can be omitted",
  50. type=str, ignoreDatabaseConfig=True)
  51. def parse(self):
  52. self.__parsedArgs = {}
  53. args = vars(self.__parser.parse_args())
  54. if self.__instanceDirArgSet:
  55. self.__config = readConfig(os.path.join(args["dataset_dir"],
  56. "dataset.config"))
  57. self.__parseDatasetConfig()
  58. for alias, flag in self.__flags.items():
  59. self.__parsedArgs[alias] = self.__processFlag(args, flag)
  60. self.__config = None
  61. return self.__parsedArgs
  62. def __parseDatasetConfig(self):
  63. for flag, value in self.__config["STRUCTURE"].items():
  64. self.__parsedArgs[flag] = value
  65. def __processFlag(self, args, flag):
  66. longFlag = flag["longFlag"]
  67. tmpValue = self.__parsedArgs[longFlag] if longFlag in self.__parsedArgs else None
  68. if flag["ignoreDatabaseConfig"] == True:
  69. tmpValue = None
  70. if args[longFlag]:
  71. tmpValue = args[longFlag]
  72. if tmpValue == None:
  73. tmpValue = flag["type"](input("pass arguement %s: " % longFlag))
  74. return tmpValue
  75. def getDBContext(dbConfigPath):
  76. dbContext = {}
  77. dbContext["client"] = connect_to_instance_pool(dbConfigPath)
  78. dbContext["db"] = dbContext["client"]["experiments"]
  79. dbContext["instances"] = dbContext["db"]["instances"]
  80. dbContext["experimentScopes"] = dbContext["db"]["experiment_scopes"]
  81. return dbContext
  82. def connect_to_instance_pool(dbConfigPath = "database.config"):
  83. dbConf = readConfig(dbConfigPath)
  84. client = pymongo.MongoClient(
  85. "mongodb://%s:%s@%s:%s/%s"
  86. % ( dbConf["INSTANCE_POOL"]["user"],
  87. dbConf["INSTANCE_POOL"]["pw"],
  88. dbConf["INSTANCE_POOL"]["url"],
  89. dbConf["INSTANCE_POOL"]["port"],
  90. dbConf["INSTANCE_POOL"]["database"]),
  91. ssl=True,
  92. ssl_cert_reqs=ssl.CERT_NONE)
  93. return client[dbConf["INSTANCE_POOL"]["database"]]
  94. def connect_to_experimetns_db(dbConfigPath = "database.config"):
  95. dbConfig = readConfig(dbConfigPath)
  96. return mysql.connector.connect(
  97. host=dbConfig["EXPERIMENT_DB"]["url"],
  98. port=dbConfig["EXPERIMENT_DB"]["port"],
  99. user=dbConfig["EXPERIMENT_DB"]["user"],
  100. password=dbConfig["EXPERIMENT_DB"]["pw"],
  101. database=dbConfig["EXPERIMENT_DB"]["database"]
  102. )
  103. def frange(start, stop, steps):
  104. while start < stop:
  105. yield start
  106. start += steps
  107. def create_experiment_scope(db, description, name):
  108. experimentScope = {}
  109. experimentScope["instances"] = []
  110. experimentScope["description"] = description
  111. experimentScope["_id"] = name.strip()
  112. db["experiment_scopes"].insert_one(experimentScope)
  113. def write_instance_to_pool_db(db, instance):
  114. instance_document = instance.writeJSONLike()
  115. result = db["instances"].insert_one(instance_document)
  116. return result.inserted_id
  117. def add_instance_to_experiment_scope(db, scope_name, instance_id):
  118. db["experiment_scopes"].update_one(
  119. {"_id": scope_name},
  120. {"$push": {"instances": instance_id}}
  121. )
  122. def write_qubo_to_pool_db(collection, qubo, sat_instance_id):
  123. doc = {}
  124. doc["instance"] = sat_instance_id
  125. doc["description"] = {"<qubo>": "<entrys>",
  126. "<entrys>": "<entry><entrys> | <entry> | \"\"",
  127. "<entry>": "<coupler><energy>",
  128. "<energy>": "<real_number>",
  129. "<coupler>": "<node><node>",
  130. "<node>": "<clause><literal>",
  131. "<clause>": "<natural_number>",
  132. "<literal>": "<integer>"}
  133. doc["qubo"] = __qubo_to_JSON(qubo)
  134. collection.insert_one(doc)
  135. def create_wmis_qubos_for_scope(db, scope):
  136. instances = queries.Instance_scope_query(db)
  137. instances.query(scope)
  138. for instance, instance_id in instances:
  139. qubo = SAT2QUBO.WMISdictQUBO(instance)
  140. write_qubo_to_pool_db(db["wmis_qubos_2"], qubo, instance_id)
  141. def create_wmis_2_qubos_for_scope(db, scope):
  142. instances = queries.Instance_scope_query(db)
  143. instances.query(scope)
  144. for instance, instance_id in instances:
  145. qubo = SAT2QUBO.WMISdictQUBO_2(instance)
  146. write_qubo_to_pool_db(db["wmis_2_qubos"], qubo, instance_id)
  147. def create_primitive_isings_for_scope_2(db, scope):
  148. instances = queries.Instance_scope_query(db)
  149. instances.query(scope)
  150. for instance, instance_id in instances:
  151. ising = SAT2QUBO.primitiveQUBO_2(instance)
  152. write_qubo_to_pool_db(db["primitive_isings_2"], ising, instance_id)
  153. def create_primitive_qubo_for_scope_5(db, scope):
  154. instances = queries.Instance_scope_query(db)
  155. instances.query(scope)
  156. for instance, instance_id in tqdm(instances):
  157. ising = SAT2QUBO.primitiveQUBO_5(instance)
  158. write_qubo_to_pool_db(db["primitive_isings_5"], ising, instance_id)
  159. def create_primitive_qubo_for_scope_8(db, scope):
  160. instances = queries.Instance_scope_query(db)
  161. instances.query(scope)
  162. for instance, instance_id in tqdm(instances):
  163. ising = SAT2QUBO.primitiveQUBO_8(instance)
  164. write_qubo_to_pool_db(db["primitive_isings_8"], ising, instance_id)
  165. def __qubo_to_JSON(qubo):
  166. quboJSON = []
  167. for coupler, value in qubo.items():
  168. quboJSON.append([coupler, float(value)])
  169. return quboJSON
  170. def write_wmis_embedding_to_pool_db(collection, qubo_id, solver_graph_id, seed, embedding):
  171. if not __embedding_entry_exists(collection, qubo_id, solver_graph_id):
  172. __prepare_new_wmis_embedding_entry(collection, qubo_id, solver_graph_id)
  173. collection.update_one(
  174. {"qubo": qubo_id, "solver_graph": solver_graph_id},
  175. {
  176. "$push":
  177. {
  178. "embeddings":
  179. {
  180. "embedding": __embedding_to_array(embedding),
  181. "seed": seed
  182. }
  183. }
  184. }
  185. )
  186. def __embedding_entry_exists(collection, qubo_id, solver_graph_id):
  187. filter = {"qubo": qubo_id, "solver_graph": solver_graph_id}
  188. if collection.count_documents(filter) > 0:
  189. return True
  190. return False
  191. def __prepare_new_wmis_embedding_entry(collection, qubo_id, solver_graph_id):
  192. doc = {}
  193. doc["qubo"] = qubo_id
  194. doc["solver_graph"] = solver_graph_id
  195. doc["description"] = {"<embedding>": "<chains>",
  196. "<chains>": "<chain><chains> | \"\"",
  197. "<chain>" : "<original_node><chimera_nodes>",
  198. "<chimera_nodes>": "<chimera_node><chimera_nodes> | \"\""}
  199. doc["embeddings"] = []
  200. collection.insert_one(doc)
  201. def __embedding_to_array(embedding):
  202. emb_arr = []
  203. for node, chain in embedding.items():
  204. emb_arr.append([node, chain])
  205. return emb_arr
  206. def write_solver_graph_to_pool_db(collection, graph):
  207. data = nx.node_link_data(graph)
  208. id = queries.get_id_of_solver_graph(collection, data)
  209. if id != None:
  210. return id
  211. doc = {}
  212. doc["data"] = data
  213. return collection.insert_one(doc).inserted_id
  214. def find_wmis_embeddings_for_scope(db, scope, solver_graph):
  215. solver_graph_id = write_solver_graph_to_pool_db(db["solver_graphs"],
  216. solver_graph)
  217. qubos = queries.WMIS_scope_query(db)
  218. qubos.query(scope)
  219. new_embeddings_found = 0
  220. already_found = 0
  221. total_count = 0
  222. for qubo, qubo_id in tqdm(qubos):
  223. total_count += 1
  224. max_no_improvement = 10
  225. for i in range(5):
  226. if __embedding_entry_exists(db["embeddings"], qubo_id, solver_graph_id):
  227. if i == 0:
  228. already_found += 1
  229. break;
  230. else:
  231. nx_qubo = graph.qubo_to_nx_graph(qubo)
  232. seed = random.randint(0, sys.maxsize)
  233. emb = minorminer.find_embedding(nx_qubo.edges(),
  234. solver_graph.edges(),
  235. return_overlap=True,
  236. max_no_improvement=max_no_improvement,
  237. random_seed=seed)
  238. if emb[1] == 1:
  239. write_wmis_embedding_to_pool_db(db["embeddings"],
  240. qubo_id,
  241. solver_graph_id,
  242. seed,
  243. emb[0])
  244. new_embeddings_found += 1
  245. max_no_improvement *= 1.5
  246. percentage = 0
  247. if total_count > 0:
  248. percentage = round(((new_embeddings_found + already_found) / total_count) * 100)
  249. print("found {} of {} embeddigns ({}%)".format(new_embeddings_found + already_found,
  250. total_count,
  251. percentage))
  252. print("{} new embeddigns found".format(new_embeddings_found))
  253. def find_embeddings_for_scope(db, solver_graph, qubo_ising_query):
  254. solver_graph_id = write_solver_graph_to_pool_db(db["solver_graphs"],
  255. solver_graph)
  256. new_embeddings_found = 0
  257. already_found = 0
  258. total_count = 0
  259. for qubo, qubo_id in tqdm(qubo_ising_query):
  260. total_count += 1
  261. max_no_improvement = 10
  262. for i in range(5):
  263. if __embedding_entry_exists(db["embeddings"], qubo_id, solver_graph_id):
  264. if i == 0:
  265. already_found += 1
  266. break;
  267. else:
  268. nx_qubo = graph.qubo_to_nx_graph(qubo)
  269. seed = random.randint(0, sys.maxsize)
  270. emb = minorminer.find_embedding(nx_qubo.edges(),
  271. solver_graph.edges(),
  272. return_overlap=True,
  273. max_no_improvement=max_no_improvement,
  274. random_seed=seed)
  275. if emb[1] == 1:
  276. write_wmis_embedding_to_pool_db(db["embeddings"],
  277. qubo_id,
  278. solver_graph_id,
  279. seed,
  280. emb[0])
  281. new_embeddings_found += 1
  282. max_no_improvement *= 1.5
  283. percentage = 0
  284. if total_count > 0:
  285. percentage = round(((new_embeddings_found + already_found) / total_count) * 100)
  286. print("found {} of {} embeddigns ({}%)".format(new_embeddings_found + already_found,
  287. total_count,
  288. percentage))
  289. print("{} new embeddigns found".format(new_embeddings_found))
  290. def save_sample_set(collection, result, solver_input, emb_list_index, run):
  291. doc = {}
  292. doc["data"] = result.to_serializable()
  293. doc["instance"] = solver_input["instance_id"]
  294. doc["embedding"] = {
  295. "embedding_id": solver_input["embeddings_id"],
  296. "list_index": emb_list_index
  297. }
  298. doc["run"] = run
  299. collection.insert_one(doc)
  300. def save_qpu_result():
  301. doc = {}
  302. def analyze_wmis_sample(sample):
  303. data = {}
  304. data["number_of_assignments"] = np.count_nonzero(list(sample.sample.values()))
  305. data["chain_break_fraction"] = sample.chain_break_fraction
  306. data["num_occurrences"] = sample.num_occurrences
  307. data["energy"] = sample.energy
  308. return data
  309. def analyde_minisat_run(run_document):
  310. data = {}
  311. data["satisfiable"] = run_document["satisfiable"]
  312. return data
  313. def majority_vote_sample(sample):
  314. assignments = {}
  315. for coupler, energy in sample.items():
  316. var = abs(coupler[1])
  317. if var not in assignments:
  318. assignments[var] = {"all": []}
  319. if energy == 1:
  320. assignments[var]["all"].append(1 if coupler[1] > 0 else 0)
  321. for var, a in assignments.items():
  322. assignments[var]["majority"] = 1 if __true_percentage(a["all"]) >= 0.5 else 0
  323. assignment = [0 for i in range(len(assignments))]
  324. for var, a in assignments.items():
  325. assignment[var - 1] = a["majority"]
  326. return assignment
  327. def __true_percentage(a):
  328. if len(a) == 0:
  329. return 0
  330. return np.count_nonzero(a) / len(a)