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

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

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