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.

369 lines
11 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
  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"], qubo, instance_id)
  141. def __qubo_to_JSON(qubo):
  142. quboJSON = []
  143. for coupler, value in qubo.items():
  144. quboJSON.append([coupler, float(value)])
  145. return quboJSON
  146. def write_wmis_embedding_to_pool_db(collection, qubo_id, solver_graph_id, seed, embedding):
  147. if not __embedding_entry_exists(collection, qubo_id, solver_graph_id):
  148. __prepare_new_wmis_embedding_entry(collection, qubo_id, solver_graph_id)
  149. collection.update_one(
  150. {"qubo": qubo_id, "solver_graph": solver_graph_id},
  151. {
  152. "$push":
  153. {
  154. "embeddings":
  155. {
  156. "embedding": __embedding_to_array(embedding),
  157. "seed": seed
  158. }
  159. }
  160. }
  161. )
  162. def __embedding_entry_exists(collection, qubo_id, solver_graph_id):
  163. filter = {"qubo": qubo_id, "solver_graph": solver_graph_id}
  164. if collection.count_documents(filter) > 0:
  165. return True
  166. return False
  167. def __prepare_new_wmis_embedding_entry(collection, qubo_id, solver_graph_id):
  168. doc = {}
  169. doc["qubo"] = qubo_id
  170. doc["solver_graph"] = solver_graph_id
  171. doc["description"] = {"<embedding>": "<chains>",
  172. "<chains>": "<chain><chains> | \"\"",
  173. "<chain>" : "<original_node><chimera_nodes>",
  174. "<chimera_nodes>": "<chimera_node><chimera_nodes> | \"\""}
  175. doc["embeddings"] = []
  176. collection.insert_one(doc)
  177. def __embedding_to_array(embedding):
  178. emb_arr = []
  179. for node, chain in embedding.items():
  180. emb_arr.append([node, chain])
  181. return emb_arr
  182. def write_solver_graph_to_pool_db(collection, graph):
  183. data = nx.node_link_data(graph)
  184. id = queries.get_id_of_solver_graph(collection, data)
  185. if id != None:
  186. return id
  187. doc = {}
  188. doc["data"] = data
  189. return collection.insert_one(doc).inserted_id
  190. def find_wmis_embeddings_for_scope(db, scope, solver_graph):
  191. solver_graph_id = write_solver_graph_to_pool_db(db["solver_graphs"],
  192. solver_graph)
  193. qubos = queries.WMIS_scope_query(db)
  194. qubos.query(scope)
  195. new_embeddings_found = 0
  196. already_found = 0
  197. total_count = 0
  198. for qubo, qubo_id in tqdm(qubos):
  199. total_count += 1
  200. max_no_improvement = 10
  201. for i in range(5):
  202. if __embedding_entry_exists(db["embeddings"], qubo_id, solver_graph_id):
  203. if i == 0:
  204. already_found += 1
  205. break;
  206. else:
  207. nx_qubo = graph.qubo_to_nx_graph(qubo)
  208. seed = random.randint(0, sys.maxsize)
  209. emb = minorminer.find_embedding(nx_qubo.edges(),
  210. solver_graph.edges(),
  211. return_overlap=True,
  212. max_no_improvement=max_no_improvement,
  213. random_seed=seed)
  214. if emb[1] == 1:
  215. write_wmis_embedding_to_pool_db(db["embeddings"],
  216. qubo_id,
  217. solver_graph_id,
  218. seed,
  219. emb[0])
  220. new_embeddings_found += 1
  221. max_no_improvement *= 1.5
  222. percentage = 0
  223. if total_count > 0:
  224. percentage = round(((new_embeddings_found + already_found) / total_count) * 100)
  225. print("found {} of {} embeddigns ({}%)".format(new_embeddings_found + already_found,
  226. total_count,
  227. percentage))
  228. print("{} new embeddigns found".format(new_embeddings_found))
  229. def save_sample_set(collection, result, solver_input, emb_list_index, run):
  230. doc = {}
  231. doc["data"] = result.to_serializable()
  232. doc["instance"] = solver_input["instance_id"]
  233. doc["embedding"] = {
  234. "embedding_id": solver_input["embeddings_id"],
  235. "list_index": emb_list_index
  236. }
  237. doc["run"] = run
  238. collection.insert_one(doc)
  239. def save_qpu_result():
  240. doc = {}
  241. def analyze_wmis_sample(sample):
  242. data = {}
  243. data["number_of_assignments"] = np.count_nonzero(list(sample.sample.values()))
  244. data["chain_break_fraction"] = sample.chain_break_fraction
  245. data["num_occurrences"] = sample.num_occurrences
  246. data["energy"] = sample.energy
  247. return data
  248. def analyde_minisat_run(run_document):
  249. data = {}
  250. data["satisfiable"] = run_document["satisfiable"]
  251. return data
  252. def majority_vote_sample(sample):
  253. assignments = {}
  254. for coupler, energy in sample.items():
  255. var = abs(coupler[1])
  256. if var not in assignments:
  257. assignments[var] = {"all": []}
  258. if energy == 1:
  259. assignments[var]["all"].append(1 if coupler[1] > 0 else 0)
  260. for var, a in assignments.items():
  261. assignments[var]["majority"] = 1 if __true_percentage(a["all"]) >= 0.5 else 0
  262. assignment = [0 for i in range(len(assignments))]
  263. for var, a in assignments.items():
  264. assignment[var - 1] = a["majority"]
  265. return assignment
  266. def __true_percentage(a):
  267. if len(a) == 0:
  268. return 0
  269. return np.count_nonzero(a) / len(a)