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

median_preimage_generator_cml.py 46 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. Created on Tue Jun 16 16:04:46 2020
  5. @author: ljia
  6. """
  7. #!/usr/bin/env python3
  8. # -*- coding: utf-8 -*-
  9. """
  10. Created on Thu Mar 26 18:27:22 2020
  11. @author: ljia
  12. """
  13. import numpy as np
  14. import time
  15. import random
  16. import multiprocessing
  17. import networkx as nx
  18. import cvxpy as cp
  19. from gklearn.preimage import PreimageGenerator
  20. from gklearn.preimage.utils import compute_k_dis
  21. from gklearn.ged.util import compute_geds_cml, ged_options_to_string
  22. from gklearn.ged.env import GEDEnv
  23. from gklearn.ged.median import MedianGraphEstimator
  24. from gklearn.ged.median import constant_node_costs,mge_options_to_string
  25. from gklearn.utils import Timer
  26. from gklearn.utils.utils import get_graph_kernel_by_name
  27. class MedianPreimageGeneratorCML(PreimageGenerator):
  28. def __init__(self, dataset=None):
  29. PreimageGenerator.__init__(self, dataset=dataset)
  30. # arguments to set.
  31. self.__mge = None
  32. self.__ged_options = {}
  33. self.__mge_options = {}
  34. self.__fit_method = 'k-graphs'
  35. self.__init_ecc = None
  36. self.__parallel = True
  37. self.__n_jobs = multiprocessing.cpu_count()
  38. self.__ds_name = None
  39. self.__time_limit_in_sec = 0
  40. self.__max_itrs = 100
  41. self.__max_itrs_without_update = 3
  42. self.__epsilon_residual = 0.01
  43. self.__epsilon_ec = 0.1
  44. self.__allow_zeros = False
  45. self.__triangle_rule = True
  46. # values to compute.
  47. self.__runtime_optimize_ec = None
  48. self.__runtime_generate_preimage = None
  49. self.__runtime_total = None
  50. self.__set_median = None
  51. self.__gen_median = None
  52. self.__best_from_dataset = None
  53. self.__sod_set_median = None
  54. self.__sod_gen_median = None
  55. self.__k_dis_set_median = None
  56. self.__k_dis_gen_median = None
  57. self.__k_dis_dataset = None
  58. self.__itrs = 0
  59. self.__converged = False
  60. self.__num_updates_ecc = 0
  61. # values that can be set or to be computed.
  62. self.__edit_cost_constants = []
  63. self.__gram_matrix_unnorm = None
  64. self.__runtime_precompute_gm = None
  65. def set_options(self, **kwargs):
  66. self._kernel_options = kwargs.get('kernel_options', {})
  67. self._graph_kernel = kwargs.get('graph_kernel', None)
  68. self._verbose = kwargs.get('verbose', 2)
  69. self.__ged_options = kwargs.get('ged_options', {})
  70. self.__mge_options = kwargs.get('mge_options', {})
  71. self.__fit_method = kwargs.get('fit_method', 'k-graphs')
  72. self.__init_ecc = kwargs.get('init_ecc', None)
  73. self.__edit_cost_constants = kwargs.get('edit_cost_constants', [])
  74. self.__parallel = kwargs.get('parallel', True)
  75. self.__n_jobs = kwargs.get('n_jobs', multiprocessing.cpu_count())
  76. self.__ds_name = kwargs.get('ds_name', None)
  77. self.__time_limit_in_sec = kwargs.get('time_limit_in_sec', 0)
  78. self.__max_itrs = kwargs.get('max_itrs', 100)
  79. self.__max_itrs_without_update = kwargs.get('max_itrs_without_update', 3)
  80. self.__epsilon_residual = kwargs.get('epsilon_residual', 0.01)
  81. self.__epsilon_ec = kwargs.get('epsilon_ec', 0.1)
  82. self.__gram_matrix_unnorm = kwargs.get('gram_matrix_unnorm', None)
  83. self.__runtime_precompute_gm = kwargs.get('runtime_precompute_gm', None)
  84. self.__allow_zeros = kwargs.get('allow_zeros', False)
  85. self.__triangle_rule = kwargs.get('triangle_rule', True)
  86. def run(self):
  87. self._graph_kernel = get_graph_kernel_by_name(self._kernel_options['name'],
  88. node_labels=self._dataset.node_labels,
  89. edge_labels=self._dataset.edge_labels,
  90. node_attrs=self._dataset.node_attrs,
  91. edge_attrs=self._dataset.edge_attrs,
  92. ds_infos=self._dataset.get_dataset_infos(keys=['directed']),
  93. kernel_options=self._kernel_options)
  94. # record start time.
  95. start = time.time()
  96. # 1. precompute gram matrix.
  97. if self.__gram_matrix_unnorm is None:
  98. gram_matrix, run_time = self._graph_kernel.compute(self._dataset.graphs, **self._kernel_options)
  99. self.__gram_matrix_unnorm = self._graph_kernel.gram_matrix_unnorm
  100. end_precompute_gm = time.time()
  101. self.__runtime_precompute_gm = end_precompute_gm - start
  102. else:
  103. if self.__runtime_precompute_gm is None:
  104. raise Exception('Parameter "runtime_precompute_gm" must be given when using pre-computed Gram matrix.')
  105. self._graph_kernel.gram_matrix_unnorm = self.__gram_matrix_unnorm
  106. if self._kernel_options['normalize']:
  107. self._graph_kernel.gram_matrix = self._graph_kernel.normalize_gm(np.copy(self.__gram_matrix_unnorm))
  108. else:
  109. self._graph_kernel.gram_matrix = np.copy(self.__gram_matrix_unnorm)
  110. end_precompute_gm = time.time()
  111. start -= self.__runtime_precompute_gm
  112. if self.__fit_method != 'k-graphs' and self.__fit_method != 'whole-dataset':
  113. start = time.time()
  114. self.__runtime_precompute_gm = 0
  115. end_precompute_gm = start
  116. # 2. optimize edit cost constants.
  117. self.__optimize_edit_cost_vector()
  118. end_optimize_ec = time.time()
  119. self.__runtime_optimize_ec = end_optimize_ec - end_precompute_gm
  120. # 3. compute set median and gen median using optimized edit costs.
  121. if self._verbose >= 2:
  122. print('\nstart computing set median and gen median using optimized edit costs...\n')
  123. self.__gmg_bcu()
  124. end_generate_preimage = time.time()
  125. self.__runtime_generate_preimage = end_generate_preimage - end_optimize_ec
  126. self.__runtime_total = end_generate_preimage - start
  127. if self._verbose >= 2:
  128. print('medians computed.')
  129. print('SOD of the set median: ', self.__sod_set_median)
  130. print('SOD of the generalized median: ', self.__sod_gen_median)
  131. # 4. compute kernel distances to the true median.
  132. if self._verbose >= 2:
  133. print('\nstart computing distances to true median....\n')
  134. self.__compute_distances_to_true_median()
  135. # 5. print out results.
  136. if self._verbose:
  137. print()
  138. print('================================================================================')
  139. print('Finished generation of preimages.')
  140. print('--------------------------------------------------------------------------------')
  141. print('The optimized edit cost constants:', self.__edit_cost_constants)
  142. print('SOD of the set median:', self.__sod_set_median)
  143. print('SOD of the generalized median:', self.__sod_gen_median)
  144. print('Distance in kernel space for set median:', self.__k_dis_set_median)
  145. print('Distance in kernel space for generalized median:', self.__k_dis_gen_median)
  146. print('Minimum distance in kernel space for each graph in median set:', self.__k_dis_dataset)
  147. print('Time to pre-compute Gram matrix:', self.__runtime_precompute_gm)
  148. print('Time to optimize edit costs:', self.__runtime_optimize_ec)
  149. print('Time to generate pre-images:', self.__runtime_generate_preimage)
  150. print('Total time:', self.__runtime_total)
  151. print('Total number of iterations for optimizing:', self.__itrs)
  152. print('Total number of updating edit costs:', self.__num_updates_ecc)
  153. print('Is optimization of edit costs converged:', self.__converged)
  154. print('================================================================================')
  155. print()
  156. def get_results(self):
  157. results = {}
  158. results['edit_cost_constants'] = self.__edit_cost_constants
  159. results['runtime_precompute_gm'] = self.__runtime_precompute_gm
  160. results['runtime_optimize_ec'] = self.__runtime_optimize_ec
  161. results['runtime_generate_preimage'] = self.__runtime_generate_preimage
  162. results['runtime_total'] = self.__runtime_total
  163. results['sod_set_median'] = self.__sod_set_median
  164. results['sod_gen_median'] = self.__sod_gen_median
  165. results['k_dis_set_median'] = self.__k_dis_set_median
  166. results['k_dis_gen_median'] = self.__k_dis_gen_median
  167. results['k_dis_dataset'] = self.__k_dis_dataset
  168. results['itrs'] = self.__itrs
  169. results['converged'] = self.__converged
  170. results['num_updates_ecc'] = self.__num_updates_ecc
  171. results['mge'] = {}
  172. results['mge']['num_decrease_order'] = self.__mge.get_num_times_order_decreased()
  173. results['mge']['num_increase_order'] = self.__mge.get_num_times_order_increased()
  174. results['mge']['num_converged_descents'] = self.__mge.get_num_converged_descents()
  175. return results
  176. def __optimize_edit_cost_vector(self):
  177. """Learn edit cost vector.
  178. """
  179. if self.__fit_method == 'random': # random
  180. if self.__ged_options['edit_cost'] == 'LETTER':
  181. self.__edit_cost_constants = random.sample(range(1, 1000), 3)
  182. self.__edit_cost_constants = [item * 0.001 for item in self.__edit_cost_constants]
  183. elif self.__ged_options['edit_cost'] == 'LETTER2':
  184. random.seed(time.time())
  185. self.__edit_cost_constants = random.sample(range(1, 1000), 5)
  186. self.__edit_cost_constants = [item * 0.01 for item in self.__edit_cost_constants]
  187. elif self.__ged_options['edit_cost'] == 'NON_SYMBOLIC':
  188. self.__edit_cost_constants = random.sample(range(1, 1000), 6)
  189. self.__edit_cost_constants = [item * 0.01 for item in self.__edit_cost_constants]
  190. if self._dataset.node_attrs == []:
  191. self.__edit_cost_constants[2] = 0
  192. if self._dataset.edge_attrs == []:
  193. self.__edit_cost_constants[5] = 0
  194. else:
  195. self.__edit_cost_constants = random.sample(range(1, 1000), 6)
  196. self.__edit_cost_constants = [item * 0.01 for item in self.__edit_cost_constants]
  197. if self._verbose >= 2:
  198. print('edit cost constants used:', self.__edit_cost_constants)
  199. elif self.__fit_method == 'expert': # expert
  200. if self.__init_ecc is None:
  201. if self.__ged_options['edit_cost'] == 'LETTER':
  202. self.__edit_cost_constants = [0.9, 1.7, 0.75]
  203. elif self.__ged_options['edit_cost'] == 'LETTER2':
  204. self.__edit_cost_constants = [0.675, 0.675, 0.75, 0.425, 0.425]
  205. else:
  206. self.__edit_cost_constants = [3, 3, 1, 3, 3, 1]
  207. else:
  208. self.__edit_cost_constants = self.__init_ecc
  209. elif self.__fit_method == 'k-graphs':
  210. if self.__init_ecc is None:
  211. if self.__ged_options['edit_cost'] == 'LETTER':
  212. self.__init_ecc = [0.9, 1.7, 0.75]
  213. elif self.__ged_options['edit_cost'] == 'LETTER2':
  214. self.__init_ecc = [0.675, 0.675, 0.75, 0.425, 0.425]
  215. elif self.__ged_options['edit_cost'] == 'NON_SYMBOLIC':
  216. self.__init_ecc = [0, 0, 1, 1, 1, 0]
  217. if self._dataset.node_attrs == []:
  218. self.__init_ecc[2] = 0
  219. if self._dataset.edge_attrs == []:
  220. self.__init_ecc[5] = 0
  221. else:
  222. self.__init_ecc = [3, 3, 1, 3, 3, 1]
  223. # optimize on the k-graph subset.
  224. self.__optimize_ecm_by_kernel_distances()
  225. elif self.__fit_method == 'whole-dataset':
  226. if self.__init_ecc is None:
  227. if self.__ged_options['edit_cost'] == 'LETTER':
  228. self.__init_ecc = [0.9, 1.7, 0.75]
  229. elif self.__ged_options['edit_cost'] == 'LETTER2':
  230. self.__init_ecc = [0.675, 0.675, 0.75, 0.425, 0.425]
  231. else:
  232. self.__init_ecc = [3, 3, 1, 3, 3, 1]
  233. # optimizeon the whole set.
  234. self.__optimize_ecc_by_kernel_distances()
  235. elif self.__fit_method == 'precomputed':
  236. pass
  237. def __optimize_ecm_by_kernel_distances(self):
  238. # compute distances in feature space.
  239. dis_k_mat, _, _, _ = self._graph_kernel.compute_distance_matrix()
  240. dis_k_vec = []
  241. for i in range(len(dis_k_mat)):
  242. # for j in range(i, len(dis_k_mat)):
  243. for j in range(i + 1, len(dis_k_mat)):
  244. dis_k_vec.append(dis_k_mat[i, j])
  245. dis_k_vec = np.array(dis_k_vec)
  246. # init ged.
  247. if self._verbose >= 2:
  248. print('\ninitial:')
  249. time0 = time.time()
  250. graphs = [self.__clean_graph(g) for g in self._dataset.graphs]
  251. self.__edit_cost_constants = self.__init_ecc
  252. options = self.__ged_options.copy()
  253. options['edit_cost_constants'] = self.__edit_cost_constants # @todo
  254. options['node_labels'] = self._dataset.node_labels
  255. options['edge_labels'] = self._dataset.edge_labels
  256. options['node_attrs'] = self._dataset.node_attrs
  257. options['edge_attrs'] = self._dataset.edge_attrs
  258. ged_vec_init, ged_mat, n_edit_operations = compute_geds_cml(graphs, options=options, parallel=self.__parallel, verbose=(self._verbose > 1))
  259. residual_list = [np.sqrt(np.sum(np.square(np.array(ged_vec_init) - dis_k_vec)))]
  260. time_list = [time.time() - time0]
  261. edit_cost_list = [self.__init_ecc]
  262. nb_cost_mat = np.array(n_edit_operations)
  263. nb_cost_mat_list = [nb_cost_mat]
  264. if self._verbose >= 2:
  265. print('Current edit cost constants:', self.__edit_cost_constants)
  266. print('Residual list:', residual_list)
  267. # run iteration from initial edit costs.
  268. self.__converged = False
  269. itrs_without_update = 0
  270. self.__itrs = 0
  271. self.__num_updates_ecc = 0
  272. timer = Timer(self.__time_limit_in_sec)
  273. while not self.__termination_criterion_met(self.__converged, timer, self.__itrs, itrs_without_update):
  274. if self._verbose >= 2:
  275. print('\niteration', self.__itrs + 1)
  276. time0 = time.time()
  277. # "fit" geds to distances in feature space by tuning edit costs using theLeast Squares Method.
  278. # np.savez('results/xp_fit_method/fit_data_debug' + str(self.__itrs) + '.gm',
  279. # nb_cost_mat=nb_cost_mat, dis_k_vec=dis_k_vec,
  280. # n_edit_operations=n_edit_operations, ged_vec_init=ged_vec_init,
  281. # ged_mat=ged_mat)
  282. self.__edit_cost_constants, _ = self.__update_ecc(nb_cost_mat, dis_k_vec)
  283. for i in range(len(self.__edit_cost_constants)):
  284. if -1e-9 <= self.__edit_cost_constants[i] <= 1e-9:
  285. self.__edit_cost_constants[i] = 0
  286. if self.__edit_cost_constants[i] < 0:
  287. raise ValueError('The edit cost is negative.')
  288. # for i in range(len(self.__edit_cost_constants)):
  289. # if self.__edit_cost_constants[i] < 0:
  290. # self.__edit_cost_constants[i] = 0
  291. # compute new GEDs and numbers of edit operations.
  292. options = self.__ged_options.copy() # np.array([self.__edit_cost_constants[0], self.__edit_cost_constants[1], 0.75])
  293. options['edit_cost_constants'] = self.__edit_cost_constants # @todo
  294. options['node_labels'] = self._dataset.node_labels
  295. options['edge_labels'] = self._dataset.edge_labels
  296. options['node_attrs'] = self._dataset.node_attrs
  297. options['edge_attrs'] = self._dataset.edge_attrs
  298. ged_vec, ged_mat, n_edit_operations = compute_geds_cml(graphs, options=options, parallel=self.__parallel, verbose=(self._verbose > 1))
  299. residual_list.append(np.sqrt(np.sum(np.square(np.array(ged_vec) - dis_k_vec))))
  300. time_list.append(time.time() - time0)
  301. edit_cost_list.append(self.__edit_cost_constants)
  302. nb_cost_mat = np.array(n_edit_operations)
  303. nb_cost_mat_list.append(nb_cost_mat)
  304. # check convergency.
  305. ec_changed = False
  306. for i, cost in enumerate(self.__edit_cost_constants):
  307. if cost == 0:
  308. if edit_cost_list[-2][i] > self.__epsilon_ec:
  309. ec_changed = True
  310. break
  311. elif abs(cost - edit_cost_list[-2][i]) / cost > self.__epsilon_ec:
  312. ec_changed = True
  313. break
  314. # if abs(cost - edit_cost_list[-2][i]) > self.__epsilon_ec:
  315. # ec_changed = True
  316. # break
  317. residual_changed = False
  318. if residual_list[-1] == 0:
  319. if residual_list[-2] > self.__epsilon_residual:
  320. residual_changed = True
  321. elif abs(residual_list[-1] - residual_list[-2]) / residual_list[-1] > self.__epsilon_residual:
  322. residual_changed = True
  323. self.__converged = not (ec_changed or residual_changed)
  324. if self.__converged:
  325. itrs_without_update += 1
  326. else:
  327. itrs_without_update = 0
  328. self.__num_updates_ecc += 1
  329. # print current states.
  330. if self._verbose >= 2:
  331. print()
  332. print('-------------------------------------------------------------------------')
  333. print('States of iteration', self.__itrs + 1)
  334. print('-------------------------------------------------------------------------')
  335. # print('Time spend:', self.__runtime_optimize_ec)
  336. print('Total number of iterations for optimizing:', self.__itrs + 1)
  337. print('Total number of updating edit costs:', self.__num_updates_ecc)
  338. print('Was optimization of edit costs converged:', self.__converged)
  339. print('Did edit costs change:', ec_changed)
  340. print('Did residual change:', residual_changed)
  341. print('Iterations without update:', itrs_without_update)
  342. print('Current edit cost constants:', self.__edit_cost_constants)
  343. print('Residual list:', residual_list)
  344. print('-------------------------------------------------------------------------')
  345. self.__itrs += 1
  346. def __termination_criterion_met(self, converged, timer, itr, itrs_without_update):
  347. if timer.expired() or (itr >= self.__max_itrs if self.__max_itrs >= 0 else False):
  348. # if self.__state == AlgorithmState.TERMINATED:
  349. # self.__state = AlgorithmState.INITIALIZED
  350. return True
  351. return converged or (itrs_without_update > self.__max_itrs_without_update if self.__max_itrs_without_update >= 0 else False)
  352. def __update_ecc(self, nb_cost_mat, dis_k_vec, rw_constraints='inequality'):
  353. # if self.__ds_name == 'Letter-high':
  354. if self.__ged_options['edit_cost'] == 'LETTER':
  355. raise Exception('Cannot compute for cost "LETTER".')
  356. pass
  357. # # method 1: set alpha automatically, just tune c_vir and c_eir by
  358. # # LMS using cvxpy.
  359. # alpha = 0.5
  360. # coeff = 100 # np.max(alpha * nb_cost_mat[:,4] / dis_k_vec)
  361. ## if np.count_nonzero(nb_cost_mat[:,4]) == 0:
  362. ## alpha = 0.75
  363. ## else:
  364. ## alpha = np.min([dis_k_vec / c_vs for c_vs in nb_cost_mat[:,4] if c_vs != 0])
  365. ## alpha = alpha * 0.99
  366. # param_vir = alpha * (nb_cost_mat[:,0] + nb_cost_mat[:,1])
  367. # param_eir = (1 - alpha) * (nb_cost_mat[:,4] + nb_cost_mat[:,5])
  368. # nb_cost_mat_new = np.column_stack((param_vir, param_eir))
  369. # dis_new = coeff * dis_k_vec - alpha * nb_cost_mat[:,3]
  370. #
  371. # x = cp.Variable(nb_cost_mat_new.shape[1])
  372. # cost = cp.sum_squares(nb_cost_mat_new * x - dis_new)
  373. # constraints = [x >= [0.0 for i in range(nb_cost_mat_new.shape[1])]]
  374. # prob = cp.Problem(cp.Minimize(cost), constraints)
  375. # prob.solve()
  376. # edit_costs_new = x.value
  377. # edit_costs_new = np.array([edit_costs_new[0], edit_costs_new[1], alpha])
  378. # residual = np.sqrt(prob.value)
  379. # # method 2: tune c_vir, c_eir and alpha by nonlinear programming by
  380. # # scipy.optimize.minimize.
  381. # w0 = nb_cost_mat[:,0] + nb_cost_mat[:,1]
  382. # w1 = nb_cost_mat[:,4] + nb_cost_mat[:,5]
  383. # w2 = nb_cost_mat[:,3]
  384. # w3 = dis_k_vec
  385. # func_min = lambda x: np.sum((w0 * x[0] * x[3] + w1 * x[1] * (1 - x[2]) \
  386. # + w2 * x[2] - w3 * x[3]) ** 2)
  387. # bounds = ((0, None), (0., None), (0.5, 0.5), (0, None))
  388. # res = minimize(func_min, [0.9, 1.7, 0.75, 10], bounds=bounds)
  389. # edit_costs_new = res.x[0:3]
  390. # residual = res.fun
  391. # method 3: tune c_vir, c_eir and alpha by nonlinear programming using cvxpy.
  392. # # method 4: tune c_vir, c_eir and alpha by QP function
  393. # # scipy.optimize.least_squares. An initial guess is required.
  394. # w0 = nb_cost_mat[:,0] + nb_cost_mat[:,1]
  395. # w1 = nb_cost_mat[:,4] + nb_cost_mat[:,5]
  396. # w2 = nb_cost_mat[:,3]
  397. # w3 = dis_k_vec
  398. # func = lambda x: (w0 * x[0] * x[3] + w1 * x[1] * (1 - x[2]) \
  399. # + w2 * x[2] - w3 * x[3]) ** 2
  400. # res = optimize.root(func, [0.9, 1.7, 0.75, 100])
  401. # edit_costs_new = res.x
  402. # residual = None
  403. elif self.__ged_options['edit_cost'] == 'LETTER2':
  404. # # 1. if c_vi != c_vr, c_ei != c_er.
  405. # nb_cost_mat_new = nb_cost_mat[:,[0,1,3,4,5]]
  406. # x = cp.Variable(nb_cost_mat_new.shape[1])
  407. # cost_fun = cp.sum_squares(nb_cost_mat_new @ x - dis_k_vec)
  408. ## # 1.1 no constraints.
  409. ## constraints = [x >= [0.0 for i in range(nb_cost_mat_new.shape[1])]]
  410. # # 1.2 c_vs <= c_vi + c_vr.
  411. # constraints = [x >= [0.0 for i in range(nb_cost_mat_new.shape[1])],
  412. # np.array([1.0, 1.0, -1.0, 0.0, 0.0]).T@x >= 0.0]
  413. ## # 2. if c_vi == c_vr, c_ei == c_er.
  414. ## nb_cost_mat_new = nb_cost_mat[:,[0,3,4]]
  415. ## nb_cost_mat_new[:,0] += nb_cost_mat[:,1]
  416. ## nb_cost_mat_new[:,2] += nb_cost_mat[:,5]
  417. ## x = cp.Variable(nb_cost_mat_new.shape[1])
  418. ## cost_fun = cp.sum_squares(nb_cost_mat_new @ x - dis_k_vec)
  419. ## # 2.1 no constraints.
  420. ## constraints = [x >= [0.0 for i in range(nb_cost_mat_new.shape[1])]]
  421. ### # 2.2 c_vs <= c_vi + c_vr.
  422. ### constraints = [x >= [0.0 for i in range(nb_cost_mat_new.shape[1])],
  423. ### np.array([2.0, -1.0, 0.0]).T@x >= 0.0]
  424. #
  425. # prob = cp.Problem(cp.Minimize(cost_fun), constraints)
  426. # prob.solve()
  427. # edit_costs_new = [x.value[0], x.value[0], x.value[1], x.value[2], x.value[2]]
  428. # edit_costs_new = np.array(edit_costs_new)
  429. # residual = np.sqrt(prob.value)
  430. if not self.__triangle_rule and self.__allow_zeros:
  431. nb_cost_mat_new = nb_cost_mat[:,[0,1,3,4,5]]
  432. x = cp.Variable(nb_cost_mat_new.shape[1])
  433. cost_fun = cp.sum_squares(nb_cost_mat_new @ x - dis_k_vec)
  434. constraints = [x >= [0.0 for i in range(nb_cost_mat_new.shape[1])],
  435. np.array([1.0, 0.0, 0.0, 0.0, 0.0]).T@x >= 0.01,
  436. np.array([0.0, 1.0, 0.0, 0.0, 0.0]).T@x >= 0.01,
  437. np.array([0.0, 0.0, 0.0, 1.0, 0.0]).T@x >= 0.01,
  438. np.array([0.0, 0.0, 0.0, 0.0, 1.0]).T@x >= 0.01]
  439. prob = cp.Problem(cp.Minimize(cost_fun), constraints)
  440. self.__execute_cvx(prob)
  441. edit_costs_new = x.value
  442. residual = np.sqrt(prob.value)
  443. elif self.__triangle_rule and self.__allow_zeros:
  444. nb_cost_mat_new = nb_cost_mat[:,[0,1,3,4,5]]
  445. x = cp.Variable(nb_cost_mat_new.shape[1])
  446. cost_fun = cp.sum_squares(nb_cost_mat_new @ x - dis_k_vec)
  447. constraints = [x >= [0.0 for i in range(nb_cost_mat_new.shape[1])],
  448. np.array([1.0, 0.0, 0.0, 0.0, 0.0]).T@x >= 0.01,
  449. np.array([0.0, 1.0, 0.0, 0.0, 0.0]).T@x >= 0.01,
  450. np.array([0.0, 0.0, 0.0, 1.0, 0.0]).T@x >= 0.01,
  451. np.array([0.0, 0.0, 0.0, 0.0, 1.0]).T@x >= 0.01,
  452. np.array([1.0, 1.0, -1.0, 0.0, 0.0]).T@x >= 0.0]
  453. prob = cp.Problem(cp.Minimize(cost_fun), constraints)
  454. self.__execute_cvx(prob)
  455. edit_costs_new = x.value
  456. residual = np.sqrt(prob.value)
  457. elif not self.__triangle_rule and not self.__allow_zeros:
  458. nb_cost_mat_new = nb_cost_mat[:,[0,1,3,4,5]]
  459. x = cp.Variable(nb_cost_mat_new.shape[1])
  460. cost_fun = cp.sum_squares(nb_cost_mat_new @ x - dis_k_vec)
  461. constraints = [x >= [0.01 for i in range(nb_cost_mat_new.shape[1])]]
  462. prob = cp.Problem(cp.Minimize(cost_fun), constraints)
  463. prob.solve()
  464. edit_costs_new = x.value
  465. residual = np.sqrt(prob.value)
  466. # elif method == 'inequality_modified':
  467. # # c_vs <= c_vi + c_vr.
  468. # nb_cost_mat_new = nb_cost_mat[:,[0,1,3,4,5]]
  469. # x = cp.Variable(nb_cost_mat_new.shape[1])
  470. # cost_fun = cp.sum_squares(nb_cost_mat_new @ x - dis_k_vec)
  471. # constraints = [x >= [0.0 for i in range(nb_cost_mat_new.shape[1])],
  472. # np.array([1.0, 1.0, -1.0, 0.0, 0.0]).T@x >= 0.0]
  473. # prob = cp.Problem(cp.Minimize(cost_fun), constraints)
  474. # prob.solve()
  475. # # use same costs for insertion and removal rather than the fitted costs.
  476. # edit_costs_new = [x.value[0], x.value[0], x.value[1], x.value[2], x.value[2]]
  477. # edit_costs_new = np.array(edit_costs_new)
  478. # residual = np.sqrt(prob.value)
  479. elif self.__triangle_rule and not self.__allow_zeros:
  480. # c_vs <= c_vi + c_vr.
  481. nb_cost_mat_new = nb_cost_mat[:,[0,1,3,4,5]]
  482. x = cp.Variable(nb_cost_mat_new.shape[1])
  483. cost_fun = cp.sum_squares(nb_cost_mat_new @ x - dis_k_vec)
  484. constraints = [x >= [0.01 for i in range(nb_cost_mat_new.shape[1])],
  485. np.array([1.0, 1.0, -1.0, 0.0, 0.0]).T@x >= 0.0]
  486. prob = cp.Problem(cp.Minimize(cost_fun), constraints)
  487. self.__execute_cvx(prob)
  488. edit_costs_new = x.value
  489. residual = np.sqrt(prob.value)
  490. elif rw_constraints == '2constraints': # @todo: rearrange it later.
  491. # c_vs <= c_vi + c_vr and c_vi == c_vr, c_ei == c_er.
  492. nb_cost_mat_new = nb_cost_mat[:,[0,1,3,4,5]]
  493. x = cp.Variable(nb_cost_mat_new.shape[1])
  494. cost_fun = cp.sum_squares(nb_cost_mat_new @ x - dis_k_vec)
  495. constraints = [x >= [0.01 for i in range(nb_cost_mat_new.shape[1])],
  496. np.array([1.0, 1.0, -1.0, 0.0, 0.0]).T@x >= 0.0,
  497. np.array([1.0, -1.0, 0.0, 0.0, 0.0]).T@x == 0.0,
  498. np.array([0.0, 0.0, 0.0, 1.0, -1.0]).T@x == 0.0]
  499. prob = cp.Problem(cp.Minimize(cost_fun), constraints)
  500. prob.solve()
  501. edit_costs_new = x.value
  502. residual = np.sqrt(prob.value)
  503. elif self.__ged_options['edit_cost'] == 'NON_SYMBOLIC':
  504. is_n_attr = np.count_nonzero(nb_cost_mat[:,2])
  505. is_e_attr = np.count_nonzero(nb_cost_mat[:,5])
  506. if self.__ds_name == 'SYNTHETICnew': # @todo: rearrenge this later.
  507. # nb_cost_mat_new = nb_cost_mat[:,[0,1,2,3,4]]
  508. nb_cost_mat_new = nb_cost_mat[:,[2,3,4]]
  509. x = cp.Variable(nb_cost_mat_new.shape[1])
  510. cost_fun = cp.sum_squares(nb_cost_mat_new @ x - dis_k_vec)
  511. # constraints = [x >= [0.0 for i in range(nb_cost_mat_new.shape[1])],
  512. # np.array([0.0, 0.0, 0.0, 1.0, -1.0]).T@x == 0.0]
  513. # constraints = [x >= [0.0001 for i in range(nb_cost_mat_new.shape[1])]]
  514. constraints = [x >= [0.0001 for i in range(nb_cost_mat_new.shape[1])],
  515. np.array([0.0, 1.0, -1.0]).T@x == 0.0]
  516. prob = cp.Problem(cp.Minimize(cost_fun), constraints)
  517. prob.solve()
  518. # print(x.value)
  519. edit_costs_new = np.concatenate((np.array([0.0, 0.0]), x.value,
  520. np.array([0.0])))
  521. residual = np.sqrt(prob.value)
  522. elif not self.__triangle_rule and self.__allow_zeros:
  523. if is_n_attr and is_e_attr:
  524. nb_cost_mat_new = nb_cost_mat[:,[0,1,2,3,4,5]]
  525. x = cp.Variable(nb_cost_mat_new.shape[1])
  526. cost_fun = cp.sum_squares(nb_cost_mat_new @ x - dis_k_vec)
  527. constraints = [x >= [0.0 for i in range(nb_cost_mat_new.shape[1])],
  528. np.array([1.0, 0.0, 0.0, 0.0, 0.0, 0.0]).T@x >= 0.01,
  529. np.array([0.0, 1.0, 0.0, 0.0, 0.0, 0.0]).T@x >= 0.01,
  530. np.array([0.0, 0.0, 0.0, 1.0, 0.0, 0.0]).T@x >= 0.01,
  531. np.array([0.0, 0.0, 0.0, 0.0, 1.0, 0.0]).T@x >= 0.01]
  532. prob = cp.Problem(cp.Minimize(cost_fun), constraints)
  533. self.__execute_cvx(prob)
  534. edit_costs_new = x.value
  535. residual = np.sqrt(prob.value)
  536. elif is_n_attr and not is_e_attr:
  537. nb_cost_mat_new = nb_cost_mat[:,[0,1,2,3,4]]
  538. x = cp.Variable(nb_cost_mat_new.shape[1])
  539. cost_fun = cp.sum_squares(nb_cost_mat_new @ x - dis_k_vec)
  540. constraints = [x >= [0.0 for i in range(nb_cost_mat_new.shape[1])],
  541. np.array([1.0, 0.0, 0.0, 0.0, 0.0]).T@x >= 0.01,
  542. np.array([0.0, 1.0, 0.0, 0.0, 0.0]).T@x >= 0.01,
  543. np.array([0.0, 0.0, 0.0, 1.0, 0.0]).T@x >= 0.01,
  544. np.array([0.0, 0.0, 0.0, 0.0, 1.0]).T@x >= 0.01]
  545. prob = cp.Problem(cp.Minimize(cost_fun), constraints)
  546. self.__execute_cvx(prob)
  547. edit_costs_new = np.concatenate((x.value, np.array([0.0])))
  548. residual = np.sqrt(prob.value)
  549. elif not is_n_attr and is_e_attr:
  550. nb_cost_mat_new = nb_cost_mat[:,[0,1,3,4,5]]
  551. x = cp.Variable(nb_cost_mat_new.shape[1])
  552. cost_fun = cp.sum_squares(nb_cost_mat_new @ x - dis_k_vec)
  553. constraints = [x >= [0.0 for i in range(nb_cost_mat_new.shape[1])],
  554. np.array([1.0, 0.0, 0.0, 0.0, 0.0]).T@x >= 0.01,
  555. np.array([0.0, 1.0, 0.0, 0.0, 0.0]).T@x >= 0.01,
  556. np.array([0.0, 0.0, 1.0, 0.0, 0.0]).T@x >= 0.01,
  557. np.array([0.0, 0.0, 0.0, 1.0, 0.0]).T@x >= 0.01]
  558. prob = cp.Problem(cp.Minimize(cost_fun), constraints)
  559. self.__execute_cvx(prob)
  560. edit_costs_new = np.concatenate((x.value[0:2], np.array([0.0]), x.value[2:]))
  561. residual = np.sqrt(prob.value)
  562. else:
  563. nb_cost_mat_new = nb_cost_mat[:,[0,1,3,4]]
  564. x = cp.Variable(nb_cost_mat_new.shape[1])
  565. cost_fun = cp.sum_squares(nb_cost_mat_new @ x - dis_k_vec)
  566. constraints = [x >= [0.01 for i in range(nb_cost_mat_new.shape[1])]]
  567. prob = cp.Problem(cp.Minimize(cost_fun), constraints)
  568. self.__execute_cvx(prob)
  569. edit_costs_new = np.concatenate((x.value[0:2], np.array([0.0]),
  570. x.value[2:], np.array([0.0])))
  571. residual = np.sqrt(prob.value)
  572. elif self.__triangle_rule and self.__allow_zeros:
  573. if is_n_attr and is_e_attr:
  574. nb_cost_mat_new = nb_cost_mat[:,[0,1,2,3,4,5]]
  575. x = cp.Variable(nb_cost_mat_new.shape[1])
  576. cost_fun = cp.sum_squares(nb_cost_mat_new @ x - dis_k_vec)
  577. constraints = [x >= [0.0 for i in range(nb_cost_mat_new.shape[1])],
  578. np.array([1.0, 0.0, 0.0, 0.0, 0.0, 0.0]).T@x >= 0.01,
  579. np.array([0.0, 1.0, 0.0, 0.0, 0.0, 0.0]).T@x >= 0.01,
  580. np.array([0.0, 0.0, 0.0, 1.0, 0.0, 0.0]).T@x >= 0.01,
  581. np.array([0.0, 0.0, 0.0, 0.0, 1.0, 0.0]).T@x >= 0.01,
  582. np.array([1.0, 1.0, -1.0, 0.0, 0.0, 0.0]).T@x >= 0.0,
  583. np.array([0.0, 0.0, 0.0, 1.0, 1.0, -1.0]).T@x >= 0.0]
  584. prob = cp.Problem(cp.Minimize(cost_fun), constraints)
  585. self.__execute_cvx(prob)
  586. edit_costs_new = x.value
  587. residual = np.sqrt(prob.value)
  588. elif is_n_attr and not is_e_attr:
  589. nb_cost_mat_new = nb_cost_mat[:,[0,1,2,3,4]]
  590. x = cp.Variable(nb_cost_mat_new.shape[1])
  591. cost_fun = cp.sum_squares(nb_cost_mat_new @ x - dis_k_vec)
  592. constraints = [x >= [0.0 for i in range(nb_cost_mat_new.shape[1])],
  593. np.array([1.0, 0.0, 0.0, 0.0, 0.0]).T@x >= 0.01,
  594. np.array([0.0, 1.0, 0.0, 0.0, 0.0]).T@x >= 0.01,
  595. np.array([0.0, 0.0, 0.0, 1.0, 0.0]).T@x >= 0.01,
  596. np.array([0.0, 0.0, 0.0, 0.0, 1.0]).T@x >= 0.01,
  597. np.array([1.0, 1.0, -1.0, 0.0, 0.0]).T@x >= 0.0]
  598. prob = cp.Problem(cp.Minimize(cost_fun), constraints)
  599. self.__execute_cvx(prob)
  600. edit_costs_new = np.concatenate((x.value, np.array([0.0])))
  601. residual = np.sqrt(prob.value)
  602. elif not is_n_attr and is_e_attr:
  603. nb_cost_mat_new = nb_cost_mat[:,[0,1,3,4,5]]
  604. x = cp.Variable(nb_cost_mat_new.shape[1])
  605. cost_fun = cp.sum_squares(nb_cost_mat_new @ x - dis_k_vec)
  606. constraints = [x >= [0.0 for i in range(nb_cost_mat_new.shape[1])],
  607. np.array([1.0, 0.0, 0.0, 0.0, 0.0]).T@x >= 0.01,
  608. np.array([0.0, 1.0, 0.0, 0.0, 0.0]).T@x >= 0.01,
  609. np.array([0.0, 0.0, 1.0, 0.0, 0.0]).T@x >= 0.01,
  610. np.array([0.0, 0.0, 0.0, 1.0, 0.0]).T@x >= 0.01,
  611. np.array([0.0, 0.0, 1.0, 1.0, -1.0]).T@x >= 0.0]
  612. prob = cp.Problem(cp.Minimize(cost_fun), constraints)
  613. self.__execute_cvx(prob)
  614. edit_costs_new = np.concatenate((x.value[0:2], np.array([0.0]), x.value[2:]))
  615. residual = np.sqrt(prob.value)
  616. else:
  617. nb_cost_mat_new = nb_cost_mat[:,[0,1,3,4]]
  618. x = cp.Variable(nb_cost_mat_new.shape[1])
  619. cost_fun = cp.sum_squares(nb_cost_mat_new @ x - dis_k_vec)
  620. constraints = [x >= [0.01 for i in range(nb_cost_mat_new.shape[1])]]
  621. prob = cp.Problem(cp.Minimize(cost_fun), constraints)
  622. self.__execute_cvx(prob)
  623. edit_costs_new = np.concatenate((x.value[0:2], np.array([0.0]),
  624. x.value[2:], np.array([0.0])))
  625. residual = np.sqrt(prob.value)
  626. elif not self.__triangle_rule and not self.__allow_zeros:
  627. if is_n_attr and is_e_attr:
  628. nb_cost_mat_new = nb_cost_mat[:,[0,1,2,3,4,5]]
  629. x = cp.Variable(nb_cost_mat_new.shape[1])
  630. cost_fun = cp.sum_squares(nb_cost_mat_new @ x - dis_k_vec)
  631. constraints = [x >= [0.01 for i in range(nb_cost_mat_new.shape[1])]]
  632. prob = cp.Problem(cp.Minimize(cost_fun), constraints)
  633. self.__execute_cvx(prob)
  634. edit_costs_new = x.value
  635. residual = np.sqrt(prob.value)
  636. elif is_n_attr and not is_e_attr:
  637. nb_cost_mat_new = nb_cost_mat[:,[0,1,2,3,4]]
  638. x = cp.Variable(nb_cost_mat_new.shape[1])
  639. cost_fun = cp.sum_squares(nb_cost_mat_new @ x - dis_k_vec)
  640. constraints = [x >= [0.01 for i in range(nb_cost_mat_new.shape[1])]]
  641. prob = cp.Problem(cp.Minimize(cost_fun), constraints)
  642. self.__execute_cvx(prob)
  643. edit_costs_new = np.concatenate((x.value, np.array([0.0])))
  644. residual = np.sqrt(prob.value)
  645. elif not is_n_attr and is_e_attr:
  646. nb_cost_mat_new = nb_cost_mat[:,[0,1,3,4,5]]
  647. x = cp.Variable(nb_cost_mat_new.shape[1])
  648. cost_fun = cp.sum_squares(nb_cost_mat_new @ x - dis_k_vec)
  649. constraints = [x >= [0.01 for i in range(nb_cost_mat_new.shape[1])]]
  650. prob = cp.Problem(cp.Minimize(cost_fun), constraints)
  651. self.__execute_cvx(prob)
  652. edit_costs_new = np.concatenate((x.value[0:2], np.array([0.0]), x.value[2:]))
  653. residual = np.sqrt(prob.value)
  654. else:
  655. nb_cost_mat_new = nb_cost_mat[:,[0,1,3,4]]
  656. x = cp.Variable(nb_cost_mat_new.shape[1])
  657. cost_fun = cp.sum_squares(nb_cost_mat_new @ x - dis_k_vec)
  658. constraints = [x >= [0.01 for i in range(nb_cost_mat_new.shape[1])]]
  659. prob = cp.Problem(cp.Minimize(cost_fun), constraints)
  660. self.__execute_cvx(prob)
  661. edit_costs_new = np.concatenate((x.value[0:2], np.array([0.0]),
  662. x.value[2:], np.array([0.0])))
  663. residual = np.sqrt(prob.value)
  664. elif self.__triangle_rule and not self.__allow_zeros:
  665. # c_vs <= c_vi + c_vr.
  666. if is_n_attr and is_e_attr:
  667. nb_cost_mat_new = nb_cost_mat[:,[0,1,2,3,4,5]]
  668. x = cp.Variable(nb_cost_mat_new.shape[1])
  669. cost_fun = cp.sum_squares(nb_cost_mat_new @ x - dis_k_vec)
  670. constraints = [x >= [0.01 for i in range(nb_cost_mat_new.shape[1])],
  671. np.array([1.0, 1.0, -1.0, 0.0, 0.0, 0.0]).T@x >= 0.0,
  672. np.array([0.0, 0.0, 0.0, 1.0, 1.0, -1.0]).T@x >= 0.0]
  673. prob = cp.Problem(cp.Minimize(cost_fun), constraints)
  674. self.__execute_cvx(prob)
  675. edit_costs_new = x.value
  676. residual = np.sqrt(prob.value)
  677. elif is_n_attr and not is_e_attr:
  678. nb_cost_mat_new = nb_cost_mat[:,[0,1,2,3,4]]
  679. x = cp.Variable(nb_cost_mat_new.shape[1])
  680. cost_fun = cp.sum_squares(nb_cost_mat_new @ x - dis_k_vec)
  681. constraints = [x >= [0.01 for i in range(nb_cost_mat_new.shape[1])],
  682. np.array([1.0, 1.0, -1.0, 0.0, 0.0]).T@x >= 0.0]
  683. prob = cp.Problem(cp.Minimize(cost_fun), constraints)
  684. self.__execute_cvx(prob)
  685. edit_costs_new = np.concatenate((x.value, np.array([0.0])))
  686. residual = np.sqrt(prob.value)
  687. elif not is_n_attr and is_e_attr:
  688. nb_cost_mat_new = nb_cost_mat[:,[0,1,3,4,5]]
  689. x = cp.Variable(nb_cost_mat_new.shape[1])
  690. cost_fun = cp.sum_squares(nb_cost_mat_new @ x - dis_k_vec)
  691. constraints = [x >= [0.01 for i in range(nb_cost_mat_new.shape[1])],
  692. np.array([0.0, 0.0, 1.0, 1.0, -1.0]).T@x >= 0.0]
  693. prob = cp.Problem(cp.Minimize(cost_fun), constraints)
  694. self.__execute_cvx(prob)
  695. edit_costs_new = np.concatenate((x.value[0:2], np.array([0.0]), x.value[2:]))
  696. residual = np.sqrt(prob.value)
  697. else:
  698. nb_cost_mat_new = nb_cost_mat[:,[0,1,3,4]]
  699. x = cp.Variable(nb_cost_mat_new.shape[1])
  700. cost_fun = cp.sum_squares(nb_cost_mat_new @ x - dis_k_vec)
  701. constraints = [x >= [0.01 for i in range(nb_cost_mat_new.shape[1])]]
  702. prob = cp.Problem(cp.Minimize(cost_fun), constraints)
  703. self.__execute_cvx(prob)
  704. edit_costs_new = np.concatenate((x.value[0:2], np.array([0.0]),
  705. x.value[2:], np.array([0.0])))
  706. residual = np.sqrt(prob.value)
  707. elif self.__ged_options['edit_cost'] == 'CONSTANT': # @todo: node/edge may not labeled.
  708. if not self.__triangle_rule and self.__allow_zeros:
  709. x = cp.Variable(nb_cost_mat.shape[1])
  710. cost_fun = cp.sum_squares(nb_cost_mat @ x - dis_k_vec)
  711. constraints = [x >= [0.0 for i in range(nb_cost_mat.shape[1])],
  712. np.array([1.0, 0.0, 0.0, 0.0, 0.0, 0.0]).T@x >= 0.01,
  713. np.array([0.0, 1.0, 0.0, 0.0, 0.0, 0.0]).T@x >= 0.01,
  714. np.array([0.0, 0.0, 0.0, 1.0, 0.0, 0.0]).T@x >= 0.01,
  715. np.array([0.0, 0.0, 0.0, 0.0, 1.0, 0.0]).T@x >= 0.01]
  716. prob = cp.Problem(cp.Minimize(cost_fun), constraints)
  717. self.__execute_cvx(prob)
  718. edit_costs_new = x.value
  719. residual = np.sqrt(prob.value)
  720. elif self.__triangle_rule and self.__allow_zeros:
  721. x = cp.Variable(nb_cost_mat.shape[1])
  722. cost_fun = cp.sum_squares(nb_cost_mat @ x - dis_k_vec)
  723. constraints = [x >= [0.0 for i in range(nb_cost_mat.shape[1])],
  724. np.array([1.0, 0.0, 0.0, 0.0, 0.0, 0.0]).T@x >= 0.01,
  725. np.array([0.0, 1.0, 0.0, 0.0, 0.0, 0.0]).T@x >= 0.01,
  726. np.array([0.0, 0.0, 0.0, 1.0, 0.0, 0.0]).T@x >= 0.01,
  727. np.array([0.0, 0.0, 0.0, 0.0, 1.0, 0.0]).T@x >= 0.01,
  728. np.array([1.0, 1.0, -1.0, 0.0, 0.0, 0.0]).T@x >= 0.0,
  729. np.array([0.0, 0.0, 0.0, 1.0, 1.0, -1.0]).T@x >= 0.0]
  730. prob = cp.Problem(cp.Minimize(cost_fun), constraints)
  731. self.__execute_cvx(prob)
  732. edit_costs_new = x.value
  733. residual = np.sqrt(prob.value)
  734. elif not self.__triangle_rule and not self.__allow_zeros:
  735. x = cp.Variable(nb_cost_mat.shape[1])
  736. cost_fun = cp.sum_squares(nb_cost_mat @ x - dis_k_vec)
  737. constraints = [x >= [0.01 for i in range(nb_cost_mat.shape[1])]]
  738. prob = cp.Problem(cp.Minimize(cost_fun), constraints)
  739. self.__execute_cvx(prob)
  740. edit_costs_new = x.value
  741. residual = np.sqrt(prob.value)
  742. elif self.__triangle_rule and not self.__allow_zeros:
  743. x = cp.Variable(nb_cost_mat.shape[1])
  744. cost_fun = cp.sum_squares(nb_cost_mat @ x - dis_k_vec)
  745. constraints = [x >= [0.01 for i in range(nb_cost_mat.shape[1])],
  746. np.array([1.0, 1.0, -1.0, 0.0, 0.0, 0.0]).T@x >= 0.0,
  747. np.array([0.0, 0.0, 0.0, 1.0, 1.0, -1.0]).T@x >= 0.0]
  748. prob = cp.Problem(cp.Minimize(cost_fun), constraints)
  749. self.__execute_cvx(prob)
  750. edit_costs_new = x.value
  751. residual = np.sqrt(prob.value)
  752. else:
  753. raise Exception('The edit cost "', self.__ged_options['edit_cost'], '" is not supported for update progress.')
  754. # # method 1: simple least square method.
  755. # edit_costs_new, residual, _, _ = np.linalg.lstsq(nb_cost_mat, dis_k_vec,
  756. # rcond=None)
  757. # # method 2: least square method with x_i >= 0.
  758. # edit_costs_new, residual = optimize.nnls(nb_cost_mat, dis_k_vec)
  759. # method 3: solve as a quadratic program with constraints.
  760. # P = np.dot(nb_cost_mat.T, nb_cost_mat)
  761. # q_T = -2 * np.dot(dis_k_vec.T, nb_cost_mat)
  762. # G = -1 * np.identity(nb_cost_mat.shape[1])
  763. # h = np.array([0 for i in range(nb_cost_mat.shape[1])])
  764. # A = np.array([1 for i in range(nb_cost_mat.shape[1])])
  765. # b = 1
  766. # x = cp.Variable(nb_cost_mat.shape[1])
  767. # prob = cp.Problem(cp.Minimize(cp.quad_form(x, P) + q_T@x),
  768. # [G@x <= h])
  769. # prob.solve()
  770. # edit_costs_new = x.value
  771. # residual = prob.value - np.dot(dis_k_vec.T, dis_k_vec)
  772. # G = -1 * np.identity(nb_cost_mat.shape[1])
  773. # h = np.array([0 for i in range(nb_cost_mat.shape[1])])
  774. x = cp.Variable(nb_cost_mat.shape[1])
  775. cost_fun = cp.sum_squares(nb_cost_mat @ x - dis_k_vec)
  776. constraints = [x >= [0.0 for i in range(nb_cost_mat.shape[1])],
  777. # np.array([1.0, 1.0, -1.0, 0.0, 0.0]).T@x >= 0.0]
  778. np.array([1.0, 1.0, -1.0, 0.0, 0.0, 0.0]).T@x >= 0.0,
  779. np.array([0.0, 0.0, 0.0, 1.0, 1.0, -1.0]).T@x >= 0.0]
  780. prob = cp.Problem(cp.Minimize(cost_fun), constraints)
  781. self.__execute_cvx(prob)
  782. edit_costs_new = x.value
  783. residual = np.sqrt(prob.value)
  784. # method 4:
  785. return edit_costs_new, residual
  786. def __execute_cvx(self, prob):
  787. try:
  788. prob.solve(verbose=(self._verbose>=2))
  789. except MemoryError as error0:
  790. if self._verbose >= 2:
  791. print('\nUsing solver "OSQP" caused a memory error.')
  792. print('the original error message is\n', error0)
  793. print('solver status: ', prob.status)
  794. print('trying solver "CVXOPT" instead...\n')
  795. try:
  796. prob.solve(solver=cp.CVXOPT, verbose=(self._verbose>=2))
  797. except Exception as error1:
  798. if self._verbose >= 2:
  799. print('\nAn error occured when using solver "CVXOPT".')
  800. print('the original error message is\n', error1)
  801. print('solver status: ', prob.status)
  802. print('trying solver "MOSEK" instead. Notice this solver is commercial and a lisence is required.\n')
  803. prob.solve(solver=cp.MOSEK, verbose=(self._verbose>=2))
  804. else:
  805. if self._verbose >= 2:
  806. print('solver status: ', prob.status)
  807. else:
  808. if self._verbose >= 2:
  809. print('solver status: ', prob.status)
  810. if self._verbose >= 2:
  811. print()
  812. def __gmg_bcu(self):
  813. """
  814. The local search algorithm based on block coordinate update (BCU) for estimating a generalized median graph (GMG).
  815. Returns
  816. -------
  817. None.
  818. """
  819. # Set up the ged environment.
  820. ged_env = GEDEnv() # @todo: maybe create a ged_env as a private varible.
  821. # gedlibpy.restart_env()
  822. ged_env.set_edit_cost(self.__ged_options['edit_cost'], edit_cost_constants=self.__edit_cost_constants)
  823. graphs = [self.__clean_graph(g) for g in self._dataset.graphs]
  824. for g in graphs:
  825. ged_env.add_nx_graph(g, '')
  826. graph_ids = ged_env.get_all_graph_ids()
  827. set_median_id = ged_env.add_graph('set_median')
  828. gen_median_id = ged_env.add_graph('gen_median')
  829. ged_env.init(init_type=self.__ged_options['init_option'])
  830. # Set up the madian graph estimator.
  831. self.__mge = MedianGraphEstimator(ged_env, constant_node_costs(self.__ged_options['edit_cost']))
  832. self.__mge.set_refine_method(self.__ged_options['method'], ged_options_to_string(self.__ged_options))
  833. options = self.__mge_options.copy()
  834. if not 'seed' in options:
  835. options['seed'] = int(round(time.time() * 1000)) # @todo: may not work correctly for possible parallel usage.
  836. options['parallel'] = self.__parallel
  837. # Select the GED algorithm.
  838. self.__mge.set_options(mge_options_to_string(options))
  839. self.__mge.set_label_names(node_labels=self._dataset.node_labels,
  840. edge_labels=self._dataset.edge_labels,
  841. node_attrs=self._dataset.node_attrs,
  842. edge_attrs=self._dataset.edge_attrs)
  843. ged_options = self.__ged_options.copy()
  844. if self.__parallel:
  845. ged_options['threads'] = 1
  846. self.__mge.set_init_method(ged_options['method'], ged_options_to_string(ged_options))
  847. self.__mge.set_descent_method(ged_options['method'], ged_options_to_string(ged_options))
  848. # Run the estimator.
  849. self.__mge.run(graph_ids, set_median_id, gen_median_id)
  850. # Get SODs.
  851. self.__sod_set_median = self.__mge.get_sum_of_distances('initialized')
  852. self.__sod_gen_median = self.__mge.get_sum_of_distances('converged')
  853. # Get median graphs.
  854. self.__set_median = ged_env.get_nx_graph(set_median_id)
  855. self.__gen_median = ged_env.get_nx_graph(gen_median_id)
  856. def __compute_distances_to_true_median(self):
  857. # compute distance in kernel space for set median.
  858. kernels_to_sm, _ = self._graph_kernel.compute(self.__set_median, self._dataset.graphs, **self._kernel_options)
  859. kernel_sm, _ = self._graph_kernel.compute(self.__set_median, self.__set_median, **self._kernel_options)
  860. if self._kernel_options['normalize']:
  861. kernels_to_sm = [kernels_to_sm[i] / np.sqrt(self.__gram_matrix_unnorm[i, i] * kernel_sm) for i in range(len(kernels_to_sm))] # normalize
  862. kernel_sm = 1
  863. # @todo: not correct kernel value
  864. gram_with_sm = np.concatenate((np.array([kernels_to_sm]), np.copy(self._graph_kernel.gram_matrix)), axis=0)
  865. gram_with_sm = np.concatenate((np.array([[kernel_sm] + kernels_to_sm]).T, gram_with_sm), axis=1)
  866. self.__k_dis_set_median = compute_k_dis(0, range(1, 1+len(self._dataset.graphs)),
  867. [1 / len(self._dataset.graphs)] * len(self._dataset.graphs),
  868. gram_with_sm, withterm3=False)
  869. # compute distance in kernel space for generalized median.
  870. kernels_to_gm, _ = self._graph_kernel.compute(self.__gen_median, self._dataset.graphs, **self._kernel_options)
  871. kernel_gm, _ = self._graph_kernel.compute(self.__gen_median, self.__gen_median, **self._kernel_options)
  872. if self._kernel_options['normalize']:
  873. kernels_to_gm = [kernels_to_gm[i] / np.sqrt(self.__gram_matrix_unnorm[i, i] * kernel_gm) for i in range(len(kernels_to_gm))] # normalize
  874. kernel_gm = 1
  875. gram_with_gm = np.concatenate((np.array([kernels_to_gm]), np.copy(self._graph_kernel.gram_matrix)), axis=0)
  876. gram_with_gm = np.concatenate((np.array([[kernel_gm] + kernels_to_gm]).T, gram_with_gm), axis=1)
  877. self.__k_dis_gen_median = compute_k_dis(0, range(1, 1+len(self._dataset.graphs)),
  878. [1 / len(self._dataset.graphs)] * len(self._dataset.graphs),
  879. gram_with_gm, withterm3=False)
  880. # compute distance in kernel space for each graph in median set.
  881. k_dis_median_set = []
  882. for idx in range(len(self._dataset.graphs)):
  883. k_dis_median_set.append(compute_k_dis(idx+1, range(1, 1+len(self._dataset.graphs)),
  884. [1 / len(self._dataset.graphs)] * len(self._dataset.graphs),
  885. gram_with_gm, withterm3=False))
  886. idx_k_dis_median_set_min = np.argmin(k_dis_median_set)
  887. self.__k_dis_dataset = k_dis_median_set[idx_k_dis_median_set_min]
  888. self.__best_from_dataset = self._dataset.graphs[idx_k_dis_median_set_min].copy()
  889. if self._verbose >= 2:
  890. print()
  891. print('distance in kernel space for set median:', self.__k_dis_set_median)
  892. print('distance in kernel space for generalized median:', self.__k_dis_gen_median)
  893. print('minimum distance in kernel space for each graph in median set:', self.__k_dis_dataset)
  894. print('distance in kernel space for each graph in median set:', k_dis_median_set)
  895. # def __clean_graph(self, G, node_labels=[], edge_labels=[], node_attrs=[], edge_attrs=[]):
  896. def __clean_graph(self, G): # @todo: this may not be needed when datafile is updated.
  897. """
  898. Cleans node and edge labels and attributes of the given graph.
  899. """
  900. G_new = nx.Graph(**G.graph)
  901. for nd, attrs in G.nodes(data=True):
  902. G_new.add_node(str(nd)) # @todo: should we keep this as str()?
  903. for l_name in self._dataset.node_labels:
  904. G_new.nodes[str(nd)][l_name] = str(attrs[l_name])
  905. for a_name in self._dataset.node_attrs:
  906. G_new.nodes[str(nd)][a_name] = str(attrs[a_name])
  907. for nd1, nd2, attrs in G.edges(data=True):
  908. G_new.add_edge(str(nd1), str(nd2))
  909. for l_name in self._dataset.edge_labels:
  910. G_new.edges[str(nd1), str(nd2)][l_name] = str(attrs[l_name])
  911. for a_name in self._dataset.edge_attrs:
  912. G_new.edges[str(nd1), str(nd2)][a_name] = str(attrs[a_name])
  913. return G_new
  914. @property
  915. def mge(self):
  916. return self.__mge
  917. @property
  918. def ged_options(self):
  919. return self.__ged_options
  920. @ged_options.setter
  921. def ged_options(self, value):
  922. self.__ged_options = value
  923. @property
  924. def mge_options(self):
  925. return self.__mge_options
  926. @mge_options.setter
  927. def mge_options(self, value):
  928. self.__mge_options = value
  929. @property
  930. def fit_method(self):
  931. return self.__fit_method
  932. @fit_method.setter
  933. def fit_method(self, value):
  934. self.__fit_method = value
  935. @property
  936. def init_ecc(self):
  937. return self.__init_ecc
  938. @init_ecc.setter
  939. def init_ecc(self, value):
  940. self.__init_ecc = value
  941. @property
  942. def set_median(self):
  943. return self.__set_median
  944. @property
  945. def gen_median(self):
  946. return self.__gen_median
  947. @property
  948. def best_from_dataset(self):
  949. return self.__best_from_dataset
  950. @property
  951. def gram_matrix_unnorm(self):
  952. return self.__gram_matrix_unnorm
  953. @gram_matrix_unnorm.setter
  954. def gram_matrix_unnorm(self, value):
  955. self.__gram_matrix_unnorm = value

A Python package for graph kernels, graph edit distances and graph pre-image problem.