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

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

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