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

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