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.

untilHPathKernel.py 23 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  1. """
  2. @author: linlin
  3. @references: Liva Ralaivola, Sanjay J Swamidass, Hiroto Saigo, and Pierre
  4. Baldi. Graph kernels for chemical informatics. Neural networks,
  5. 18(8):1093–1110, 2005.
  6. """
  7. import sys
  8. sys.path.insert(0, "../")
  9. import time
  10. from collections import Counter
  11. from itertools import chain
  12. from functools import partial
  13. from multiprocessing import Pool
  14. from tqdm import tqdm
  15. import networkx as nx
  16. import numpy as np
  17. from pygraph.utils.graphdataset import get_dataset_attributes
  18. from pygraph.utils.parallel import parallel_gm
  19. from pygraph.utils.trie import Trie
  20. def untilhpathkernel(*args,
  21. node_label='atom',
  22. edge_label='bond_type',
  23. depth=10,
  24. k_func='tanimoto',
  25. compute_method='trie',
  26. n_jobs=None):
  27. """Calculate path graph kernels up to depth/hight h between graphs.
  28. Parameters
  29. ----------
  30. Gn : List of NetworkX graph
  31. List of graphs between which the kernels are calculated.
  32. /
  33. G1, G2 : NetworkX graphs
  34. 2 graphs between which the kernel is calculated.
  35. node_label : string
  36. Node attribute used as label. The default node label is atom.
  37. edge_label : string
  38. Edge attribute used as label. The default edge label is bond_type.
  39. depth : integer
  40. Depth of search. Longest length of paths.
  41. k_func : function
  42. A kernel function applied using different notions of fingerprint
  43. similarity.
  44. compute_method: string
  45. Computation method, 'trie' or 'naive'.
  46. Return
  47. ------
  48. Kmatrix : Numpy matrix
  49. Kernel matrix, each element of which is the path kernel up to h between
  50. 2 praphs.
  51. """
  52. # pre-process
  53. depth = int(depth)
  54. Gn = args[0] if len(args) == 1 else [args[0], args[1]]
  55. Kmatrix = np.zeros((len(Gn), len(Gn)))
  56. ds_attrs = get_dataset_attributes(
  57. Gn,
  58. attr_names=['node_labeled', 'edge_labeled', 'is_directed'],
  59. node_label=node_label, edge_label=edge_label)
  60. if not ds_attrs['node_labeled']:
  61. for G in Gn:
  62. nx.set_node_attributes(G, '0', 'atom')
  63. if not ds_attrs['edge_labeled']:
  64. for G in Gn:
  65. nx.set_edge_attributes(G, '0', 'bond_type')
  66. start_time = time.time()
  67. # ---- use pool.imap_unordered to parallel and track progress. ----
  68. # get all paths of all graphs before calculating kernels to save time,
  69. # but this may cost a lot of memory for large datasets.
  70. pool = Pool(n_jobs)
  71. itr = zip(Gn, range(0, len(Gn)))
  72. if len(Gn) < 100 * n_jobs:
  73. chunksize = int(len(Gn) / n_jobs) + 1
  74. else:
  75. chunksize = 100
  76. all_paths = [[] for _ in range(len(Gn))]
  77. if compute_method == 'trie':
  78. getps_partial = partial(wrapper_find_all_path_as_trie, depth,
  79. ds_attrs, node_label, edge_label)
  80. else:
  81. getps_partial = partial(wrapper_find_all_paths_until_length, depth,
  82. ds_attrs, node_label, edge_label)
  83. for i, ps in tqdm(
  84. pool.imap_unordered(getps_partial, itr, chunksize),
  85. desc='getting paths', file=sys.stdout):
  86. all_paths[i] = ps
  87. pool.close()
  88. pool.join()
  89. # for g in Gn:
  90. # if compute_method == 'trie':
  91. # find_all_path_as_trie(g, depth, ds_attrs, node_label, edge_label)
  92. # else:
  93. # find_all_paths_until_length(g, depth, ds_attrs, node_label, edge_label)
  94. ## size = sys.getsizeof(all_paths)
  95. ## for item in all_paths:
  96. ## size += sys.getsizeof(item)
  97. ## for pppps in item:
  98. ## size += sys.getsizeof(pppps)
  99. ## print(size)
  100. #
  101. ## ttt = time.time()
  102. ## # ---- ---- use pool.map to parallel ----
  103. ## for i, ps in tqdm(
  104. ## pool.map(getps_partial, range(0, len(Gn))),
  105. ## desc='getting paths', file=sys.stdout):
  106. ## all_paths[i] = ps
  107. ## print(time.time() - ttt)
  108. if compute_method == 'trie':
  109. def init_worker(trie_toshare):
  110. global G_trie
  111. G_trie = trie_toshare
  112. do_partial = partial(wrapper_uhpath_do_trie, k_func)
  113. parallel_gm(do_partial, Kmatrix, Gn, init_worker=init_worker,
  114. glbv=(all_paths,), n_jobs=n_jobs)
  115. else:
  116. def init_worker(plist_toshare):
  117. global G_plist
  118. G_plist = plist_toshare
  119. do_partial = partial(wrapper_uhpath_do_naive, k_func)
  120. parallel_gm(do_partial, Kmatrix, Gn, init_worker=init_worker,
  121. glbv=(all_paths,), n_jobs=n_jobs)
  122. # # ---- direct running, normally use single CPU core. ----
  123. # all_paths = [
  124. # find_all_paths_until_length(
  125. # Gn[i],
  126. # depth,
  127. # ds_attrs,
  128. # node_label=node_label,
  129. # edge_label=edge_label) for i in tqdm(
  130. # range(0, len(Gn)), desc='getting paths', file=sys.stdout)
  131. # ]
  132. #
  133. # if compute_method == 'trie':
  134. # pbar = tqdm(
  135. # total=((len(Gn) + 1) * len(Gn) / 2),
  136. # desc='calculating kernels',
  137. # file=sys.stdout)
  138. # for i in range(0, len(Gn)):
  139. # for j in range(i, len(Gn)):
  140. # Kmatrix[i][j] = _untilhpathkernel_do_trie(all_paths[i],
  141. # all_paths[j], k_func)
  142. # Kmatrix[j][i] = Kmatrix[i][j]
  143. # pbar.update(1)
  144. # else:
  145. # pbar = tqdm(
  146. # total=((len(Gn) + 1) * len(Gn) / 2),
  147. # desc='calculating kernels',
  148. # file=sys.stdout)
  149. # for i in range(0, len(Gn)):
  150. # for j in range(i, len(Gn)):
  151. # Kmatrix[i][j] = _untilhpathkernel_do_naive(all_paths[i], all_paths[j],
  152. # k_func)
  153. # Kmatrix[j][i] = Kmatrix[i][j]
  154. # pbar.update(1)
  155. run_time = time.time() - start_time
  156. print(
  157. "\n --- kernel matrix of path kernel up to %d of size %d built in %s seconds ---"
  158. % (depth, len(Gn), run_time))
  159. # print(Kmatrix[0][0:10])
  160. return Kmatrix, run_time
  161. def _untilhpathkernel_do_trie(trie1, trie2, k_func):
  162. """Calculate path graph kernels up to depth d between 2 graphs using trie.
  163. Parameters
  164. ----------
  165. trie1, trie2 : list
  166. Tries that contains all paths in 2 graphs.
  167. k_func : function
  168. A kernel function applied using different notions of fingerprint
  169. similarity.
  170. Return
  171. ------
  172. kernel : float
  173. Path kernel up to h between 2 graphs.
  174. """
  175. if k_func == 'tanimoto':
  176. # traverse all paths in graph1 and search them in graph2. Deep-first
  177. # search is applied.
  178. def traverseTrie1t(root, trie2, setlist, pcurrent=[]):
  179. for key, node in root['children'].items():
  180. pcurrent.append(key)
  181. if node['isEndOfWord']:
  182. setlist[1] += 1
  183. count2 = trie2.searchWord(pcurrent)
  184. if count2 != 0:
  185. setlist[0] += 1
  186. if node['children'] != {}:
  187. traverseTrie1t(node, trie2, setlist, pcurrent)
  188. else:
  189. del pcurrent[-1]
  190. if pcurrent != []:
  191. del pcurrent[-1]
  192. # traverse all paths in graph2 and find out those that are not in
  193. # graph1. Deep-first search is applied.
  194. def traverseTrie2t(root, trie1, setlist, pcurrent=[]):
  195. for key, node in root['children'].items():
  196. pcurrent.append(key)
  197. if node['isEndOfWord']:
  198. # print(node['count'])
  199. count1 = trie1.searchWord(pcurrent)
  200. if count1 == 0:
  201. setlist[1] += 1
  202. if node['children'] != {}:
  203. traverseTrie2t(node, trie1, setlist, pcurrent)
  204. else:
  205. del pcurrent[-1]
  206. if pcurrent != []:
  207. del pcurrent[-1]
  208. setlist = [0, 0] # intersection and union of path sets of g1, g2.
  209. # print(trie1.root)
  210. # print(trie2.root)
  211. traverseTrie1t(trie1.root, trie2, setlist)
  212. # print(setlist)
  213. traverseTrie2t(trie2.root, trie1, setlist)
  214. # print(setlist)
  215. kernel = setlist[0] / setlist[1]
  216. else: # MinMax kernel
  217. # traverse all paths in graph1 and search them in graph2. Deep-first
  218. # search is applied.
  219. def traverseTrie1m(root, trie2, sumlist, pcurrent=[]):
  220. for key, node in root['children'].items():
  221. pcurrent.append(key)
  222. if node['isEndOfWord']:
  223. # print(node['count'])
  224. count1 = node['count']
  225. count2 = trie2.searchWord(pcurrent)
  226. sumlist[0] += min(count1, count2)
  227. sumlist[1] += max(count1, count2)
  228. if node['children'] != {}:
  229. traverseTrie1m(node, trie2, sumlist, pcurrent)
  230. else:
  231. del pcurrent[-1]
  232. if pcurrent != []:
  233. del pcurrent[-1]
  234. # traverse all paths in graph2 and find out those that are not in
  235. # graph1. Deep-first search is applied.
  236. def traverseTrie2m(root, trie1, sumlist, pcurrent=[]):
  237. for key, node in root['children'].items():
  238. pcurrent.append(key)
  239. if node['isEndOfWord']:
  240. # print(node['count'])
  241. count1 = trie1.searchWord(pcurrent)
  242. if count1 == 0:
  243. sumlist[1] += node['count']
  244. if node['children'] != {}:
  245. traverseTrie2m(node, trie1, sumlist, pcurrent)
  246. else:
  247. del pcurrent[-1]
  248. if pcurrent != []:
  249. del pcurrent[-1]
  250. sumlist = [0, 0] # sum of mins and sum of maxs
  251. # print(trie1.root)
  252. # print(trie2.root)
  253. traverseTrie1m(trie1.root, trie2, sumlist)
  254. # print(sumlist)
  255. traverseTrie2m(trie2.root, trie1, sumlist)
  256. # print(sumlist)
  257. kernel = sumlist[0] / sumlist[1]
  258. return kernel
  259. def wrapper_uhpath_do_trie(k_func, itr):
  260. i = itr[0]
  261. j = itr[1]
  262. return i, j, _untilhpathkernel_do_trie(G_trie[i], G_trie[j], k_func)
  263. def _untilhpathkernel_do_naive(paths1, paths2, k_func):
  264. """Calculate path graph kernels up to depth d between 2 graphs naively.
  265. Parameters
  266. ----------
  267. paths_list : list of list
  268. List of list of paths in all graphs, where for unlabeled graphs, each
  269. path is represented by a list of nodes; while for labeled graphs, each
  270. path is represented by a string consists of labels of nodes and/or
  271. edges on that path.
  272. k_func : function
  273. A kernel function applied using different notions of fingerprint
  274. similarity.
  275. Return
  276. ------
  277. kernel : float
  278. Path kernel up to h between 2 graphs.
  279. """
  280. all_paths = list(set(paths1 + paths2))
  281. if k_func == 'tanimoto':
  282. length_union = len(set(paths1 + paths2))
  283. kernel = (len(set(paths1)) + len(set(paths2)) -
  284. length_union) / length_union
  285. # vector1 = [(1 if path in paths1 else 0) for path in all_paths]
  286. # vector2 = [(1 if path in paths2 else 0) for path in all_paths]
  287. # kernel_uv = np.dot(vector1, vector2)
  288. # kernel = kernel_uv / (len(set(paths1)) + len(set(paths2)) - kernel_uv)
  289. else: # MinMax kernel
  290. path_count1 = Counter(paths1)
  291. path_count2 = Counter(paths2)
  292. vector1 = [(path_count1[key] if (key in path_count1.keys()) else 0)
  293. for key in all_paths]
  294. vector2 = [(path_count2[key] if (key in path_count2.keys()) else 0)
  295. for key in all_paths]
  296. kernel = np.sum(np.minimum(vector1, vector2)) / \
  297. np.sum(np.maximum(vector1, vector2))
  298. return kernel
  299. def wrapper_uhpath_do_naive(k_func, itr):
  300. i = itr[0]
  301. j = itr[1]
  302. return i, j, _untilhpathkernel_do_naive(G_plist[i], G_plist[j], k_func)
  303. # @todo: (can be removed maybe) this method find paths repetively, it could be faster.
  304. def find_all_paths_until_length(G,
  305. length,
  306. ds_attrs,
  307. node_label='atom',
  308. edge_label='bond_type'):
  309. """Find all paths no longer than a certain maximum length in a graph. A
  310. recursive depth first search is applied.
  311. Parameters
  312. ----------
  313. G : NetworkX graphs
  314. The graph in which paths are searched.
  315. length : integer
  316. The maximum length of paths.
  317. ds_attrs: dict
  318. Dataset attributes.
  319. node_label : string
  320. Node attribute used as label. The default node label is atom.
  321. edge_label : string
  322. Edge attribute used as label. The default edge label is bond_type.
  323. Return
  324. ------
  325. path : list
  326. List of paths retrieved, where for unlabeled graphs, each path is
  327. represented by a list of nodes; while for labeled graphs, each path is
  328. represented by a list of strings consists of labels of nodes and/or
  329. edges on that path.
  330. """
  331. # path_l = [tuple([n]) for n in G.nodes] # paths of length l
  332. # all_paths = path_l[:]
  333. # for l in range(1, length + 1):
  334. # path_l_new = []
  335. # for path in path_l:
  336. # for neighbor in G[path[-1]]:
  337. # if len(path) < 2 or neighbor != path[-2]:
  338. # tmp = path + (neighbor, )
  339. # if tuple(tmp[::-1]) not in path_l_new:
  340. # path_l_new.append(tuple(tmp))
  341. # all_paths += path_l_new
  342. # path_l = path_l_new[:]
  343. path_l = [[n] for n in G.nodes] # paths of length l
  344. all_paths = path_l[:]
  345. for l in range(1, length + 1):
  346. path_lplus1 = []
  347. for path in path_l:
  348. for neighbor in G[path[-1]]:
  349. if neighbor not in path:
  350. tmp = path + [neighbor]
  351. # if tmp[::-1] not in path_lplus1:
  352. path_lplus1.append(tmp)
  353. all_paths += path_lplus1
  354. path_l = path_lplus1[:]
  355. # for i in range(0, length + 1):
  356. # new_paths = find_all_paths(G, i)
  357. # if new_paths == []:
  358. # break
  359. # all_paths.extend(new_paths)
  360. # consider labels
  361. # print(paths2labelseqs(all_paths, G, ds_attrs, node_label, edge_label))
  362. return paths2labelseqs(all_paths, G, ds_attrs, node_label, edge_label)
  363. def wrapper_find_all_paths_until_length(length, ds_attrs, node_label,
  364. edge_label, itr_item):
  365. g = itr_item[0]
  366. i = itr_item[1]
  367. return i, find_all_paths_until_length(g, length, ds_attrs,
  368. node_label=node_label, edge_label=edge_label)
  369. def find_all_path_as_trie(G,
  370. length,
  371. ds_attrs,
  372. node_label='atom',
  373. edge_label='bond_type'):
  374. # time1 = time.time()
  375. # all_path = find_all_paths_until_length(G, length, ds_attrs,
  376. # node_label=node_label,
  377. # edge_label=edge_label)
  378. # ptrie = Trie()
  379. # for path in all_path:
  380. # ptrie.insertWord(path)
  381. # ptrie = Trie()
  382. # path_l = [[n] for n in G.nodes] # paths of length l
  383. # path_l_str = paths2labelseqs(path_l, G, ds_attrs, node_label, edge_label)
  384. # for p in path_l_str:
  385. # ptrie.insertWord(p)
  386. # for l in range(1, length + 1):
  387. # path_lplus1 = []
  388. # for path in path_l:
  389. # for neighbor in G[path[-1]]:
  390. # if neighbor not in path:
  391. # tmp = path + [neighbor]
  392. ## if tmp[::-1] not in path_lplus1:
  393. # path_lplus1.append(tmp)
  394. # path_l = path_lplus1[:]
  395. # # consider labels
  396. # path_l_str = paths2labelseqs(path_l, G, ds_attrs, node_label, edge_label)
  397. # for p in path_l_str:
  398. # ptrie.insertWord(p)
  399. #
  400. # print(time.time() - time1)
  401. # print(ptrie.root)
  402. # print()
  403. # traverse all paths up to length h in a graph and construct a trie with
  404. # them. Deep-first search is applied. Notice the reverse of each path is
  405. # also stored to the trie.
  406. def traverseGraph(root, ptrie, length, G, ds_attrs, node_label, edge_label,
  407. pcurrent=[]):
  408. if len(pcurrent) < length + 1:
  409. for neighbor in G[root]:
  410. if neighbor not in pcurrent:
  411. pcurrent.append(neighbor)
  412. plstr = paths2labelseqs([pcurrent], G, ds_attrs,
  413. node_label, edge_label)
  414. ptrie.insertWord(plstr[0])
  415. traverseGraph(neighbor, ptrie, length, G, ds_attrs,
  416. node_label, edge_label, pcurrent)
  417. del pcurrent[-1]
  418. ptrie = Trie()
  419. path_l = [[n] for n in G.nodes] # paths of length l
  420. path_l_str = paths2labelseqs(path_l, G, ds_attrs, node_label, edge_label)
  421. for p in path_l_str:
  422. ptrie.insertWord(p)
  423. for n in G.nodes:
  424. traverseGraph(n, ptrie, length, G, ds_attrs, node_label, edge_label,
  425. pcurrent=[n])
  426. # def traverseGraph(root, all_paths, length, G, ds_attrs, node_label, edge_label,
  427. # pcurrent=[]):
  428. # if len(pcurrent) < length + 1:
  429. # for neighbor in G[root]:
  430. # if neighbor not in pcurrent:
  431. # pcurrent.append(neighbor)
  432. # plstr = paths2labelseqs([pcurrent], G, ds_attrs,
  433. # node_label, edge_label)
  434. # all_paths.append(pcurrent[:])
  435. # traverseGraph(neighbor, all_paths, length, G, ds_attrs,
  436. # node_label, edge_label, pcurrent)
  437. # del pcurrent[-1]
  438. #
  439. #
  440. # path_l = [[n] for n in G.nodes] # paths of length l
  441. # all_paths = path_l[:]
  442. # path_l_str = paths2labelseqs(path_l, G, ds_attrs, node_label, edge_label)
  443. ## for p in path_l_str:
  444. ## ptrie.insertWord(p)
  445. # for n in G.nodes:
  446. # traverseGraph(n, all_paths, length, G, ds_attrs, node_label, edge_label,
  447. # pcurrent=[n])
  448. # print(ptrie.root)
  449. return ptrie
  450. def wrapper_find_all_path_as_trie(length, ds_attrs, node_label,
  451. edge_label, itr_item):
  452. g = itr_item[0]
  453. i = itr_item[1]
  454. return i, find_all_path_as_trie(g, length, ds_attrs,
  455. node_label=node_label, edge_label=edge_label)
  456. def paths2labelseqs(plist, G, ds_attrs, node_label, edge_label):
  457. if ds_attrs['node_labeled']:
  458. if ds_attrs['edge_labeled']:
  459. path_strs = [
  460. tuple(
  461. list(
  462. chain.from_iterable(
  463. (G.node[node][node_label],
  464. G[node][path[idx + 1]][edge_label])
  465. for idx, node in enumerate(path[:-1]))) +
  466. [G.node[path[-1]][node_label]]) for path in plist
  467. ]
  468. # path_strs = []
  469. # for path in all_paths:
  470. # strlist = list(
  471. # chain.from_iterable((G.node[node][node_label],
  472. # G[node][path[idx + 1]][edge_label])
  473. # for idx, node in enumerate(path[:-1])))
  474. # strlist.append(G.node[path[-1]][node_label])
  475. # path_strs.append(tuple(strlist))
  476. else:
  477. path_strs = [
  478. tuple([G.node[node][node_label] for node in path])
  479. for path in plist
  480. ]
  481. return path_strs
  482. else:
  483. if ds_attrs['edge_labeled']:
  484. return [
  485. tuple([] if len(path) == 1 else [
  486. G[node][path[idx + 1]][edge_label]
  487. for idx, node in enumerate(path[:-1])
  488. ]) for path in plist
  489. ]
  490. else:
  491. return [tuple(['0' for node in path]) for path in plist]
  492. # return [tuple([len(path)]) for path in all_paths]
  493. #
  494. #def paths2GSuffixTree(paths):
  495. # return Tree(paths, builder=ukkonen.Builder)
  496. # def find_paths(G, source_node, length):
  497. # """Find all paths no longer than a certain length those start from a source node. A recursive depth first search is applied.
  498. # Parameters
  499. # ----------
  500. # G : NetworkX graphs
  501. # The graph in which paths are searched.
  502. # source_node : integer
  503. # The number of the node from where all paths start.
  504. # length : integer
  505. # The length of paths.
  506. # Return
  507. # ------
  508. # path : list of list
  509. # List of paths retrieved, where each path is represented by a list of nodes.
  510. # """
  511. # return [[source_node]] if length == 0 else \
  512. # [[source_node] + path for neighbor in G[source_node]
  513. # for path in find_paths(G, neighbor, length - 1) if source_node not in path]
  514. # def find_all_paths(G, length):
  515. # """Find all paths with a certain length in a graph. A recursive depth first search is applied.
  516. # Parameters
  517. # ----------
  518. # G : NetworkX graphs
  519. # The graph in which paths are searched.
  520. # length : integer
  521. # The length of paths.
  522. # Return
  523. # ------
  524. # path : list of list
  525. # List of paths retrieved, where each path is represented by a list of nodes.
  526. # """
  527. # all_paths = []
  528. # for node in G:
  529. # all_paths.extend(find_paths(G, node, length))
  530. # # The following process is not carried out according to the original article
  531. # # all_paths_r = [ path[::-1] for path in all_paths ]
  532. # # # For each path, two presentation are retrieved from its two extremities. Remove one of them.
  533. # # for idx, path in enumerate(all_paths[:-1]):
  534. # # for path2 in all_paths_r[idx+1::]:
  535. # # if path == path2:
  536. # # all_paths[idx] = []
  537. # # break
  538. # # return list(filter(lambda a: a != [], all_paths))
  539. # return all_paths

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