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.

preimage.py 15 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. Created on Wed Mar 6 16:03:11 2019
  5. pre-image
  6. @author: ljia
  7. """
  8. import sys
  9. import numpy as np
  10. import random
  11. import multiprocessing
  12. from tqdm import tqdm
  13. import networkx as nx
  14. import matplotlib.pyplot as plt
  15. sys.path.insert(0, "../")
  16. from pygraph.utils.graphfiles import loadDataset
  17. from pygraph.kernels.marginalizedKernel import marginalizedkernel
  18. from pygraph.kernels.untilHPathKernel import untilhpathkernel
  19. from pygraph.kernels.spKernel import spkernel
  20. import functools
  21. from pygraph.utils.kernels import deltakernel, gaussiankernel, kernelproduct
  22. from pygraph.kernels.structuralspKernel import structuralspkernel
  23. from gk_iam import dis_gstar
  24. def compute_kernel(Gn, graph_kernel, verbose):
  25. if graph_kernel == 'marginalizedkernel':
  26. Kmatrix, _ = marginalizedkernel(Gn, node_label='atom', edge_label=None,
  27. p_quit=0.03, n_iteration=10, remove_totters=False,
  28. n_jobs=multiprocessing.cpu_count(), verbose=verbose)
  29. elif graph_kernel == 'untilhpathkernel':
  30. Kmatrix, _ = untilhpathkernel(Gn, node_label='atom', edge_label=None,
  31. depth=10, k_func='MinMax', compute_method='trie',
  32. n_jobs=multiprocessing.cpu_count(), verbose=verbose)
  33. elif graph_kernel == 'spkernel':
  34. mixkernel = functools.partial(kernelproduct, deltakernel, gaussiankernel)
  35. Kmatrix, _, _ = spkernel(Gn, node_label='atom', node_kernels=
  36. {'symb': deltakernel, 'nsymb': gaussiankernel, 'mix': mixkernel},
  37. n_jobs=multiprocessing.cpu_count(), verbose=verbose)
  38. elif graph_kernel == 'structuralspkernel':
  39. mixkernel = functools.partial(kernelproduct, deltakernel, gaussiankernel)
  40. Kmatrix, _ = structuralspkernel(Gn, node_label='atom', node_kernels=
  41. {'symb': deltakernel, 'nsymb': gaussiankernel, 'mix': mixkernel},
  42. n_jobs=multiprocessing.cpu_count(), verbose=verbose)
  43. # normalization
  44. Kmatrix_diag = Kmatrix.diagonal().copy()
  45. for i in range(len(Kmatrix)):
  46. for j in range(i, len(Kmatrix)):
  47. Kmatrix[i][j] /= np.sqrt(Kmatrix_diag[i] * Kmatrix_diag[j])
  48. Kmatrix[j][i] = Kmatrix[i][j]
  49. return Kmatrix
  50. def random_preimage(Gn_init, Gn_median, alpha, idx_gi, Kmatrix, k, r_max, l, gkernel):
  51. Gn_init = [nx.convert_node_labels_to_integers(g) for g in Gn_init]
  52. # compute k nearest neighbors of phi in DN.
  53. dis_list = [] # distance between g_star and each graph.
  54. term3 = 0
  55. for i1, a1 in enumerate(alpha):
  56. for i2, a2 in enumerate(alpha):
  57. term3 += a1 * a2 * Kmatrix[idx_gi[i1], idx_gi[i2]]
  58. for ig, g in tqdm(enumerate(Gn_init), desc='computing distances', file=sys.stdout):
  59. dtemp = dis_gstar(ig, idx_gi, alpha, Kmatrix, term3=term3)
  60. dis_list.append(dtemp)
  61. # print(np.max(dis_list))
  62. # print(np.min(dis_list))
  63. # print(np.min([item for item in dis_list if item != 0]))
  64. # print(np.mean(dis_list))
  65. # sort
  66. sort_idx = np.argsort(dis_list)
  67. dis_gs = [dis_list[idis] for idis in sort_idx[0:k]] # the k shortest distances
  68. nb_best = len(np.argwhere(dis_gs == dis_gs[0]).flatten().tolist())
  69. g0hat_list = [Gn_init[idx] for idx in sort_idx[0:nb_best]] # the nearest neighbors of phi in DN
  70. if dis_gs[0] == 0: # the exact pre-image.
  71. print('The exact pre-image is found from the input dataset.')
  72. return 0, g0hat_list[0], 0
  73. dhat = dis_gs[0] # the nearest distance
  74. # ghat_list = [g.copy() for g in g0hat_list]
  75. # for g in ghat_list:
  76. # draw_Letter_graph(g)
  77. # nx.draw_networkx(g)
  78. # plt.show()
  79. # print(g.nodes(data=True))
  80. # print(g.edges(data=True))
  81. Gk = [Gn_init[ig].copy() for ig in sort_idx[0:k]] # the k nearest neighbors
  82. # for gi in Gk:
  83. ## nx.draw_networkx(gi)
  84. ## plt.show()
  85. # draw_Letter_graph(g)
  86. # print(gi.nodes(data=True))
  87. # print(gi.edges(data=True))
  88. Gs_nearest = [g.copy() for g in Gk]
  89. gihat_list = []
  90. dihat_list = []
  91. # i = 1
  92. r = 0
  93. # sod_list = [dhat]
  94. # found = False
  95. nb_updated = 0
  96. g_best = []
  97. while r < r_max:
  98. print('\nr =', r)
  99. print('itr for gk =', nb_updated, '\n')
  100. found = False
  101. dis_bests = dis_gs + dihat_list
  102. # @todo what if the log is negetive? how to choose alpha (scalar)?
  103. fdgs_list = np.array(dis_bests)
  104. if np.min(fdgs_list) < 1:
  105. fdgs_list /= np.min(dis_bests)
  106. fdgs_list = [int(item) for item in np.ceil(np.log(fdgs_list))]
  107. if np.min(fdgs_list) < 1:
  108. fdgs_list = np.array(fdgs_list) + 1
  109. for ig, gs in enumerate(Gs_nearest + gihat_list):
  110. # nx.draw_networkx(gs)
  111. # plt.show()
  112. for trail in range(0, l):
  113. # for trail in tqdm(range(0, l), desc='l loops', file=sys.stdout):
  114. # add and delete edges.
  115. gtemp = gs.copy()
  116. np.random.seed()
  117. # which edges to change.
  118. # @todo: should we use just half of the adjacency matrix for undirected graphs?
  119. nb_vpairs = nx.number_of_nodes(gs) * (nx.number_of_nodes(gs) - 1)
  120. # @todo: what if fdgs is bigger than nb_vpairs?
  121. idx_change = random.sample(range(nb_vpairs), fdgs_list[ig] if
  122. fdgs_list[ig] < nb_vpairs else nb_vpairs)
  123. # idx_change = np.random.randint(0, nx.number_of_nodes(gs) *
  124. # (nx.number_of_nodes(gs) - 1), fdgs)
  125. for item in idx_change:
  126. node1 = int(item / (nx.number_of_nodes(gs) - 1))
  127. node2 = (item - node1 * (nx.number_of_nodes(gs) - 1))
  128. if node2 >= node1: # skip the self pair.
  129. node2 += 1
  130. # @todo: is the randomness correct?
  131. if not gtemp.has_edge(node1, node2):
  132. gtemp.add_edge(node1, node2)
  133. # nx.draw_networkx(gs)
  134. # plt.show()
  135. # nx.draw_networkx(gtemp)
  136. # plt.show()
  137. else:
  138. gtemp.remove_edge(node1, node2)
  139. # nx.draw_networkx(gs)
  140. # plt.show()
  141. # nx.draw_networkx(gtemp)
  142. # plt.show()
  143. # nx.draw_networkx(gtemp)
  144. # plt.show()
  145. # compute distance between \psi and the new generated graph.
  146. # knew = marginalizedkernel([gtemp, g1, g2], node_label='atom', edge_label=None,
  147. # p_quit=lmbda, n_iteration=20, remove_totters=False,
  148. # n_jobs=multiprocessing.cpu_count(), verbose=False)
  149. knew = compute_kernel([gtemp] + Gn_median, gkernel, verbose=False)
  150. dnew = dis_gstar(0, [1, 2], alpha, knew, withterm3=False)
  151. if dnew <= dhat: # @todo: the new distance is smaller or also equal?
  152. if dnew < dhat:
  153. print('\nI am smaller!')
  154. print('ig =', str(ig), ', l =', str(trail))
  155. print(dhat, '->', dnew)
  156. nb_updated += 1
  157. elif dnew == dhat:
  158. print('I am equal!')
  159. # nx.draw_networkx(gtemp)
  160. # plt.show()
  161. # print(gtemp.nodes(data=True))
  162. # print(gtemp.edges(data=True))
  163. dhat = dnew
  164. gnew = gtemp.copy()
  165. found = True # found better graph.
  166. if found:
  167. r = 0
  168. gihat_list = [gnew]
  169. dihat_list = [dhat]
  170. else:
  171. r += 1
  172. # dis_best.append(dhat)
  173. g_best = (g0hat_list[0] if len(gihat_list) == 0 else gihat_list[0])
  174. return dhat, g_best, nb_updated
  175. # return 0, 0, 0
  176. if __name__ == '__main__':
  177. # ds = {'name': 'MUTAG', 'dataset': '../datasets/MUTAG/MUTAG_A.txt',
  178. # 'extra_params': {}} # node/edge symb
  179. ds = {'name': 'Letter-high', 'dataset': '../datasets/Letter-high/Letter-high_A.txt',
  180. 'extra_params': {}} # node nsymb
  181. # ds = {'name': 'Acyclic', 'dataset': '../datasets/monoterpenoides/trainset_9.ds',
  182. # 'extra_params': {}}
  183. # ds = {'name': 'Acyclic', 'dataset': '../datasets/acyclic/dataset_bps.ds',
  184. # 'extra_params': {}} # node symb
  185. DN, y_all = loadDataset(ds['dataset'], extra_params=ds['extra_params'])
  186. #DN = DN[0:10]
  187. lmbda = 0.03 # termination probalility
  188. r_max = 3 # 10 # iteration limit.
  189. l = 500
  190. alpha_range = np.linspace(0.5, 0.5, 1)
  191. #alpha_range = np.linspace(0.1, 0.9, 9)
  192. k = 10 # 5 # k nearest neighbors
  193. # randomly select two molecules
  194. #np.random.seed(1)
  195. #idx1, idx2 = np.random.randint(0, len(DN), 2)
  196. #g1 = DN[idx1]
  197. #g2 = DN[idx2]
  198. idx1 = 0
  199. idx2 = 6
  200. g1 = DN[idx1]
  201. g2 = DN[idx2]
  202. # compute
  203. k_list = [] # kernel between each graph and itself.
  204. k_g1_list = [] # kernel between each graph and g1
  205. k_g2_list = [] # kernel between each graph and g2
  206. for ig, g in tqdm(enumerate(DN), desc='computing self kernels', file=sys.stdout):
  207. # ktemp = marginalizedkernel([g, g1, g2], node_label='atom', edge_label=None,
  208. # p_quit=lmbda, n_iteration=20, remove_totters=False,
  209. # n_jobs=multiprocessing.cpu_count(), verbose=False)
  210. ktemp = compute_kernel([g, g1, g2], 'untilhpathkernel', verbose=False)
  211. k_list.append(ktemp[0, 0])
  212. k_g1_list.append(ktemp[0, 1])
  213. k_g2_list.append(ktemp[0, 2])
  214. g_best = []
  215. dis_best = []
  216. # for each alpha
  217. for alpha in alpha_range:
  218. print('alpha =', alpha)
  219. # compute k nearest neighbors of phi in DN.
  220. dis_list = [] # distance between g_star and each graph.
  221. for ig, g in tqdm(enumerate(DN), desc='computing distances', file=sys.stdout):
  222. dtemp = k_list[ig] - 2 * (alpha * k_g1_list[ig] + (1 - alpha) *
  223. k_g2_list[ig]) + (alpha * alpha * k_list[idx1] + alpha *
  224. (1 - alpha) * k_g2_list[idx1] + (1 - alpha) * alpha *
  225. k_g1_list[idx2] + (1 - alpha) * (1 - alpha) * k_list[idx2])
  226. dis_list.append(np.sqrt(dtemp))
  227. # sort
  228. sort_idx = np.argsort(dis_list)
  229. dis_gs = [dis_list[idis] for idis in sort_idx[0:k]]
  230. g0hat = DN[sort_idx[0]] # the nearest neighbor of phi in DN
  231. if dis_gs[0] == 0: # the exact pre-image.
  232. print('The exact pre-image is found from the input dataset.')
  233. g_pimg = g0hat
  234. break
  235. dhat = dis_gs[0] # the nearest distance
  236. Dk = [DN[ig] for ig in sort_idx[0:k]] # the k nearest neighbors
  237. gihat_list = []
  238. i = 1
  239. r = 1
  240. while r < r_max:
  241. print('r =', r)
  242. found = False
  243. for ig, gs in enumerate(Dk + gihat_list):
  244. # nx.draw_networkx(gs)
  245. # plt.show()
  246. # @todo what if the log is negetive?
  247. fdgs = int(np.abs(np.ceil(np.log(alpha * dis_gs[ig]))))
  248. for trail in tqdm(range(0, l), desc='l loop', file=sys.stdout):
  249. # add and delete edges.
  250. gtemp = gs.copy()
  251. np.random.seed()
  252. # which edges to change.
  253. # @todo: should we use just half of the adjacency matrix for undirected graphs?
  254. nb_vpairs = nx.number_of_nodes(gs) * (nx.number_of_nodes(gs) - 1)
  255. # @todo: what if fdgs is bigger than nb_vpairs?
  256. idx_change = random.sample(range(nb_vpairs), fdgs if fdgs < nb_vpairs else nb_vpairs)
  257. # idx_change = np.random.randint(0, nx.number_of_nodes(gs) *
  258. # (nx.number_of_nodes(gs) - 1), fdgs)
  259. for item in idx_change:
  260. node1 = int(item / (nx.number_of_nodes(gs) - 1))
  261. node2 = (item - node1 * (nx.number_of_nodes(gs) - 1))
  262. if node2 >= node1: # skip the self pair.
  263. node2 += 1
  264. # @todo: is the randomness correct?
  265. if not gtemp.has_edge(node1, node2):
  266. # @todo: how to update the bond_type? 0 or 1?
  267. gtemp.add_edges_from([(node1, node2, {'bond_type': 1})])
  268. # nx.draw_networkx(gs)
  269. # plt.show()
  270. # nx.draw_networkx(gtemp)
  271. # plt.show()
  272. else:
  273. gtemp.remove_edge(node1, node2)
  274. # nx.draw_networkx(gs)
  275. # plt.show()
  276. # nx.draw_networkx(gtemp)
  277. # plt.show()
  278. # nx.draw_networkx(gtemp)
  279. # plt.show()
  280. # compute distance between phi and the new generated graph.
  281. # knew = marginalizedkernel([gtemp, g1, g2], node_label='atom', edge_label=None,
  282. # p_quit=lmbda, n_iteration=20, remove_totters=False,
  283. # n_jobs=multiprocessing.cpu_count(), verbose=False)
  284. knew = compute_kernel([gtemp, g1, g2], 'untilhpathkernel', verbose=False)
  285. dnew = np.sqrt(knew[0, 0] - 2 * (alpha * knew[0, 1] + (1 - alpha) *
  286. knew[0, 2]) + (alpha * alpha * k_list[idx1] + alpha *
  287. (1 - alpha) * k_g2_list[idx1] + (1 - alpha) * alpha *
  288. k_g1_list[idx2] + (1 - alpha) * (1 - alpha) * k_list[idx2]))
  289. if dnew < dhat: # @todo: the new distance is smaller or also equal?
  290. print('I am smaller!')
  291. print(dhat, '->', dnew)
  292. nx.draw_networkx(gtemp)
  293. plt.show()
  294. print(gtemp.nodes(data=True))
  295. print(gtemp.edges(data=True))
  296. dhat = dnew
  297. gnew = gtemp.copy()
  298. found = True # found better graph.
  299. r = 0
  300. elif dnew == dhat:
  301. print('I am equal!')
  302. if found:
  303. gihat_list = [gnew]
  304. dis_gs.append(dhat)
  305. else:
  306. r += 1
  307. dis_best.append(dhat)
  308. g_best += ([g0hat] if len(gihat_list) == 0 else gihat_list)
  309. for idx, item in enumerate(alpha_range):
  310. print('when alpha is', item, 'the shortest distance is', dis_best[idx])
  311. print('the corresponding pre-image is')
  312. nx.draw_networkx(g_best[idx])
  313. plt.show()

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