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

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

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