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

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

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