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

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

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