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_py.py 46 kB

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

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