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

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

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