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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775
  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. from gklearn.utils.graphdataset import get_dataset_attributes
  13. from gklearn.utils.utils import graph_isIdentical, get_node_labels, get_edge_labels
  14. from gklearn.preimage.ged import GED, ged_median
  15. def iam_upgraded(Gn_median, Gn_candidate, c_ei=3, c_er=3, c_es=1, ite_max=50,
  16. epsilon=0.001, node_label='atom', edge_label='bond_type',
  17. connected=False, removeNodes=True, allBestInit=False, allBestNodes=False,
  18. allBestEdges=False, allBestOutput=False,
  19. params_ged={'lib': 'gedlibpy', 'cost': 'CHEM_1', 'method': 'IPFP',
  20. 'edit_cost_constant': [], 'stabilizer': None,
  21. 'algo_options': '--threads 8 --initial-solutions 40 --ratio-runs-from-initial-solutions 1'}):
  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. node_ir = np.inf # corresponding to the node remove and insertion.
  27. label_r = 'thanksdanny' # the label for node remove. # @todo: make this label unrepeatable.
  28. ds_attrs = get_dataset_attributes(Gn_median + Gn_candidate,
  29. attr_names=['edge_labeled', 'node_attr_dim', 'edge_attr_dim'],
  30. edge_label=edge_label)
  31. node_label_set = get_node_labels(Gn_median, node_label)
  32. edge_label_set = get_edge_labels(Gn_median, edge_label)
  33. def generate_graph(G, pi_p_forward):
  34. G_new_list = [G.copy()] # all "best" graphs generated in this iteration.
  35. # nx.draw_networkx(G)
  36. # import matplotlib.pyplot as plt
  37. # plt.show()
  38. # print(pi_p_forward)
  39. # update vertex labels.
  40. # pre-compute h_i0 for each label.
  41. # for label in get_node_labels(Gn, node_label):
  42. # print(label)
  43. # for nd in G.nodes(data=True):
  44. # pass
  45. if not ds_attrs['node_attr_dim']: # labels are symbolic
  46. for ndi, (nd, _) in enumerate(G.nodes(data=True)):
  47. h_i0_list = []
  48. label_list = []
  49. for label in node_label_set:
  50. h_i0 = 0
  51. for idx, g in enumerate(Gn_median):
  52. pi_i = pi_p_forward[idx][ndi]
  53. if pi_i != node_ir and g.nodes[pi_i][node_label] == label:
  54. h_i0 += 1
  55. h_i0_list.append(h_i0)
  56. label_list.append(label)
  57. # case when the node is to be removed.
  58. if removeNodes:
  59. h_i0_remove = 0 # @todo: maybe this can be added to the node_label_set above.
  60. for idx, g in enumerate(Gn_median):
  61. pi_i = pi_p_forward[idx][ndi]
  62. if pi_i == node_ir:
  63. h_i0_remove += 1
  64. h_i0_list.append(h_i0_remove)
  65. label_list.append(label_r)
  66. # get the best labels.
  67. idx_max = np.argwhere(h_i0_list == np.max(h_i0_list)).flatten().tolist()
  68. if allBestNodes: # choose all best graphs.
  69. nlabel_best = [label_list[idx] for idx in idx_max]
  70. # generate "best" graphs with regard to "best" node labels.
  71. G_new_list_nd = []
  72. for g in G_new_list: # @todo: seems it can be simplified. The G_new_list will only contain 1 graph for now.
  73. for nl in nlabel_best:
  74. g_tmp = g.copy()
  75. if nl == label_r:
  76. g_tmp.remove_node(nd)
  77. else:
  78. g_tmp.nodes[nd][node_label] = nl
  79. G_new_list_nd.append(g_tmp)
  80. # nx.draw_networkx(g_tmp)
  81. # import matplotlib.pyplot as plt
  82. # plt.show()
  83. # print(g_tmp.nodes(data=True))
  84. # print(g_tmp.edges(data=True))
  85. G_new_list = [ggg.copy() for ggg in G_new_list_nd]
  86. else:
  87. # choose one of the best randomly.
  88. idx_rdm = random.randint(0, len(idx_max) - 1)
  89. best_label = label_list[idx_max[idx_rdm]]
  90. h_i0_max = h_i0_list[idx_max[idx_rdm]]
  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. for label in edge_label_set:
  128. h_ij0 = 0
  129. for idx, g in enumerate(Gn_median):
  130. pi_i = pi_p_forward[idx][nd1i]
  131. pi_j = pi_p_forward[idx][nd2i]
  132. h_ij0_p = (g.has_node(pi_i) and g.has_node(pi_j) and
  133. g.has_edge(pi_i, pi_j) and
  134. g.edges[pi_i, pi_j][edge_label] == label)
  135. h_ij0 += h_ij0_p
  136. h_ij0_list.append(h_ij0)
  137. label_list.append(label)
  138. # get the best labels.
  139. idx_max = np.argwhere(h_ij0_list == np.max(h_ij0_list)).flatten().tolist()
  140. if allBestEdges: # choose all best graphs.
  141. elabel_best = [label_list[idx] for idx in idx_max]
  142. h_ij0_max = [h_ij0_list[idx] for idx in idx_max]
  143. # generate "best" graphs with regard to "best" node labels.
  144. G_new_list_ed = []
  145. for g_tmp in g_tmp_list: # @todo: seems it can be simplified. The G_new_list will only contain 1 graph for now.
  146. for idxl, el in enumerate(elabel_best):
  147. g_tmp_copy = g_tmp.copy()
  148. # check whether a_ij is 0 or 1.
  149. sij_norm = 0
  150. for idx, g in enumerate(Gn_median):
  151. pi_i = pi_p_forward[idx][nd1i]
  152. pi_j = pi_p_forward[idx][nd2i]
  153. if g.has_node(pi_i) and g.has_node(pi_j) and \
  154. g.has_edge(pi_i, pi_j):
  155. sij_norm += 1
  156. if h_ij0_max[idxl] > len(Gn_median) * c_er / c_es + \
  157. sij_norm * (1 - (c_er + c_ei) / c_es):
  158. if not g_tmp_copy.has_edge(nd1, nd2):
  159. g_tmp_copy.add_edge(nd1, nd2)
  160. g_tmp_copy.edges[nd1, nd2][edge_label] = elabel_best[idxl]
  161. else:
  162. if g_tmp_copy.has_edge(nd1, nd2):
  163. g_tmp_copy.remove_edge(nd1, nd2)
  164. G_new_list_ed.append(g_tmp_copy)
  165. g_tmp_list = [ggg.copy() for ggg in G_new_list_ed]
  166. else: # choose one of the best randomly.
  167. idx_rdm = random.randint(0, len(idx_max) - 1)
  168. best_label = label_list[idx_max[idx_rdm]]
  169. h_ij0_max = h_ij0_list[idx_max[idx_rdm]]
  170. # check whether a_ij is 0 or 1.
  171. sij_norm = 0
  172. for idx, g in enumerate(Gn_median):
  173. pi_i = pi_p_forward[idx][nd1i]
  174. pi_j = pi_p_forward[idx][nd2i]
  175. if g.has_node(pi_i) and g.has_node(pi_j) and g.has_edge(pi_i, pi_j):
  176. sij_norm += 1
  177. if h_ij0_max > len(Gn_median) * c_er / c_es + sij_norm * (1 - (c_er + c_ei) / c_es):
  178. if not g_new.has_edge(nd1, nd2):
  179. g_new.add_edge(nd1, nd2)
  180. g_new.edges[nd1, nd2][edge_label] = best_label
  181. else:
  182. # elif h_ij0_max < len(Gn_median) * c_er / c_es + sij_norm * (1 - (c_er + c_ei) / c_es):
  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=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. # while itr < ite_max:
  264. # for itr in range(0, 5): # the convergence condition?
  265. print('itr_iam is', itr)
  266. G_new_list = []
  267. pi_forward_new_list = []
  268. dis_new_list = []
  269. for idx, g in enumerate(G_list):
  270. # label_set = get_node_labels(Gn_median + [g], node_label)
  271. G_tmp_list, pi_forward_tmp_list, dis_tmp_list = generate_graph(
  272. g, pi_forward_list[idx])
  273. G_new_list += G_tmp_list
  274. pi_forward_new_list += pi_forward_tmp_list
  275. dis_new_list += dis_tmp_list
  276. # @todo: need to remove duplicates here?
  277. G_list = [ggg.copy() for ggg in G_new_list]
  278. pi_forward_list = [pitem.copy() for pitem in pi_forward_new_list]
  279. dis_list = dis_new_list[:]
  280. old_sod = cur_sod
  281. cur_sod = np.min(dis_list)
  282. sod_list.append(cur_sod)
  283. itr += 1
  284. # @todo: do we return all graphs or the best ones?
  285. # get the best ones of the generated graphs.
  286. G_list, pi_forward_list, dis_min = best_median_graphs(
  287. G_list, pi_forward_list, dis_list)
  288. if ds_attrs['node_attr_dim'] == 0 and ds_attrs['edge_attr_dim'] == 0:
  289. G_list, idx_list = remove_duplicates(G_list)
  290. pi_forward_list = [pi_forward_list[idx] for idx in idx_list]
  291. # dis_list = [dis_list[idx] for idx in idx_list]
  292. # import matplotlib.pyplot as plt
  293. # for g in G_list:
  294. # nx.draw_networkx(g)
  295. # plt.show()
  296. # print(g.nodes(data=True))
  297. # print(g.edges(data=True))
  298. print('\nsods:', sod_list, '\n')
  299. return G_list, pi_forward_list, dis_min, sod_list
  300. def remove_duplicates(Gn):
  301. """Remove duplicate graphs from list.
  302. """
  303. Gn_new = []
  304. idx_list = []
  305. for idx, g in enumerate(Gn):
  306. dupl = False
  307. for g_new in Gn_new:
  308. if graph_isIdentical(g_new, g):
  309. dupl = True
  310. break
  311. if not dupl:
  312. Gn_new.append(g)
  313. idx_list.append(idx)
  314. return Gn_new, idx_list
  315. def remove_disconnected(Gn):
  316. """Remove disconnected graphs from list.
  317. """
  318. Gn_new = []
  319. idx_list = []
  320. for idx, g in enumerate(Gn):
  321. if nx.is_connected(g):
  322. Gn_new.append(g)
  323. idx_list.append(idx)
  324. return Gn_new, idx_list
  325. ###########################################################################
  326. # phase 1: initilize.
  327. # compute set-median.
  328. dis_min = np.inf
  329. dis_list, pi_forward_all = ged_median(Gn_candidate, Gn_median,
  330. params_ged=params_ged, parallel=True)
  331. print('finish computing GEDs.')
  332. # find all smallest distances.
  333. if allBestInit: # try all best init graphs.
  334. idx_min_list = range(len(dis_list))
  335. dis_min = dis_list
  336. else:
  337. idx_min_list = np.argwhere(dis_list == np.min(dis_list)).flatten().tolist()
  338. dis_min = [dis_list[idx_min_list[0]]] * len(idx_min_list)
  339. idx_min_rdm = random.randint(0, len(idx_min_list) - 1)
  340. idx_min_list = [idx_min_list[idx_min_rdm]]
  341. sod_set_median = np.min(dis_min)
  342. # phase 2: iteration.
  343. G_list = []
  344. dis_list = []
  345. pi_forward_list = []
  346. G_set_median_list = []
  347. # sod_list = []
  348. for idx_tmp, idx_min in enumerate(idx_min_list):
  349. # print('idx_min is', idx_min)
  350. G = Gn_candidate[idx_min].copy()
  351. G_set_median_list.append(G.copy())
  352. # list of edit operations.
  353. pi_p_forward = pi_forward_all[idx_min]
  354. # pi_p_backward = pi_all_backward[idx_min]
  355. Gi_list, pi_i_forward_list, dis_i_min, sod_list = iteration_proc(G,
  356. pi_p_forward, dis_min[idx_tmp])
  357. G_list += Gi_list
  358. dis_list += [dis_i_min] * len(Gi_list)
  359. pi_forward_list += pi_i_forward_list
  360. if ds_attrs['node_attr_dim'] == 0 and ds_attrs['edge_attr_dim'] == 0:
  361. G_list, idx_list = remove_duplicates(G_list)
  362. dis_list = [dis_list[idx] for idx in idx_list]
  363. pi_forward_list = [pi_forward_list[idx] for idx in idx_list]
  364. if connected == True:
  365. G_list_con, idx_list = remove_disconnected(G_list)
  366. # if there is no connected graphs at all, then remain the disconnected ones.
  367. if len(G_list_con) > 0: # @todo: ??????????????????????????
  368. G_list = G_list_con
  369. dis_list = [dis_list[idx] for idx in idx_list]
  370. pi_forward_list = [pi_forward_list[idx] for idx in idx_list]
  371. # import matplotlib.pyplot as plt
  372. # for g in G_list:
  373. # nx.draw_networkx(g)
  374. # plt.show()
  375. # print(g.nodes(data=True))
  376. # print(g.edges(data=True))
  377. # get the best median graphs
  378. G_gen_median_list, pi_forward_min_list, sod_gen_median = best_median_graphs(
  379. G_list, pi_forward_list, dis_list)
  380. # for g in G_gen_median_list:
  381. # nx.draw_networkx(g)
  382. # plt.show()
  383. # print(g.nodes(data=True))
  384. # print(g.edges(data=True))
  385. if not allBestOutput:
  386. # randomly choose one graph.
  387. idx_rdm = random.randint(0, len(G_gen_median_list) - 1)
  388. G_gen_median_list = [G_gen_median_list[idx_rdm]]
  389. return G_gen_median_list, sod_gen_median, sod_list, G_set_median_list, sod_set_median
  390. def iam_bash(Gn_names, edit_cost_constant, cost='CONSTANT', initial_solutions=1,
  391. dataset='monoterpenoides',
  392. graph_dir=''):
  393. """Compute the iam by c++ implementation (gedlib) through bash.
  394. """
  395. import os
  396. import time
  397. def createCollectionFile(Gn_names, y, filename):
  398. """Create collection file.
  399. """
  400. dirname_ds = os.path.dirname(filename)
  401. if dirname_ds != '':
  402. dirname_ds += '/'
  403. if not os.path.exists(dirname_ds) :
  404. os.makedirs(dirname_ds)
  405. with open(filename + '.xml', 'w') as fgroup:
  406. fgroup.write("<?xml version=\"1.0\"?>")
  407. fgroup.write("\n<!DOCTYPE GraphCollection SYSTEM \"http://www.inf.unibz.it/~blumenthal/dtd/GraphCollection.dtd\">")
  408. fgroup.write("\n<GraphCollection>")
  409. for idx, fname in enumerate(Gn_names):
  410. fgroup.write("\n\t<graph file=\"" + fname + "\" class=\"" + str(y[idx]) + "\"/>")
  411. fgroup.write("\n</GraphCollection>")
  412. fgroup.close()
  413. tmp_dir = os.path.dirname(os.path.realpath(__file__)) + '/cpp_ext/output/tmp_ged/'
  414. fn_collection = tmp_dir + 'collection.' + str(time.time()) + str(random.randint(0, 1e9))
  415. createCollectionFile(Gn_names, ['dummy'] * len(Gn_names), fn_collection)
  416. # fn_collection = tmp_dir + 'collection_for_debug'
  417. # graph_dir = os.path.dirname(os.path.realpath(__file__)) + '/cpp_ext/generated_datsets/monoterpenoides/gxl'
  418. # if dataset == 'Letter-high' or dataset == 'Fingerprint':
  419. # dataset = 'letter'
  420. command = 'GEDLIB_HOME=\'/media/ljia/DATA/research-repo/codes/Linlin/gedlib\'\n'
  421. command += 'LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$GEDLIB_HOME/lib\n'
  422. command += 'export LD_LIBRARY_PATH\n'
  423. command += 'cd \'' + os.path.dirname(os.path.realpath(__file__)) + '/cpp_ext/bin\'\n'
  424. command += './iam_for_python_bash ' + dataset + ' ' + fn_collection \
  425. + ' \'' + graph_dir + '\' ' + ' ' + cost + ' ' + str(initial_solutions) + ' '
  426. if edit_cost_constant is None:
  427. command += 'None'
  428. else:
  429. for ec in edit_cost_constant:
  430. command += str(ec) + ' '
  431. # output = os.system(command)
  432. stream = os.popen(command)
  433. output = stream.readlines()
  434. # print(output)
  435. sod_sm = float(output[0].strip())
  436. sod_gm = float(output[1].strip())
  437. fname_sm = os.path.dirname(os.path.realpath(__file__)) + '/cpp_ext/output/tmp_ged/set_median.gxl'
  438. fname_gm = os.path.dirname(os.path.realpath(__file__)) + '/cpp_ext/output/tmp_ged/gen_median.gxl'
  439. return sod_sm, sod_gm, fname_sm, fname_gm
  440. ###############################################################################
  441. # Old implementations.
  442. def iam(Gn, c_ei=3, c_er=3, c_es=1, node_label='atom', edge_label='bond_type',
  443. connected=True):
  444. """See my name, then you know what I do.
  445. """
  446. # Gn = Gn[0:10]
  447. Gn = [nx.convert_node_labels_to_integers(g) for g in Gn]
  448. # phase 1: initilize.
  449. # compute set-median.
  450. dis_min = np.inf
  451. pi_p = []
  452. pi_all = []
  453. for idx1, G_p in enumerate(Gn):
  454. dist_sum = 0
  455. pi_all.append([])
  456. for idx2, G_p_prime in enumerate(Gn):
  457. dist_tmp, pi_tmp, _ = GED(G_p, G_p_prime)
  458. pi_all[idx1].append(pi_tmp)
  459. dist_sum += dist_tmp
  460. if dist_sum < dis_min:
  461. dis_min = dist_sum
  462. G = G_p.copy()
  463. idx_min = idx1
  464. # list of edit operations.
  465. pi_p = pi_all[idx_min]
  466. # phase 2: iteration.
  467. ds_attrs = get_dataset_attributes(Gn, attr_names=['edge_labeled', 'node_attr_dim'],
  468. edge_label=edge_label)
  469. for itr in range(0, 10): # @todo: the convergence condition?
  470. G_new = G.copy()
  471. # update vertex labels.
  472. # pre-compute h_i0 for each label.
  473. # for label in get_node_labels(Gn, node_label):
  474. # print(label)
  475. # for nd in G.nodes(data=True):
  476. # pass
  477. if not ds_attrs['node_attr_dim']: # labels are symbolic
  478. for nd, _ in G.nodes(data=True):
  479. h_i0_list = []
  480. label_list = []
  481. for label in get_node_labels(Gn, node_label):
  482. h_i0 = 0
  483. for idx, g in enumerate(Gn):
  484. pi_i = pi_p[idx][nd]
  485. if g.has_node(pi_i) and g.nodes[pi_i][node_label] == label:
  486. h_i0 += 1
  487. h_i0_list.append(h_i0)
  488. label_list.append(label)
  489. # choose one of the best randomly.
  490. idx_max = np.argwhere(h_i0_list == np.max(h_i0_list)).flatten().tolist()
  491. idx_rdm = random.randint(0, len(idx_max) - 1)
  492. G_new.nodes[nd][node_label] = label_list[idx_max[idx_rdm]]
  493. else: # labels are non-symbolic
  494. for nd, _ in G.nodes(data=True):
  495. Si_norm = 0
  496. phi_i_bar = np.array([0.0 for _ in range(ds_attrs['node_attr_dim'])])
  497. for idx, g in enumerate(Gn):
  498. pi_i = pi_p[idx][nd]
  499. if g.has_node(pi_i): #@todo: what if no g has node? phi_i_bar = 0?
  500. Si_norm += 1
  501. phi_i_bar += np.array([float(itm) for itm in g.nodes[pi_i]['attributes']])
  502. phi_i_bar /= Si_norm
  503. G_new.nodes[nd]['attributes'] = phi_i_bar
  504. # update edge labels and adjacency matrix.
  505. if ds_attrs['edge_labeled']:
  506. for nd1, nd2, _ in G.edges(data=True):
  507. h_ij0_list = []
  508. label_list = []
  509. for label in get_edge_labels(Gn, edge_label):
  510. h_ij0 = 0
  511. for idx, g in enumerate(Gn):
  512. pi_i = pi_p[idx][nd1]
  513. pi_j = pi_p[idx][nd2]
  514. h_ij0_p = (g.has_node(pi_i) and g.has_node(pi_j) and
  515. g.has_edge(pi_i, pi_j) and
  516. g.edges[pi_i, pi_j][edge_label] == label)
  517. h_ij0 += h_ij0_p
  518. h_ij0_list.append(h_ij0)
  519. label_list.append(label)
  520. # choose one of the best randomly.
  521. idx_max = np.argwhere(h_ij0_list == np.max(h_ij0_list)).flatten().tolist()
  522. h_ij0_max = h_ij0_list[idx_max[0]]
  523. idx_rdm = random.randint(0, len(idx_max) - 1)
  524. best_label = label_list[idx_max[idx_rdm]]
  525. # check whether a_ij is 0 or 1.
  526. sij_norm = 0
  527. for idx, g in enumerate(Gn):
  528. pi_i = pi_p[idx][nd1]
  529. pi_j = pi_p[idx][nd2]
  530. if g.has_node(pi_i) and g.has_node(pi_j) and g.has_edge(pi_i, pi_j):
  531. sij_norm += 1
  532. if h_ij0_max > len(Gn) * c_er / c_es + sij_norm * (1 - (c_er + c_ei) / c_es):
  533. if not G_new.has_edge(nd1, nd2):
  534. G_new.add_edge(nd1, nd2)
  535. G_new.edges[nd1, nd2][edge_label] = best_label
  536. else:
  537. if G_new.has_edge(nd1, nd2):
  538. G_new.remove_edge(nd1, nd2)
  539. else: # if edges are unlabeled
  540. for nd1, nd2, _ in G.edges(data=True):
  541. sij_norm = 0
  542. for idx, g in enumerate(Gn):
  543. pi_i = pi_p[idx][nd1]
  544. pi_j = pi_p[idx][nd2]
  545. if g.has_node(pi_i) and g.has_node(pi_j) and g.has_edge(pi_i, pi_j):
  546. sij_norm += 1
  547. if sij_norm > len(Gn) * c_er / (c_er + c_ei):
  548. if not G_new.has_edge(nd1, nd2):
  549. G_new.add_edge(nd1, nd2)
  550. else:
  551. if G_new.has_edge(nd1, nd2):
  552. G_new.remove_edge(nd1, nd2)
  553. G = G_new.copy()
  554. # update pi_p
  555. pi_p = []
  556. for idx1, G_p in enumerate(Gn):
  557. dist_tmp, pi_tmp, _ = GED(G, G_p)
  558. pi_p.append(pi_tmp)
  559. return G
  560. # --------------------------- These are tests --------------------------------#
  561. def test_iam_with_more_graphs_as_init(Gn, G_candidate, c_ei=3, c_er=3, c_es=1,
  562. node_label='atom', edge_label='bond_type'):
  563. """See my name, then you know what I do.
  564. """
  565. # Gn = Gn[0:10]
  566. Gn = [nx.convert_node_labels_to_integers(g) for g in Gn]
  567. # phase 1: initilize.
  568. # compute set-median.
  569. dis_min = np.inf
  570. # pi_p = []
  571. pi_all_forward = []
  572. pi_all_backward = []
  573. for idx1, G_p in tqdm(enumerate(G_candidate), desc='computing GEDs', file=sys.stdout):
  574. dist_sum = 0
  575. pi_all_forward.append([])
  576. pi_all_backward.append([])
  577. for idx2, G_p_prime in enumerate(Gn):
  578. dist_tmp, pi_tmp_forward, pi_tmp_backward = GED(G_p, G_p_prime)
  579. pi_all_forward[idx1].append(pi_tmp_forward)
  580. pi_all_backward[idx1].append(pi_tmp_backward)
  581. dist_sum += dist_tmp
  582. if dist_sum <= dis_min:
  583. dis_min = dist_sum
  584. G = G_p.copy()
  585. idx_min = idx1
  586. # list of edit operations.
  587. pi_p_forward = pi_all_forward[idx_min]
  588. pi_p_backward = pi_all_backward[idx_min]
  589. # phase 2: iteration.
  590. ds_attrs = get_dataset_attributes(Gn + [G], attr_names=['edge_labeled', 'node_attr_dim'],
  591. edge_label=edge_label)
  592. label_set = get_node_labels(Gn + [G], node_label)
  593. for itr in range(0, 10): # @todo: the convergence condition?
  594. G_new = G.copy()
  595. # update vertex labels.
  596. # pre-compute h_i0 for each label.
  597. # for label in get_node_labels(Gn, node_label):
  598. # print(label)
  599. # for nd in G.nodes(data=True):
  600. # pass
  601. if not ds_attrs['node_attr_dim']: # labels are symbolic
  602. for nd in G.nodes():
  603. h_i0_list = []
  604. label_list = []
  605. for label in label_set:
  606. h_i0 = 0
  607. for idx, g in enumerate(Gn):
  608. pi_i = pi_p_forward[idx][nd]
  609. if g.has_node(pi_i) and g.nodes[pi_i][node_label] == label:
  610. h_i0 += 1
  611. h_i0_list.append(h_i0)
  612. label_list.append(label)
  613. # choose one of the best randomly.
  614. idx_max = np.argwhere(h_i0_list == np.max(h_i0_list)).flatten().tolist()
  615. idx_rdm = random.randint(0, len(idx_max) - 1)
  616. G_new.nodes[nd][node_label] = label_list[idx_max[idx_rdm]]
  617. else: # labels are non-symbolic
  618. for nd in G.nodes():
  619. Si_norm = 0
  620. phi_i_bar = np.array([0.0 for _ in range(ds_attrs['node_attr_dim'])])
  621. for idx, g in enumerate(Gn):
  622. pi_i = pi_p_forward[idx][nd]
  623. if g.has_node(pi_i): #@todo: what if no g has node? phi_i_bar = 0?
  624. Si_norm += 1
  625. phi_i_bar += np.array([float(itm) for itm in g.nodes[pi_i]['attributes']])
  626. phi_i_bar /= Si_norm
  627. G_new.nodes[nd]['attributes'] = phi_i_bar
  628. # update edge labels and adjacency matrix.
  629. if ds_attrs['edge_labeled']:
  630. for nd1, nd2, _ in G.edges(data=True):
  631. h_ij0_list = []
  632. label_list = []
  633. for label in get_edge_labels(Gn, edge_label):
  634. h_ij0 = 0
  635. for idx, g in enumerate(Gn):
  636. pi_i = pi_p_forward[idx][nd1]
  637. pi_j = pi_p_forward[idx][nd2]
  638. h_ij0_p = (g.has_node(pi_i) and g.has_node(pi_j) and
  639. g.has_edge(pi_i, pi_j) and
  640. g.edges[pi_i, pi_j][edge_label] == label)
  641. h_ij0 += h_ij0_p
  642. h_ij0_list.append(h_ij0)
  643. label_list.append(label)
  644. # choose one of the best randomly.
  645. idx_max = np.argwhere(h_ij0_list == np.max(h_ij0_list)).flatten().tolist()
  646. h_ij0_max = h_ij0_list[idx_max[0]]
  647. idx_rdm = random.randint(0, len(idx_max) - 1)
  648. best_label = label_list[idx_max[idx_rdm]]
  649. # check whether a_ij is 0 or 1.
  650. sij_norm = 0
  651. for idx, g in enumerate(Gn):
  652. pi_i = pi_p_forward[idx][nd1]
  653. pi_j = pi_p_forward[idx][nd2]
  654. if g.has_node(pi_i) and g.has_node(pi_j) and g.has_edge(pi_i, pi_j):
  655. sij_norm += 1
  656. if h_ij0_max > len(Gn) * c_er / c_es + sij_norm * (1 - (c_er + c_ei) / c_es):
  657. if not G_new.has_edge(nd1, nd2):
  658. G_new.add_edge(nd1, nd2)
  659. G_new.edges[nd1, nd2][edge_label] = best_label
  660. else:
  661. if G_new.has_edge(nd1, nd2):
  662. G_new.remove_edge(nd1, nd2)
  663. else: # if edges are unlabeled
  664. # @todo: works only for undirected graphs.
  665. for nd1 in range(nx.number_of_nodes(G)):
  666. for nd2 in range(nd1 + 1, nx.number_of_nodes(G)):
  667. sij_norm = 0
  668. for idx, g in enumerate(Gn):
  669. pi_i = pi_p_forward[idx][nd1]
  670. pi_j = pi_p_forward[idx][nd2]
  671. if g.has_node(pi_i) and g.has_node(pi_j) and g.has_edge(pi_i, pi_j):
  672. sij_norm += 1
  673. if sij_norm > len(Gn) * c_er / (c_er + c_ei):
  674. if not G_new.has_edge(nd1, nd2):
  675. G_new.add_edge(nd1, nd2)
  676. elif sij_norm < len(Gn) * c_er / (c_er + c_ei):
  677. if G_new.has_edge(nd1, nd2):
  678. G_new.remove_edge(nd1, nd2)
  679. # do not change anything when equal.
  680. G = G_new.copy()
  681. # update pi_p
  682. pi_p_forward = []
  683. for G_p in Gn:
  684. dist_tmp, pi_tmp_forward, pi_tmp_backward = GED(G, G_p)
  685. pi_p_forward.append(pi_tmp_forward)
  686. return G
  687. ###############################################################################
  688. if __name__ == '__main__':
  689. from gklearn.utils.graphfiles import loadDataset
  690. ds = {'name': 'MUTAG', 'dataset': '../datasets/MUTAG/MUTAG.mat',
  691. 'extra_params': {'am_sp_al_nl_el': [0, 0, 3, 1, 2]}} # node/edge symb
  692. # ds = {'name': 'Letter-high', 'dataset': '../datasets/Letter-high/Letter-high_A.txt',
  693. # 'extra_params': {}} # node nsymb
  694. # ds = {'name': 'Acyclic', 'dataset': '../datasets/monoterpenoides/trainset_9.ds',
  695. # 'extra_params': {}}
  696. Gn, y_all = loadDataset(ds['dataset'], extra_params=ds['extra_params'])
  697. iam(Gn)

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