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

median_preimage_generator_cml.py 48 kB

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

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