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.

iam.py 33 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. Created on Fri Apr 26 11:49:12 2019
  5. Iterative alternate minimizations using GED.
  6. @author: ljia
  7. """
  8. import numpy as np
  9. import random
  10. import networkx as nx
  11. from tqdm import tqdm
  12. import sys
  13. sys.path.insert(0, "../")
  14. from pygraph.utils.graphdataset import get_dataset_attributes
  15. from pygraph.utils.utils import graph_isIdentical, get_node_labels, get_edge_labels
  16. from ged import GED, ged_median
  17. def iam_upgraded(Gn_median, Gn_candidate, c_ei=3, c_er=3, c_es=1, ite_max=50,
  18. epsilon=0.001, node_label='atom', edge_label='bond_type',
  19. connected=False, removeNodes=True, allBestInit=False, allBestNodes=False,
  20. allBestEdges=False, allBestOutput=False,
  21. params_ged={'ged_cost': 'CHEM_1', 'ged_method': 'IPFP', 'saveGXL': 'benoit'}):
  22. """See my name, then you know what I do.
  23. """
  24. # Gn_median = Gn_median[0:10]
  25. # Gn_median = [nx.convert_node_labels_to_integers(g) for g in Gn_median]
  26. if removeNodes:
  27. node_ir = np.inf # corresponding to the node remove and insertion.
  28. label_r = 'thanksdanny' # the label for node remove. # @todo: make this label unrepeatable.
  29. ds_attrs = get_dataset_attributes(Gn_median + Gn_candidate,
  30. attr_names=['edge_labeled', 'node_attr_dim', 'edge_attr_dim'],
  31. edge_label=edge_label)
  32. def generate_graph(G, pi_p_forward, label_set):
  33. G_new_list = [G.copy()] # all "best" graphs generated in this iteration.
  34. # nx.draw_networkx(G)
  35. # import matplotlib.pyplot as plt
  36. # plt.show()
  37. # print(pi_p_forward)
  38. # update vertex labels.
  39. # pre-compute h_i0 for each label.
  40. # for label in get_node_labels(Gn, node_label):
  41. # print(label)
  42. # for nd in G.nodes(data=True):
  43. # pass
  44. if not ds_attrs['node_attr_dim']: # labels are symbolic
  45. for ndi, (nd, _) in enumerate(G.nodes(data=True)):
  46. h_i0_list = []
  47. label_list = []
  48. for label in label_set:
  49. h_i0 = 0
  50. for idx, g in enumerate(Gn_median):
  51. pi_i = pi_p_forward[idx][ndi]
  52. if pi_i != node_ir and g.nodes[pi_i][node_label] == label:
  53. h_i0 += 1
  54. h_i0_list.append(h_i0)
  55. label_list.append(label)
  56. # case when the node is to be removed.
  57. if removeNodes:
  58. h_i0_remove = 0 # @todo: maybe this can be added to the label_set above.
  59. for idx, g in enumerate(Gn_median):
  60. pi_i = pi_p_forward[idx][ndi]
  61. if pi_i == node_ir:
  62. h_i0_remove += 1
  63. h_i0_list.append(h_i0_remove)
  64. label_list.append(label_r)
  65. # get the best labels.
  66. idx_max = np.argwhere(h_i0_list == np.max(h_i0_list)).flatten().tolist()
  67. if allBestNodes: # choose all best graphs.
  68. nlabel_best = [label_list[idx] for idx in idx_max]
  69. # generate "best" graphs with regard to "best" node labels.
  70. G_new_list_nd = []
  71. for g in G_new_list: # @todo: seems it can be simplified. The G_new_list will only contain 1 graph for now.
  72. for nl in nlabel_best:
  73. g_tmp = g.copy()
  74. if nl == label_r:
  75. g_tmp.remove_node(nd)
  76. else:
  77. g_tmp.nodes[nd][node_label] = nl
  78. G_new_list_nd.append(g_tmp)
  79. # nx.draw_networkx(g_tmp)
  80. # import matplotlib.pyplot as plt
  81. # plt.show()
  82. # print(g_tmp.nodes(data=True))
  83. # print(g_tmp.edges(data=True))
  84. G_new_list = [ggg.copy() for ggg in G_new_list_nd]
  85. else:
  86. # choose one of the best randomly.
  87. h_ij0_max = h_i0_list[idx_max[0]]
  88. idx_rdm = random.randint(0, len(idx_max) - 1)
  89. best_label = label_list[idx_max[idx_rdm]]
  90. # check whether a_ij is 0 or 1.
  91. g_new = G_new_list[0]
  92. if best_label == label_r:
  93. g_new.remove_node(nd)
  94. else:
  95. g_new.nodes[nd][node_label] = best_label
  96. G_new_list = [g_new]
  97. else: # labels are non-symbolic
  98. for ndi, (nd, _) in enumerate(G.nodes(data=True)):
  99. Si_norm = 0
  100. phi_i_bar = np.array([0.0 for _ in range(ds_attrs['node_attr_dim'])])
  101. for idx, g in enumerate(Gn_median):
  102. pi_i = pi_p_forward[idx][ndi]
  103. if g.has_node(pi_i): #@todo: what if no g has node? phi_i_bar = 0?
  104. Si_norm += 1
  105. phi_i_bar += np.array([float(itm) for itm in g.nodes[pi_i]['attributes']])
  106. phi_i_bar /= Si_norm
  107. G_new_list[0].nodes[nd]['attributes'] = phi_i_bar
  108. # for g in G_new_list:
  109. # import matplotlib.pyplot as plt
  110. # nx.draw(g, labels=nx.get_node_attributes(g, 'atom'), with_labels=True)
  111. # plt.show()
  112. # print(g.nodes(data=True))
  113. # print(g.edges(data=True))
  114. # update edge labels and adjacency matrix.
  115. if ds_attrs['edge_labeled']:
  116. G_new_list_edge = []
  117. for g_new in G_new_list:
  118. nd_list = [n for n in g_new.nodes()]
  119. g_tmp_list = [g_new.copy()]
  120. for nd1i in range(nx.number_of_nodes(g_new)):
  121. nd1 = nd_list[nd1i]# @todo: not just edges, but all pairs of nodes
  122. for nd2i in range(nd1i + 1, nx.number_of_nodes(g_new)):
  123. nd2 = nd_list[nd2i]
  124. # for nd1, nd2, _ in g_new.edges(data=True):
  125. h_ij0_list = []
  126. label_list = []
  127. # @todo: compute edge label set before.
  128. for label in get_edge_labels(Gn_median, edge_label):
  129. h_ij0 = 0
  130. for idx, g in enumerate(Gn_median):
  131. pi_i = pi_p_forward[idx][nd1i]
  132. pi_j = pi_p_forward[idx][nd2i]
  133. h_ij0_p = (g.has_node(pi_i) and g.has_node(pi_j) and
  134. g.has_edge(pi_i, pi_j) and
  135. g.edges[pi_i, pi_j][edge_label] == label)
  136. h_ij0 += h_ij0_p
  137. h_ij0_list.append(h_ij0)
  138. label_list.append(label)
  139. # get the best labels.
  140. idx_max = np.argwhere(h_ij0_list == np.max(h_ij0_list)).flatten().tolist()
  141. if allBestEdges: # choose all best graphs.
  142. elabel_best = [label_list[idx] for idx in idx_max]
  143. h_ij0_max = [h_ij0_list[idx] for idx in idx_max]
  144. # generate "best" graphs with regard to "best" node labels.
  145. G_new_list_ed = []
  146. for g_tmp in g_tmp_list: # @todo: seems it can be simplified. The G_new_list will only contain 1 graph for now.
  147. for idxl, el in enumerate(elabel_best):
  148. g_tmp_copy = g_tmp.copy()
  149. # check whether a_ij is 0 or 1.
  150. sij_norm = 0
  151. for idx, g in enumerate(Gn_median):
  152. pi_i = pi_p_forward[idx][nd1i]
  153. pi_j = pi_p_forward[idx][nd2i]
  154. if g.has_node(pi_i) and g.has_node(pi_j) and \
  155. g.has_edge(pi_i, pi_j):
  156. sij_norm += 1
  157. if h_ij0_max[idxl] > len(Gn_median) * c_er / c_es + \
  158. sij_norm * (1 - (c_er + c_ei) / c_es):
  159. if not g_tmp_copy.has_edge(nd1, nd2):
  160. g_tmp_copy.add_edge(nd1, nd2)
  161. g_tmp_copy.edges[nd1, nd2][edge_label] = elabel_best[idxl]
  162. else:
  163. if g_tmp_copy.has_edge(nd1, nd2):
  164. g_tmp_copy.remove_edge(nd1, nd2)
  165. G_new_list_ed.append(g_tmp_copy)
  166. g_tmp_list = [ggg.copy() for ggg in G_new_list_ed]
  167. else: # choose one of the best randomly.
  168. h_ij0_max = h_ij0_list[idx_max[0]]
  169. idx_rdm = random.randint(0, len(idx_max) - 1)
  170. best_label = label_list[idx_max[idx_rdm]]
  171. # check whether a_ij is 0 or 1.
  172. sij_norm = 0
  173. for idx, g in enumerate(Gn_median):
  174. pi_i = pi_p_forward[idx][nd1i]
  175. pi_j = pi_p_forward[idx][nd2i]
  176. if g.has_node(pi_i) and g.has_node(pi_j) and g.has_edge(pi_i, pi_j):
  177. sij_norm += 1
  178. if h_ij0_max > len(Gn_median) * c_er / c_es + sij_norm * (1 - (c_er + c_ei) / c_es):
  179. if not g_new.has_edge(nd1, nd2):
  180. g_new.add_edge(nd1, nd2)
  181. g_new.edges[nd1, nd2][edge_label] = best_label
  182. else:
  183. if g_new.has_edge(nd1, nd2):
  184. g_new.remove_edge(nd1, nd2)
  185. g_tmp_list = [g_new]
  186. G_new_list_edge += g_tmp_list
  187. G_new_list = [ggg.copy() for ggg in G_new_list_edge]
  188. else: # if edges are unlabeled
  189. # @todo: is this even right? G or g_tmp? check if the new one is right
  190. # @todo: works only for undirected graphs.
  191. for g_tmp in G_new_list:
  192. nd_list = [n for n in g_tmp.nodes()]
  193. for nd1i in range(nx.number_of_nodes(g_tmp)):
  194. nd1 = nd_list[nd1i]
  195. for nd2i in range(nd1i + 1, nx.number_of_nodes(g_tmp)):
  196. nd2 = nd_list[nd2i]
  197. sij_norm = 0
  198. for idx, g in enumerate(Gn_median):
  199. pi_i = pi_p_forward[idx][nd1i]
  200. pi_j = pi_p_forward[idx][nd2i]
  201. if g.has_node(pi_i) and g.has_node(pi_j) and g.has_edge(pi_i, pi_j):
  202. sij_norm += 1
  203. if sij_norm > len(Gn_median) * c_er / (c_er + c_ei):
  204. # @todo: should we consider if nd1 and nd2 in g_tmp?
  205. # or just add the edge anyway?
  206. if g_tmp.has_node(nd1) and g_tmp.has_node(nd2) \
  207. and not g_tmp.has_edge(nd1, nd2):
  208. g_tmp.add_edge(nd1, nd2)
  209. # else: # @todo: which to use?
  210. elif sij_norm < len(Gn_median) * c_er / (c_er + c_ei):
  211. if g_tmp.has_edge(nd1, nd2):
  212. g_tmp.remove_edge(nd1, nd2)
  213. # do not change anything when equal.
  214. # for i, g in enumerate(G_new_list):
  215. # import matplotlib.pyplot as plt
  216. # nx.draw(g, labels=nx.get_node_attributes(g, 'atom'), with_labels=True)
  217. ## plt.savefig("results/gk_iam/simple_two/xx" + str(i) + ".png", format="PNG")
  218. # plt.show()
  219. # print(g.nodes(data=True))
  220. # print(g.edges(data=True))
  221. # # find the best graph generated in this iteration and update pi_p.
  222. # @todo: should we update all graphs generated or just the best ones?
  223. dis_list, pi_forward_list = ged_median(G_new_list, Gn_median,
  224. **params_ged)
  225. # @todo: should we remove the identical and connectivity check?
  226. # Don't know which is faster.
  227. if ds_attrs['node_attr_dim'] == 0 and ds_attrs['edge_attr_dim'] == 0:
  228. G_new_list, idx_list = remove_duplicates(G_new_list)
  229. pi_forward_list = [pi_forward_list[idx] for idx in idx_list]
  230. dis_list = [dis_list[idx] for idx in idx_list]
  231. # if connected == True:
  232. # G_new_list, idx_list = remove_disconnected(G_new_list)
  233. # pi_forward_list = [pi_forward_list[idx] for idx in idx_list]
  234. # idx_min_list = np.argwhere(dis_list == np.min(dis_list)).flatten().tolist()
  235. # dis_min = dis_list[idx_min_tmp_list[0]]
  236. # pi_forward_list = [pi_forward_list[idx] for idx in idx_min_list]
  237. # G_new_list = [G_new_list[idx] for idx in idx_min_list]
  238. # for g in G_new_list:
  239. # import matplotlib.pyplot as plt
  240. # nx.draw_networkx(g)
  241. # plt.show()
  242. # print(g.nodes(data=True))
  243. # print(g.edges(data=True))
  244. return G_new_list, pi_forward_list, dis_list
  245. def best_median_graphs(Gn_candidate, pi_all_forward, dis_all):
  246. idx_min_list = np.argwhere(dis_all == np.min(dis_all)).flatten().tolist()
  247. dis_min = dis_all[idx_min_list[0]]
  248. pi_forward_min_list = [pi_all_forward[idx] for idx in idx_min_list]
  249. G_min_list = [Gn_candidate[idx] for idx in idx_min_list]
  250. return G_min_list, pi_forward_min_list, dis_min
  251. def iteration_proc(G, pi_p_forward, cur_sod):
  252. G_list = [G]
  253. pi_forward_list = [pi_p_forward]
  254. old_sod = cur_sod * 2
  255. sod_list = [cur_sod]
  256. dis_list = [cur_sod]
  257. # iterations.
  258. itr = 0
  259. # @todo: what if difference == 0?
  260. # while itr < ite_max and (np.abs(old_sod - cur_sod) > epsilon or
  261. # np.abs(old_sod - cur_sod) == 0):
  262. while itr < ite_max and np.abs(old_sod - cur_sod) > epsilon:
  263. # for itr in range(0, 5): # the convergence condition?
  264. print('itr_iam is', itr)
  265. G_new_list = []
  266. pi_forward_new_list = []
  267. dis_new_list = []
  268. for idx, g in enumerate(G_list):
  269. label_set = get_node_labels(Gn_median + [g], node_label)
  270. G_tmp_list, pi_forward_tmp_list, dis_tmp_list = generate_graph(
  271. g, pi_forward_list[idx], label_set)
  272. G_new_list += G_tmp_list
  273. pi_forward_new_list += pi_forward_tmp_list
  274. dis_new_list += dis_tmp_list
  275. # @todo: need to remove duplicates here?
  276. G_list = [ggg.copy() for ggg in G_new_list]
  277. pi_forward_list = [pitem.copy() for pitem in pi_forward_new_list]
  278. dis_list = dis_new_list[:]
  279. old_sod = cur_sod
  280. cur_sod = np.min(dis_list)
  281. sod_list.append(cur_sod)
  282. itr += 1
  283. # @todo: do we return all graphs or the best ones?
  284. # get the best ones of the generated graphs.
  285. G_list, pi_forward_list, dis_min = best_median_graphs(
  286. G_list, pi_forward_list, dis_list)
  287. if ds_attrs['node_attr_dim'] == 0 and ds_attrs['edge_attr_dim'] == 0:
  288. G_list, idx_list = remove_duplicates(G_list)
  289. pi_forward_list = [pi_forward_list[idx] for idx in idx_list]
  290. # dis_list = [dis_list[idx] for idx in idx_list]
  291. # import matplotlib.pyplot as plt
  292. # for g in G_list:
  293. # nx.draw_networkx(g)
  294. # plt.show()
  295. # print(g.nodes(data=True))
  296. # print(g.edges(data=True))
  297. print('\nsods:', sod_list, '\n')
  298. return G_list, pi_forward_list, dis_min
  299. def remove_duplicates(Gn):
  300. """Remove duplicate graphs from list.
  301. """
  302. Gn_new = []
  303. idx_list = []
  304. for idx, g in enumerate(Gn):
  305. dupl = False
  306. for g_new in Gn_new:
  307. if graph_isIdentical(g_new, g):
  308. dupl = True
  309. break
  310. if not dupl:
  311. Gn_new.append(g)
  312. idx_list.append(idx)
  313. return Gn_new, idx_list
  314. def remove_disconnected(Gn):
  315. """Remove disconnected graphs from list.
  316. """
  317. Gn_new = []
  318. idx_list = []
  319. for idx, g in enumerate(Gn):
  320. if nx.is_connected(g):
  321. Gn_new.append(g)
  322. idx_list.append(idx)
  323. return Gn_new, idx_list
  324. ###########################################################################
  325. # phase 1: initilize.
  326. # compute set-median.
  327. dis_min = np.inf
  328. dis_list, pi_forward_all = ged_median(Gn_candidate, Gn_median,
  329. **params_ged)
  330. # find all smallest distances.
  331. if allBestInit: # try all best init graphs.
  332. idx_min_list = range(len(dis_list))
  333. dis_min = dis_list
  334. else:
  335. idx_min_list = np.argwhere(dis_list == np.min(dis_list)).flatten().tolist()
  336. dis_min = [dis_list[idx_min_list[0]]] * len(idx_min_list)
  337. # phase 2: iteration.
  338. G_list = []
  339. dis_list = []
  340. pi_forward_list = []
  341. for idx_tmp, idx_min in enumerate(idx_min_list):
  342. # print('idx_min is', idx_min)
  343. G = Gn_candidate[idx_min].copy()
  344. # list of edit operations.
  345. pi_p_forward = pi_forward_all[idx_min]
  346. # pi_p_backward = pi_all_backward[idx_min]
  347. Gi_list, pi_i_forward_list, dis_i_min = iteration_proc(G, pi_p_forward, dis_min[idx_tmp])
  348. G_list += Gi_list
  349. dis_list += [dis_i_min] * len(Gi_list)
  350. pi_forward_list += pi_i_forward_list
  351. if ds_attrs['node_attr_dim'] == 0 and ds_attrs['edge_attr_dim'] == 0:
  352. G_list, idx_list = remove_duplicates(G_list)
  353. dis_list = [dis_list[idx] for idx in idx_list]
  354. pi_forward_list = [pi_forward_list[idx] for idx in idx_list]
  355. if connected == True:
  356. G_list_con, idx_list = remove_disconnected(G_list)
  357. # if there is no connected graphs at all, then remain the disconnected ones.
  358. if len(G_list_con) > 0: # @todo: ??????????????????????????
  359. G_list = G_list_con
  360. dis_list = [dis_list[idx] for idx in idx_list]
  361. pi_forward_list = [pi_forward_list[idx] for idx in idx_list]
  362. # import matplotlib.pyplot as plt
  363. # for g in G_list:
  364. # nx.draw_networkx(g)
  365. # plt.show()
  366. # print(g.nodes(data=True))
  367. # print(g.edges(data=True))
  368. # get the best median graphs
  369. G_min_list, pi_forward_min_list, dis_min = best_median_graphs(
  370. G_list, pi_forward_list, dis_list)
  371. # for g in G_min_list:
  372. # nx.draw_networkx(g)
  373. # plt.show()
  374. # print(g.nodes(data=True))
  375. # print(g.edges(data=True))
  376. if not allBestOutput:
  377. # randomly choose one graph.
  378. idx_rdm = random.randint(0, len(G_min_list) - 1)
  379. G_min_list = [G_min_list[idx_rdm]]
  380. return G_min_list, dis_min
  381. ###############################################################################
  382. # Old implementations.
  383. def iam(Gn, c_ei=3, c_er=3, c_es=1, node_label='atom', edge_label='bond_type',
  384. connected=True):
  385. """See my name, then you know what I do.
  386. """
  387. # Gn = Gn[0:10]
  388. Gn = [nx.convert_node_labels_to_integers(g) for g in Gn]
  389. # phase 1: initilize.
  390. # compute set-median.
  391. dis_min = np.inf
  392. pi_p = []
  393. pi_all = []
  394. for idx1, G_p in enumerate(Gn):
  395. dist_sum = 0
  396. pi_all.append([])
  397. for idx2, G_p_prime in enumerate(Gn):
  398. dist_tmp, pi_tmp, _ = GED(G_p, G_p_prime)
  399. pi_all[idx1].append(pi_tmp)
  400. dist_sum += dist_tmp
  401. if dist_sum < dis_min:
  402. dis_min = dist_sum
  403. G = G_p.copy()
  404. idx_min = idx1
  405. # list of edit operations.
  406. pi_p = pi_all[idx_min]
  407. # phase 2: iteration.
  408. ds_attrs = get_dataset_attributes(Gn, attr_names=['edge_labeled', 'node_attr_dim'],
  409. edge_label=edge_label)
  410. for itr in range(0, 10): # @todo: the convergence condition?
  411. G_new = G.copy()
  412. # update vertex labels.
  413. # pre-compute h_i0 for each label.
  414. # for label in get_node_labels(Gn, node_label):
  415. # print(label)
  416. # for nd in G.nodes(data=True):
  417. # pass
  418. if not ds_attrs['node_attr_dim']: # labels are symbolic
  419. for nd, _ in G.nodes(data=True):
  420. h_i0_list = []
  421. label_list = []
  422. for label in get_node_labels(Gn, node_label):
  423. h_i0 = 0
  424. for idx, g in enumerate(Gn):
  425. pi_i = pi_p[idx][nd]
  426. if g.has_node(pi_i) and g.nodes[pi_i][node_label] == label:
  427. h_i0 += 1
  428. h_i0_list.append(h_i0)
  429. label_list.append(label)
  430. # choose one of the best randomly.
  431. idx_max = np.argwhere(h_i0_list == np.max(h_i0_list)).flatten().tolist()
  432. idx_rdm = random.randint(0, len(idx_max) - 1)
  433. G_new.nodes[nd][node_label] = label_list[idx_max[idx_rdm]]
  434. else: # labels are non-symbolic
  435. for nd, _ in G.nodes(data=True):
  436. Si_norm = 0
  437. phi_i_bar = np.array([0.0 for _ in range(ds_attrs['node_attr_dim'])])
  438. for idx, g in enumerate(Gn):
  439. pi_i = pi_p[idx][nd]
  440. if g.has_node(pi_i): #@todo: what if no g has node? phi_i_bar = 0?
  441. Si_norm += 1
  442. phi_i_bar += np.array([float(itm) for itm in g.nodes[pi_i]['attributes']])
  443. phi_i_bar /= Si_norm
  444. G_new.nodes[nd]['attributes'] = phi_i_bar
  445. # update edge labels and adjacency matrix.
  446. if ds_attrs['edge_labeled']:
  447. for nd1, nd2, _ in G.edges(data=True):
  448. h_ij0_list = []
  449. label_list = []
  450. for label in get_edge_labels(Gn, edge_label):
  451. h_ij0 = 0
  452. for idx, g in enumerate(Gn):
  453. pi_i = pi_p[idx][nd1]
  454. pi_j = pi_p[idx][nd2]
  455. h_ij0_p = (g.has_node(pi_i) and g.has_node(pi_j) and
  456. g.has_edge(pi_i, pi_j) and
  457. g.edges[pi_i, pi_j][edge_label] == label)
  458. h_ij0 += h_ij0_p
  459. h_ij0_list.append(h_ij0)
  460. label_list.append(label)
  461. # choose one of the best randomly.
  462. idx_max = np.argwhere(h_ij0_list == np.max(h_ij0_list)).flatten().tolist()
  463. h_ij0_max = h_ij0_list[idx_max[0]]
  464. idx_rdm = random.randint(0, len(idx_max) - 1)
  465. best_label = label_list[idx_max[idx_rdm]]
  466. # check whether a_ij is 0 or 1.
  467. sij_norm = 0
  468. for idx, g in enumerate(Gn):
  469. pi_i = pi_p[idx][nd1]
  470. pi_j = pi_p[idx][nd2]
  471. if g.has_node(pi_i) and g.has_node(pi_j) and g.has_edge(pi_i, pi_j):
  472. sij_norm += 1
  473. if h_ij0_max > len(Gn) * c_er / c_es + sij_norm * (1 - (c_er + c_ei) / c_es):
  474. if not G_new.has_edge(nd1, nd2):
  475. G_new.add_edge(nd1, nd2)
  476. G_new.edges[nd1, nd2][edge_label] = best_label
  477. else:
  478. if G_new.has_edge(nd1, nd2):
  479. G_new.remove_edge(nd1, nd2)
  480. else: # if edges are unlabeled
  481. for nd1, nd2, _ in G.edges(data=True):
  482. sij_norm = 0
  483. for idx, g in enumerate(Gn):
  484. pi_i = pi_p[idx][nd1]
  485. pi_j = pi_p[idx][nd2]
  486. if g.has_node(pi_i) and g.has_node(pi_j) and g.has_edge(pi_i, pi_j):
  487. sij_norm += 1
  488. if sij_norm > len(Gn) * c_er / (c_er + c_ei):
  489. if not G_new.has_edge(nd1, nd2):
  490. G_new.add_edge(nd1, nd2)
  491. else:
  492. if G_new.has_edge(nd1, nd2):
  493. G_new.remove_edge(nd1, nd2)
  494. G = G_new.copy()
  495. # update pi_p
  496. pi_p = []
  497. for idx1, G_p in enumerate(Gn):
  498. dist_tmp, pi_tmp, _ = GED(G, G_p)
  499. pi_p.append(pi_tmp)
  500. return G
  501. # --------------------------- These are tests --------------------------------#
  502. def test_iam_with_more_graphs_as_init(Gn, G_candidate, c_ei=3, c_er=3, c_es=1,
  503. node_label='atom', edge_label='bond_type'):
  504. """See my name, then you know what I do.
  505. """
  506. # Gn = Gn[0:10]
  507. Gn = [nx.convert_node_labels_to_integers(g) for g in Gn]
  508. # phase 1: initilize.
  509. # compute set-median.
  510. dis_min = np.inf
  511. # pi_p = []
  512. pi_all_forward = []
  513. pi_all_backward = []
  514. for idx1, G_p in tqdm(enumerate(G_candidate), desc='computing GEDs', file=sys.stdout):
  515. dist_sum = 0
  516. pi_all_forward.append([])
  517. pi_all_backward.append([])
  518. for idx2, G_p_prime in enumerate(Gn):
  519. dist_tmp, pi_tmp_forward, pi_tmp_backward = GED(G_p, G_p_prime)
  520. pi_all_forward[idx1].append(pi_tmp_forward)
  521. pi_all_backward[idx1].append(pi_tmp_backward)
  522. dist_sum += dist_tmp
  523. if dist_sum <= dis_min:
  524. dis_min = dist_sum
  525. G = G_p.copy()
  526. idx_min = idx1
  527. # list of edit operations.
  528. pi_p_forward = pi_all_forward[idx_min]
  529. pi_p_backward = pi_all_backward[idx_min]
  530. # phase 2: iteration.
  531. ds_attrs = get_dataset_attributes(Gn + [G], attr_names=['edge_labeled', 'node_attr_dim'],
  532. edge_label=edge_label)
  533. label_set = get_node_labels(Gn + [G], node_label)
  534. for itr in range(0, 10): # @todo: the convergence condition?
  535. G_new = G.copy()
  536. # update vertex labels.
  537. # pre-compute h_i0 for each label.
  538. # for label in get_node_labels(Gn, node_label):
  539. # print(label)
  540. # for nd in G.nodes(data=True):
  541. # pass
  542. if not ds_attrs['node_attr_dim']: # labels are symbolic
  543. for nd in G.nodes():
  544. h_i0_list = []
  545. label_list = []
  546. for label in label_set:
  547. h_i0 = 0
  548. for idx, g in enumerate(Gn):
  549. pi_i = pi_p_forward[idx][nd]
  550. if g.has_node(pi_i) and g.nodes[pi_i][node_label] == label:
  551. h_i0 += 1
  552. h_i0_list.append(h_i0)
  553. label_list.append(label)
  554. # choose one of the best randomly.
  555. idx_max = np.argwhere(h_i0_list == np.max(h_i0_list)).flatten().tolist()
  556. idx_rdm = random.randint(0, len(idx_max) - 1)
  557. G_new.nodes[nd][node_label] = label_list[idx_max[idx_rdm]]
  558. else: # labels are non-symbolic
  559. for nd in G.nodes():
  560. Si_norm = 0
  561. phi_i_bar = np.array([0.0 for _ in range(ds_attrs['node_attr_dim'])])
  562. for idx, g in enumerate(Gn):
  563. pi_i = pi_p_forward[idx][nd]
  564. if g.has_node(pi_i): #@todo: what if no g has node? phi_i_bar = 0?
  565. Si_norm += 1
  566. phi_i_bar += np.array([float(itm) for itm in g.nodes[pi_i]['attributes']])
  567. phi_i_bar /= Si_norm
  568. G_new.nodes[nd]['attributes'] = phi_i_bar
  569. # update edge labels and adjacency matrix.
  570. if ds_attrs['edge_labeled']:
  571. for nd1, nd2, _ in G.edges(data=True):
  572. h_ij0_list = []
  573. label_list = []
  574. for label in get_edge_labels(Gn, edge_label):
  575. h_ij0 = 0
  576. for idx, g in enumerate(Gn):
  577. pi_i = pi_p_forward[idx][nd1]
  578. pi_j = pi_p_forward[idx][nd2]
  579. h_ij0_p = (g.has_node(pi_i) and g.has_node(pi_j) and
  580. g.has_edge(pi_i, pi_j) and
  581. g.edges[pi_i, pi_j][edge_label] == label)
  582. h_ij0 += h_ij0_p
  583. h_ij0_list.append(h_ij0)
  584. label_list.append(label)
  585. # choose one of the best randomly.
  586. idx_max = np.argwhere(h_ij0_list == np.max(h_ij0_list)).flatten().tolist()
  587. h_ij0_max = h_ij0_list[idx_max[0]]
  588. idx_rdm = random.randint(0, len(idx_max) - 1)
  589. best_label = label_list[idx_max[idx_rdm]]
  590. # check whether a_ij is 0 or 1.
  591. sij_norm = 0
  592. for idx, g in enumerate(Gn):
  593. pi_i = pi_p_forward[idx][nd1]
  594. pi_j = pi_p_forward[idx][nd2]
  595. if g.has_node(pi_i) and g.has_node(pi_j) and g.has_edge(pi_i, pi_j):
  596. sij_norm += 1
  597. if h_ij0_max > len(Gn) * c_er / c_es + sij_norm * (1 - (c_er + c_ei) / c_es):
  598. if not G_new.has_edge(nd1, nd2):
  599. G_new.add_edge(nd1, nd2)
  600. G_new.edges[nd1, nd2][edge_label] = best_label
  601. else:
  602. if G_new.has_edge(nd1, nd2):
  603. G_new.remove_edge(nd1, nd2)
  604. else: # if edges are unlabeled
  605. # @todo: works only for undirected graphs.
  606. for nd1 in range(nx.number_of_nodes(G)):
  607. for nd2 in range(nd1 + 1, nx.number_of_nodes(G)):
  608. sij_norm = 0
  609. for idx, g in enumerate(Gn):
  610. pi_i = pi_p_forward[idx][nd1]
  611. pi_j = pi_p_forward[idx][nd2]
  612. if g.has_node(pi_i) and g.has_node(pi_j) and g.has_edge(pi_i, pi_j):
  613. sij_norm += 1
  614. if sij_norm > len(Gn) * c_er / (c_er + c_ei):
  615. if not G_new.has_edge(nd1, nd2):
  616. G_new.add_edge(nd1, nd2)
  617. elif sij_norm < len(Gn) * c_er / (c_er + c_ei):
  618. if G_new.has_edge(nd1, nd2):
  619. G_new.remove_edge(nd1, nd2)
  620. # do not change anything when equal.
  621. G = G_new.copy()
  622. # update pi_p
  623. pi_p_forward = []
  624. for G_p in Gn:
  625. dist_tmp, pi_tmp_forward, pi_tmp_backward = GED(G, G_p)
  626. pi_p_forward.append(pi_tmp_forward)
  627. return G
  628. ###############################################################################
  629. if __name__ == '__main__':
  630. from pygraph.utils.graphfiles import loadDataset
  631. ds = {'name': 'MUTAG', 'dataset': '../datasets/MUTAG/MUTAG.mat',
  632. 'extra_params': {'am_sp_al_nl_el': [0, 0, 3, 1, 2]}} # node/edge symb
  633. # ds = {'name': 'Letter-high', 'dataset': '../datasets/Letter-high/Letter-high_A.txt',
  634. # 'extra_params': {}} # node nsymb
  635. # ds = {'name': 'Acyclic', 'dataset': '../datasets/monoterpenoides/trainset_9.ds',
  636. # 'extra_params': {}}
  637. Gn, y_all = loadDataset(ds['dataset'], extra_params=ds['extra_params'])
  638. iam(Gn)

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