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.

ged.py 18 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. Created on Thu Oct 17 18:44:59 2019
  5. @author: ljia
  6. """
  7. import numpy as np
  8. import networkx as nx
  9. from tqdm import tqdm
  10. import sys
  11. import multiprocessing
  12. from multiprocessing import Pool
  13. from functools import partial
  14. #from gedlibpy_linlin import librariesImport, gedlibpy
  15. from libs import *
  16. def GED(g1, g2, dataset='monoterpenoides', lib='gedlibpy', cost='CHEM_1', method='IPFP',
  17. edit_cost_constant=[], algo_options='', stabilizer='min', repeat=50):
  18. """
  19. Compute GED for 2 graphs.
  20. """
  21. def convertGraph(G, cost):
  22. """Convert a graph to the proper NetworkX format that can be
  23. recognized by library gedlibpy.
  24. """
  25. G_new = nx.Graph()
  26. if cost == 'LETTER' or cost == 'LETTER2':
  27. for nd, attrs in G.nodes(data=True):
  28. G_new.add_node(str(nd), x=str(attrs['attributes'][0]),
  29. y=str(attrs['attributes'][1]))
  30. for nd1, nd2, attrs in G.edges(data=True):
  31. G_new.add_edge(str(nd1), str(nd2))
  32. elif cost == 'NON_SYMBOLIC':
  33. for nd, attrs in G.nodes(data=True):
  34. G_new.add_node(str(nd))
  35. for a_name in G.graph['node_attrs']:
  36. G_new.nodes[str(nd)][a_name] = str(attrs[a_name])
  37. for nd1, nd2, attrs in G.edges(data=True):
  38. G_new.add_edge(str(nd1), str(nd2))
  39. for a_name in G.graph['edge_attrs']:
  40. G_new.edges[str(nd1), str(nd2)][a_name] = str(attrs[a_name])
  41. else:
  42. for nd, attrs in G.nodes(data=True):
  43. G_new.add_node(str(nd), chem=attrs['atom'])
  44. for nd1, nd2, attrs in G.edges(data=True):
  45. G_new.add_edge(str(nd1), str(nd2), valence=attrs['bond_type'])
  46. # G_new.add_edge(str(nd1), str(nd2))
  47. return G_new
  48. # dataset = dataset.lower()
  49. if lib == 'gedlibpy':
  50. gedlibpy.restart_env()
  51. gedlibpy.add_nx_graph(convertGraph(g1, cost), "")
  52. gedlibpy.add_nx_graph(convertGraph(g2, cost), "")
  53. listID = gedlibpy.get_all_graph_ids()
  54. gedlibpy.set_edit_cost(cost, edit_cost_constant=edit_cost_constant)
  55. gedlibpy.init()
  56. gedlibpy.set_method(method, algo_options)
  57. gedlibpy.init_method()
  58. g = listID[0]
  59. h = listID[1]
  60. if stabilizer is None:
  61. gedlibpy.run_method(g, h)
  62. pi_forward = gedlibpy.get_forward_map(g, h)
  63. pi_backward = gedlibpy.get_backward_map(g, h)
  64. upper = gedlibpy.get_upper_bound(g, h)
  65. lower = gedlibpy.get_lower_bound(g, h)
  66. elif stabilizer == 'mean':
  67. # @todo: to be finished...
  68. upper_list = [np.inf] * repeat
  69. for itr in range(repeat):
  70. gedlibpy.run_method(g, h)
  71. upper_list[itr] = gedlibpy.get_upper_bound(g, h)
  72. pi_forward = gedlibpy.get_forward_map(g, h)
  73. pi_backward = gedlibpy.get_backward_map(g, h)
  74. lower = gedlibpy.get_lower_bound(g, h)
  75. upper = np.mean(upper_list)
  76. elif stabilizer == 'median':
  77. if repeat % 2 == 0:
  78. repeat += 1
  79. upper_list = [np.inf] * repeat
  80. pi_forward_list = [0] * repeat
  81. pi_backward_list = [0] * repeat
  82. for itr in range(repeat):
  83. gedlibpy.run_method(g, h)
  84. upper_list[itr] = gedlibpy.get_upper_bound(g, h)
  85. pi_forward_list[itr] = gedlibpy.get_forward_map(g, h)
  86. pi_backward_list[itr] = gedlibpy.get_backward_map(g, h)
  87. lower = gedlibpy.get_lower_bound(g, h)
  88. upper = np.median(upper_list)
  89. idx_median = upper_list.index(upper)
  90. pi_forward = pi_forward_list[idx_median]
  91. pi_backward = pi_backward_list[idx_median]
  92. elif stabilizer == 'min':
  93. upper = np.inf
  94. for itr in range(repeat):
  95. gedlibpy.run_method(g, h)
  96. upper_tmp = gedlibpy.get_upper_bound(g, h)
  97. if upper_tmp < upper:
  98. upper = upper_tmp
  99. pi_forward = gedlibpy.get_forward_map(g, h)
  100. pi_backward = gedlibpy.get_backward_map(g, h)
  101. lower = gedlibpy.get_lower_bound(g, h)
  102. if upper == 0:
  103. break
  104. elif stabilizer == 'max':
  105. upper = 0
  106. for itr in range(repeat):
  107. gedlibpy.run_method(g, h)
  108. upper_tmp = gedlibpy.get_upper_bound(g, h)
  109. if upper_tmp > upper:
  110. upper = upper_tmp
  111. pi_forward = gedlibpy.get_forward_map(g, h)
  112. pi_backward = gedlibpy.get_backward_map(g, h)
  113. lower = gedlibpy.get_lower_bound(g, h)
  114. elif stabilizer == 'gaussian':
  115. pass
  116. dis = upper
  117. elif lib == 'gedlib-bash':
  118. import time
  119. import random
  120. import os
  121. from gklearn.utils.graphfiles import saveDataset
  122. tmp_dir = os.path.dirname(os.path.realpath(__file__)) + '/cpp_ext/output/tmp_ged/'
  123. if not os.path.exists(tmp_dir):
  124. os.makedirs(tmp_dir)
  125. fn_collection = tmp_dir + 'collection.' + str(time.time()) + str(random.randint(0, 1e9))
  126. xparams = {'method': 'gedlib', 'graph_dir': fn_collection}
  127. saveDataset([g1, g2], ['dummy', 'dummy'], gformat='gxl', group='xml',
  128. filename=fn_collection, xparams=xparams)
  129. command = 'GEDLIB_HOME=\'/media/ljia/DATA/research-repo/codes/others/gedlib/gedlib2\'\n'
  130. command += 'LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$GEDLIB_HOME/lib\n'
  131. command += 'export LD_LIBRARY_PATH\n'
  132. command += 'cd \'' + os.path.dirname(os.path.realpath(__file__)) + '/cpp_ext/bin\'\n'
  133. command += './ged_for_python_bash monoterpenoides ' + fn_collection \
  134. + ' \'' + algo_options + '\' '
  135. for ec in edit_cost_constant:
  136. command += str(ec) + ' '
  137. # output = os.system(command)
  138. stream = os.popen(command)
  139. output = stream.readlines()
  140. # print(output)
  141. dis = float(output[0].strip())
  142. runtime = float(output[1].strip())
  143. size_forward = int(output[2].strip())
  144. pi_forward = [int(item.strip()) for item in output[3:3+size_forward]]
  145. pi_backward = [int(item.strip()) for item in output[3+size_forward:]]
  146. # print(dis)
  147. # print(runtime)
  148. # print(size_forward)
  149. # print(pi_forward)
  150. # print(pi_backward)
  151. # make the map label correct (label remove map as np.inf)
  152. nodes1 = [n for n in g1.nodes()]
  153. nodes2 = [n for n in g2.nodes()]
  154. nb1 = nx.number_of_nodes(g1)
  155. nb2 = nx.number_of_nodes(g2)
  156. pi_forward = [nodes2[pi] if pi < nb2 else np.inf for pi in pi_forward]
  157. pi_backward = [nodes1[pi] if pi < nb1 else np.inf for pi in pi_backward]
  158. # print(pi_forward)
  159. return dis, pi_forward, pi_backward
  160. def GED_n(Gn, lib='gedlibpy', cost='CHEM_1', method='IPFP',
  161. edit_cost_constant=[], stabilizer='min', repeat=50):
  162. """
  163. Compute GEDs for a group of graphs.
  164. """
  165. if lib == 'gedlibpy':
  166. def convertGraph(G):
  167. """Convert a graph to the proper NetworkX format that can be
  168. recognized by library gedlibpy.
  169. """
  170. G_new = nx.Graph()
  171. for nd, attrs in G.nodes(data=True):
  172. G_new.add_node(str(nd), chem=attrs['atom'])
  173. for nd1, nd2, attrs in G.edges(data=True):
  174. # G_new.add_edge(str(nd1), str(nd2), valence=attrs['bond_type'])
  175. G_new.add_edge(str(nd1), str(nd2))
  176. return G_new
  177. gedlibpy.restart_env()
  178. gedlibpy.add_nx_graph(convertGraph(g1), "")
  179. gedlibpy.add_nx_graph(convertGraph(g2), "")
  180. listID = gedlibpy.get_all_graph_ids()
  181. gedlibpy.set_edit_cost(cost, edit_cost_constant=edit_cost_constant)
  182. gedlibpy.init()
  183. gedlibpy.set_method(method, "")
  184. gedlibpy.init_method()
  185. g = listID[0]
  186. h = listID[1]
  187. if stabilizer is None:
  188. gedlibpy.run_method(g, h)
  189. pi_forward = gedlibpy.get_forward_map(g, h)
  190. pi_backward = gedlibpy.get_backward_map(g, h)
  191. upper = gedlibpy.get_upper_bound(g, h)
  192. lower = gedlibpy.get_lower_bound(g, h)
  193. elif stabilizer == 'min':
  194. upper = np.inf
  195. for itr in range(repeat):
  196. gedlibpy.run_method(g, h)
  197. upper_tmp = gedlibpy.get_upper_bound(g, h)
  198. if upper_tmp < upper:
  199. upper = upper_tmp
  200. pi_forward = gedlibpy.get_forward_map(g, h)
  201. pi_backward = gedlibpy.get_backward_map(g, h)
  202. lower = gedlibpy.get_lower_bound(g, h)
  203. if upper == 0:
  204. break
  205. dis = upper
  206. # make the map label correct (label remove map as np.inf)
  207. nodes1 = [n for n in g1.nodes()]
  208. nodes2 = [n for n in g2.nodes()]
  209. nb1 = nx.number_of_nodes(g1)
  210. nb2 = nx.number_of_nodes(g2)
  211. pi_forward = [nodes2[pi] if pi < nb2 else np.inf for pi in pi_forward]
  212. pi_backward = [nodes1[pi] if pi < nb1 else np.inf for pi in pi_backward]
  213. return dis, pi_forward, pi_backward
  214. def ged_median(Gn, Gn_median, verbose=False, params_ged={'lib': 'gedlibpy',
  215. 'cost': 'CHEM_1', 'method': 'IPFP', 'edit_cost_constant': [],
  216. 'algo_options': '--threads 8 --initial-solutions 40 --ratio-runs-from-initial-solutions 1',
  217. 'stabilizer': None}, parallel=False):
  218. if parallel:
  219. len_itr = int(len(Gn))
  220. pi_forward_list = [[] for i in range(len_itr)]
  221. dis_list = [0 for i in range(len_itr)]
  222. itr = range(0, len_itr)
  223. n_jobs = multiprocessing.cpu_count()
  224. if len_itr < 100 * n_jobs:
  225. chunksize = int(len_itr / n_jobs) + 1
  226. else:
  227. chunksize = 100
  228. def init_worker(gn_toshare, gn_median_toshare):
  229. global G_gn, G_gn_median
  230. G_gn = gn_toshare
  231. G_gn_median = gn_median_toshare
  232. do_partial = partial(_compute_ged_median, params_ged)
  233. pool = Pool(processes=n_jobs, initializer=init_worker, initargs=(Gn, Gn_median))
  234. if verbose:
  235. iterator = tqdm(pool.imap_unordered(do_partial, itr, chunksize),
  236. desc='computing GEDs', file=sys.stdout)
  237. else:
  238. iterator = pool.imap_unordered(do_partial, itr, chunksize)
  239. for i, dis_sum, pi_forward in iterator:
  240. pi_forward_list[i] = pi_forward
  241. dis_list[i] = dis_sum
  242. # print('\n-------------------------------------------')
  243. # print(i, j, idx_itr, dis)
  244. pool.close()
  245. pool.join()
  246. else:
  247. dis_list = []
  248. pi_forward_list = []
  249. for idx, G in tqdm(enumerate(Gn), desc='computing median distances',
  250. file=sys.stdout) if verbose else enumerate(Gn):
  251. dis_sum = 0
  252. pi_forward_list.append([])
  253. for G_p in Gn_median:
  254. dis_tmp, pi_tmp_forward, pi_tmp_backward = GED(G, G_p,
  255. **params_ged)
  256. pi_forward_list[idx].append(pi_tmp_forward)
  257. dis_sum += dis_tmp
  258. dis_list.append(dis_sum)
  259. return dis_list, pi_forward_list
  260. def _compute_ged_median(params_ged, itr):
  261. # print(itr)
  262. dis_sum = 0
  263. pi_forward = []
  264. for G_p in G_gn_median:
  265. dis_tmp, pi_tmp_forward, pi_tmp_backward = GED(G_gn[itr], G_p,
  266. **params_ged)
  267. pi_forward.append(pi_tmp_forward)
  268. dis_sum += dis_tmp
  269. return itr, dis_sum, pi_forward
  270. def get_nb_edit_operations(g1, g2, forward_map, backward_map):
  271. """Compute the number of each edit operations.
  272. """
  273. n_vi = 0
  274. n_vr = 0
  275. n_vs = 0
  276. n_ei = 0
  277. n_er = 0
  278. n_es = 0
  279. nodes1 = [n for n in g1.nodes()]
  280. for i, map_i in enumerate(forward_map):
  281. if map_i == np.inf:
  282. n_vr += 1
  283. elif g1.node[nodes1[i]]['atom'] != g2.node[map_i]['atom']:
  284. n_vs += 1
  285. for map_i in backward_map:
  286. if map_i == np.inf:
  287. n_vi += 1
  288. # idx_nodes1 = range(0, len(node1))
  289. edges1 = [e for e in g1.edges()]
  290. nb_edges2_cnted = 0
  291. for n1, n2 in edges1:
  292. idx1 = nodes1.index(n1)
  293. idx2 = nodes1.index(n2)
  294. # one of the nodes is removed, thus the edge is removed.
  295. if forward_map[idx1] == np.inf or forward_map[idx2] == np.inf:
  296. n_er += 1
  297. # corresponding edge is in g2.
  298. elif (forward_map[idx1], forward_map[idx2]) in g2.edges():
  299. nb_edges2_cnted += 1
  300. # edge labels are different.
  301. if g2.edges[((forward_map[idx1], forward_map[idx2]))]['bond_type'] \
  302. != g1.edges[(n1, n2)]['bond_type']:
  303. n_es += 1
  304. elif (forward_map[idx2], forward_map[idx1]) in g2.edges():
  305. nb_edges2_cnted += 1
  306. # edge labels are different.
  307. if g2.edges[((forward_map[idx2], forward_map[idx1]))]['bond_type'] \
  308. != g1.edges[(n1, n2)]['bond_type']:
  309. n_es += 1
  310. # corresponding nodes are in g2, however the edge is removed.
  311. else:
  312. n_er += 1
  313. n_ei = nx.number_of_edges(g2) - nb_edges2_cnted
  314. return n_vi, n_vr, n_vs, n_ei, n_er, n_es
  315. def get_nb_edit_operations_letter(g1, g2, forward_map, backward_map):
  316. """Compute the number of each edit operations.
  317. """
  318. n_vi = 0
  319. n_vr = 0
  320. n_vs = 0
  321. sod_vs = 0
  322. n_ei = 0
  323. n_er = 0
  324. nodes1 = [n for n in g1.nodes()]
  325. for i, map_i in enumerate(forward_map):
  326. if map_i == np.inf:
  327. n_vr += 1
  328. else:
  329. n_vs += 1
  330. diff_x = float(g1.nodes[nodes1[i]]['x']) - float(g2.nodes[map_i]['x'])
  331. diff_y = float(g1.nodes[nodes1[i]]['y']) - float(g2.nodes[map_i]['y'])
  332. sod_vs += np.sqrt(np.square(diff_x) + np.square(diff_y))
  333. for map_i in backward_map:
  334. if map_i == np.inf:
  335. n_vi += 1
  336. # idx_nodes1 = range(0, len(node1))
  337. edges1 = [e for e in g1.edges()]
  338. nb_edges2_cnted = 0
  339. for n1, n2 in edges1:
  340. idx1 = nodes1.index(n1)
  341. idx2 = nodes1.index(n2)
  342. # one of the nodes is removed, thus the edge is removed.
  343. if forward_map[idx1] == np.inf or forward_map[idx2] == np.inf:
  344. n_er += 1
  345. # corresponding edge is in g2. Edge label is not considered.
  346. elif (forward_map[idx1], forward_map[idx2]) in g2.edges() or \
  347. (forward_map[idx2], forward_map[idx1]) in g2.edges():
  348. nb_edges2_cnted += 1
  349. # corresponding nodes are in g2, however the edge is removed.
  350. else:
  351. n_er += 1
  352. n_ei = nx.number_of_edges(g2) - nb_edges2_cnted
  353. return n_vi, n_vr, n_vs, sod_vs, n_ei, n_er
  354. def get_nb_edit_operations_nonsymbolic(g1, g2, forward_map, backward_map):
  355. """Compute the number of each edit operations.
  356. """
  357. n_vi = 0
  358. n_vr = 0
  359. n_vs = 0
  360. sod_vs = 0
  361. n_ei = 0
  362. n_er = 0
  363. n_es = 0
  364. sod_es = 0
  365. nodes1 = [n for n in g1.nodes()]
  366. for i, map_i in enumerate(forward_map):
  367. if map_i == np.inf:
  368. n_vr += 1
  369. else:
  370. n_vs += 1
  371. sum_squares = 0
  372. for a_name in g1.graph['node_attrs']:
  373. diff = float(g1.nodes[nodes1[i]][a_name]) - float(g2.nodes[map_i][a_name])
  374. sum_squares += np.square(diff)
  375. sod_vs += np.sqrt(sum_squares)
  376. for map_i in backward_map:
  377. if map_i == np.inf:
  378. n_vi += 1
  379. # idx_nodes1 = range(0, len(node1))
  380. edges1 = [e for e in g1.edges()]
  381. for n1, n2 in edges1:
  382. idx1 = nodes1.index(n1)
  383. idx2 = nodes1.index(n2)
  384. n1_g2 = forward_map[idx1]
  385. n2_g2 = forward_map[idx2]
  386. # one of the nodes is removed, thus the edge is removed.
  387. if n1_g2 == np.inf or n2_g2 == np.inf:
  388. n_er += 1
  389. # corresponding edge is in g2.
  390. elif (n1_g2, n2_g2) in g2.edges():
  391. n_es += 1
  392. sum_squares = 0
  393. for a_name in g1.graph['edge_attrs']:
  394. diff = float(g1.edges[n1, n2][a_name]) - float(g2.nodes[n1_g2, n2_g2][a_name])
  395. sum_squares += np.square(diff)
  396. sod_es += np.sqrt(sum_squares)
  397. elif (n2_g2, n1_g2) in g2.edges():
  398. n_es += 1
  399. sum_squares = 0
  400. for a_name in g1.graph['edge_attrs']:
  401. diff = float(g1.edges[n2, n1][a_name]) - float(g2.nodes[n2_g2, n1_g2][a_name])
  402. sum_squares += np.square(diff)
  403. sod_es += np.sqrt(sum_squares)
  404. # corresponding nodes are in g2, however the edge is removed.
  405. else:
  406. n_er += 1
  407. n_ei = nx.number_of_edges(g2) - n_es
  408. return n_vi, n_vr, sod_vs, n_ei, n_er, sod_es
  409. if __name__ == '__main__':
  410. print('check test_ged.py')

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