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_random.py 14 kB

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

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