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

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