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 35 kB

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

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