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.

path_up_to_h.py 20 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. Created on Fri Apr 10 18:33:13 2020
  5. @author: ljia
  6. @references:
  7. [1] Liva Ralaivola, Sanjay J Swamidass, Hiroto Saigo, and Pierre
  8. Baldi. Graph kernels for chemical informatics. Neural networks,
  9. 18(8):1093–1110, 2005.
  10. """
  11. import sys
  12. from multiprocessing import Pool
  13. from tqdm import tqdm
  14. import numpy as np
  15. import networkx as nx
  16. from collections import Counter
  17. from functools import partial
  18. from gklearn.utils.parallel import parallel_gm, parallel_me
  19. from gklearn.kernels import GraphKernel
  20. from gklearn.utils import Trie
  21. class PathUpToH(GraphKernel): # @todo: add function for k_func == None
  22. def __init__(self, **kwargs):
  23. GraphKernel.__init__(self)
  24. self.__node_labels = kwargs.get('node_labels', [])
  25. self.__edge_labels = kwargs.get('edge_labels', [])
  26. self.__depth = int(kwargs.get('depth', 10))
  27. self.__k_func = kwargs.get('k_func', 'MinMax')
  28. self.__compute_method = kwargs.get('compute_method', 'trie')
  29. self.__ds_infos = kwargs.get('ds_infos', {})
  30. def _compute_gm_series(self):
  31. self.__add_dummy_labels(self._graphs)
  32. from itertools import combinations_with_replacement
  33. itr_kernel = combinations_with_replacement(range(0, len(self._graphs)), 2)
  34. if self._verbose >= 2:
  35. iterator_ps = tqdm(range(0, len(self._graphs)), desc='getting paths', file=sys.stdout)
  36. iterator_kernel = tqdm(itr_kernel, desc='calculating kernels', file=sys.stdout)
  37. else:
  38. iterator_ps = range(0, len(self._graphs))
  39. iterator_kernel = itr_kernel
  40. gram_matrix = np.zeros((len(self._graphs), len(self._graphs)))
  41. if self.__compute_method == 'trie':
  42. all_paths = [self.__find_all_path_as_trie(self._graphs[i]) for i in iterator_ps]
  43. for i, j in iterator_kernel:
  44. kernel = self.__kernel_do_trie(all_paths[i], all_paths[j])
  45. gram_matrix[i][j] = kernel
  46. gram_matrix[j][i] = kernel
  47. else:
  48. all_paths = [self.__find_all_paths_until_length(self._graphs[i]) for i in iterator_ps]
  49. for i, j in iterator_kernel:
  50. kernel = self.__kernel_do_naive(all_paths[i], all_paths[j])
  51. gram_matrix[i][j] = kernel
  52. gram_matrix[j][i] = kernel
  53. return gram_matrix
  54. def _compute_gm_imap_unordered(self):
  55. self.__add_dummy_labels(self._graphs)
  56. # get all paths of all graphs before calculating kernels to save time,
  57. # but this may cost a lot of memory for large datasets.
  58. pool = Pool(self._n_jobs)
  59. itr = zip(self._graphs, range(0, len(self._graphs)))
  60. if len(self._graphs) < 100 * self._n_jobs:
  61. chunksize = int(len(self._graphs) / self._n_jobs) + 1
  62. else:
  63. chunksize = 100
  64. all_paths = [[] for _ in range(len(self._graphs))]
  65. if self.__compute_method == 'trie' and self.__k_func is not None:
  66. get_ps_fun = self._wrapper_find_all_path_as_trie
  67. elif self.__compute_method != 'trie' and self.__k_func is not None:
  68. get_ps_fun = partial(self._wrapper_find_all_paths_until_length, True)
  69. else:
  70. get_ps_fun = partial(self._wrapper_find_all_paths_until_length, False)
  71. if self._verbose >= 2:
  72. iterator = tqdm(pool.imap_unordered(get_ps_fun, itr, chunksize),
  73. desc='getting paths', file=sys.stdout)
  74. else:
  75. iterator = pool.imap_unordered(get_ps_fun, itr, chunksize)
  76. for i, ps in iterator:
  77. all_paths[i] = ps
  78. pool.close()
  79. pool.join()
  80. # compute Gram matrix.
  81. gram_matrix = np.zeros((len(self._graphs), len(self._graphs)))
  82. if self.__compute_method == 'trie' and self.__k_func is not None:
  83. def init_worker(trie_toshare):
  84. global G_trie
  85. G_trie = trie_toshare
  86. do_fun = self._wrapper_kernel_do_trie
  87. elif self.__compute_method != 'trie' and self.__k_func is not None:
  88. def init_worker(plist_toshare):
  89. global G_plist
  90. G_plist = plist_toshare
  91. do_fun = self._wrapper_kernel_do_naive
  92. else:
  93. def init_worker(plist_toshare):
  94. global G_plist
  95. G_plist = plist_toshare
  96. do_fun = self.__wrapper_kernel_do_kernelless # @todo: what is this?
  97. parallel_gm(do_fun, gram_matrix, self._graphs, init_worker=init_worker,
  98. glbv=(all_paths,), n_jobs=self._n_jobs, verbose=self._verbose)
  99. return gram_matrix
  100. def _compute_kernel_list_series(self, g1, g_list):
  101. self.__add_dummy_labels(g_list + [g1])
  102. if self._verbose >= 2:
  103. iterator_ps = tqdm(g_list, desc='getting paths', file=sys.stdout)
  104. iterator_kernel = tqdm(range(len(g_list)), desc='calculating kernels', file=sys.stdout)
  105. else:
  106. iterator_ps = g_list
  107. iterator_kernel = range(len(g_list))
  108. kernel_list = [None] * len(g_list)
  109. if self.__compute_method == 'trie':
  110. paths_g1 = self.__find_all_path_as_trie(g1)
  111. paths_g_list = [self.__find_all_path_as_trie(g) for g in iterator_ps]
  112. for i in iterator_kernel:
  113. kernel = self.__kernel_do_trie(paths_g1, paths_g_list[i])
  114. kernel_list[i] = kernel
  115. else:
  116. paths_g1 = self.__find_all_paths_until_length(g1)
  117. paths_g_list = [self.__find_all_paths_until_length(g) for g in iterator_ps]
  118. for i in iterator_kernel:
  119. kernel = self.__kernel_do_naive(paths_g1, paths_g_list[i])
  120. kernel_list[i] = kernel
  121. return kernel_list
  122. def _compute_kernel_list_imap_unordered(self, g1, g_list):
  123. self.__add_dummy_labels(g_list + [g1])
  124. # get all paths of all graphs before calculating kernels to save time,
  125. # but this may cost a lot of memory for large datasets.
  126. pool = Pool(self._n_jobs)
  127. itr = zip(g_list, range(0, len(g_list)))
  128. if len(g_list) < 100 * self._n_jobs:
  129. chunksize = int(len(g_list) / self._n_jobs) + 1
  130. else:
  131. chunksize = 100
  132. paths_g_list = [[] for _ in range(len(g_list))]
  133. if self.__compute_method == 'trie' and self.__k_func is not None:
  134. paths_g1 = self.__find_all_path_as_trie(g1)
  135. get_ps_fun = self._wrapper_find_all_path_as_trie
  136. elif self.__compute_method != 'trie' and self.__k_func is not None:
  137. paths_g1 = self.__find_all_paths_until_length(g1)
  138. get_ps_fun = partial(self._wrapper_find_all_paths_until_length, True)
  139. else:
  140. paths_g1 = self.__find_all_paths_until_length(g1)
  141. get_ps_fun = partial(self._wrapper_find_all_paths_until_length, False)
  142. if self._verbose >= 2:
  143. iterator = tqdm(pool.imap_unordered(get_ps_fun, itr, chunksize),
  144. desc='getting paths', file=sys.stdout)
  145. else:
  146. iterator = pool.imap_unordered(get_ps_fun, itr, chunksize)
  147. for i, ps in iterator:
  148. paths_g_list[i] = ps
  149. pool.close()
  150. pool.join()
  151. # compute kernel list.
  152. kernel_list = [None] * len(g_list)
  153. def init_worker(p1_toshare, plist_toshare):
  154. global G_p1, G_plist
  155. G_p1 = p1_toshare
  156. G_plist = plist_toshare
  157. do_fun = self._wrapper_kernel_list_do
  158. def func_assign(result, var_to_assign):
  159. var_to_assign[result[0]] = result[1]
  160. itr = range(len(g_list))
  161. len_itr = len(g_list)
  162. parallel_me(do_fun, func_assign, kernel_list, itr, len_itr=len_itr,
  163. init_worker=init_worker, glbv=(paths_g1, paths_g_list), method='imap_unordered', n_jobs=self._n_jobs, itr_desc='calculating kernels', verbose=self._verbose)
  164. return kernel_list
  165. def _wrapper_kernel_list_do(self, itr):
  166. if self.__compute_method == 'trie' and self.__k_func is not None:
  167. return itr, self.__kernel_do_trie(G_p1, G_plist[itr])
  168. elif self.__compute_method != 'trie' and self.__k_func is not None:
  169. return itr, self.__kernel_do_naive(G_p1, G_plist[itr])
  170. else:
  171. return itr, self.__kernel_do_kernelless(G_p1, G_plist[itr])
  172. def _compute_single_kernel_series(self, g1, g2):
  173. self.__add_dummy_labels([g1] + [g2])
  174. if self.__compute_method == 'trie':
  175. paths_g1 = self.__find_all_path_as_trie(g1)
  176. paths_g2 = self.__find_all_path_as_trie(g2)
  177. kernel = self.__kernel_do_trie(paths_g1, paths_g2)
  178. else:
  179. paths_g1 = self.__find_all_paths_until_length(g1)
  180. paths_g2 = self.__find_all_paths_until_length(g2)
  181. kernel = self.__kernel_do_naive(paths_g1, paths_g2)
  182. return kernel
  183. def __kernel_do_trie(self, trie1, trie2):
  184. """Calculate path graph kernels up to depth d between 2 graphs using trie.
  185. Parameters
  186. ----------
  187. trie1, trie2 : list
  188. Tries that contains all paths in 2 graphs.
  189. k_func : function
  190. A kernel function applied using different notions of fingerprint
  191. similarity.
  192. Return
  193. ------
  194. kernel : float
  195. Path kernel up to h between 2 graphs.
  196. """
  197. if self.__k_func == 'tanimoto':
  198. # traverse all paths in graph1 and search them in graph2. Deep-first
  199. # search is applied.
  200. def traverseTrie1t(root, trie2, setlist, pcurrent=[]):
  201. for key, node in root['children'].items():
  202. pcurrent.append(key)
  203. if node['isEndOfWord']:
  204. setlist[1] += 1
  205. count2 = trie2.searchWord(pcurrent)
  206. if count2 != 0:
  207. setlist[0] += 1
  208. if node['children'] != {}:
  209. traverseTrie1t(node, trie2, setlist, pcurrent)
  210. else:
  211. del pcurrent[-1]
  212. if pcurrent != []:
  213. del pcurrent[-1]
  214. # traverse all paths in graph2 and find out those that are not in
  215. # graph1. Deep-first search is applied.
  216. def traverseTrie2t(root, trie1, setlist, pcurrent=[]):
  217. for key, node in root['children'].items():
  218. pcurrent.append(key)
  219. if node['isEndOfWord']:
  220. # print(node['count'])
  221. count1 = trie1.searchWord(pcurrent)
  222. if count1 == 0:
  223. setlist[1] += 1
  224. if node['children'] != {}:
  225. traverseTrie2t(node, trie1, setlist, pcurrent)
  226. else:
  227. del pcurrent[-1]
  228. if pcurrent != []:
  229. del pcurrent[-1]
  230. setlist = [0, 0] # intersection and union of path sets of g1, g2.
  231. # print(trie1.root)
  232. # print(trie2.root)
  233. traverseTrie1t(trie1.root, trie2, setlist)
  234. # print(setlist)
  235. traverseTrie2t(trie2.root, trie1, setlist)
  236. # print(setlist)
  237. kernel = setlist[0] / setlist[1]
  238. elif self.__k_func == 'MinMax': # MinMax kernel
  239. # traverse all paths in graph1 and search them in graph2. Deep-first
  240. # search is applied.
  241. def traverseTrie1m(root, trie2, sumlist, pcurrent=[]):
  242. for key, node in root['children'].items():
  243. pcurrent.append(key)
  244. if node['isEndOfWord']:
  245. # print(node['count'])
  246. count1 = node['count']
  247. count2 = trie2.searchWord(pcurrent)
  248. sumlist[0] += min(count1, count2)
  249. sumlist[1] += max(count1, count2)
  250. if node['children'] != {}:
  251. traverseTrie1m(node, trie2, sumlist, pcurrent)
  252. else:
  253. del pcurrent[-1]
  254. if pcurrent != []:
  255. del pcurrent[-1]
  256. # traverse all paths in graph2 and find out those that are not in
  257. # graph1. Deep-first search is applied.
  258. def traverseTrie2m(root, trie1, sumlist, pcurrent=[]):
  259. for key, node in root['children'].items():
  260. pcurrent.append(key)
  261. if node['isEndOfWord']:
  262. # print(node['count'])
  263. count1 = trie1.searchWord(pcurrent)
  264. if count1 == 0:
  265. sumlist[1] += node['count']
  266. if node['children'] != {}:
  267. traverseTrie2m(node, trie1, sumlist, pcurrent)
  268. else:
  269. del pcurrent[-1]
  270. if pcurrent != []:
  271. del pcurrent[-1]
  272. sumlist = [0, 0] # sum of mins and sum of maxs
  273. # print(trie1.root)
  274. # print(trie2.root)
  275. traverseTrie1m(trie1.root, trie2, sumlist)
  276. # print(sumlist)
  277. traverseTrie2m(trie2.root, trie1, sumlist)
  278. # print(sumlist)
  279. kernel = sumlist[0] / sumlist[1]
  280. else:
  281. raise Exception('The given "k_func" cannot be recognized. Possible choices include: "tanimoto", "MinMax".')
  282. return kernel
  283. def _wrapper_kernel_do_trie(self, itr):
  284. i = itr[0]
  285. j = itr[1]
  286. return i, j, self.__kernel_do_trie(G_trie[i], G_trie[j])
  287. def __kernel_do_naive(self, paths1, paths2):
  288. """Calculate path graph kernels up to depth d between 2 graphs naively.
  289. Parameters
  290. ----------
  291. paths_list : list of list
  292. List of list of paths in all graphs, where for unlabeled graphs, each
  293. path is represented by a list of nodes; while for labeled graphs, each
  294. path is represented by a string consists of labels of nodes and/or
  295. edges on that path.
  296. k_func : function
  297. A kernel function applied using different notions of fingerprint
  298. similarity.
  299. Return
  300. ------
  301. kernel : float
  302. Path kernel up to h between 2 graphs.
  303. """
  304. all_paths = list(set(paths1 + paths2))
  305. if self.__k_func == 'tanimoto':
  306. length_union = len(set(paths1 + paths2))
  307. kernel = (len(set(paths1)) + len(set(paths2)) -
  308. length_union) / length_union
  309. # vector1 = [(1 if path in paths1 else 0) for path in all_paths]
  310. # vector2 = [(1 if path in paths2 else 0) for path in all_paths]
  311. # kernel_uv = np.dot(vector1, vector2)
  312. # kernel = kernel_uv / (len(set(paths1)) + len(set(paths2)) - kernel_uv)
  313. elif self.__k_func == 'MinMax': # MinMax kernel
  314. path_count1 = Counter(paths1)
  315. path_count2 = Counter(paths2)
  316. vector1 = [(path_count1[key] if (key in path_count1.keys()) else 0)
  317. for key in all_paths]
  318. vector2 = [(path_count2[key] if (key in path_count2.keys()) else 0)
  319. for key in all_paths]
  320. kernel = np.sum(np.minimum(vector1, vector2)) / \
  321. np.sum(np.maximum(vector1, vector2))
  322. else:
  323. raise Exception('The given "k_func" cannot be recognized. Possible choices include: "tanimoto", "MinMax".')
  324. return kernel
  325. def _wrapper_kernel_do_naive(self, itr):
  326. i = itr[0]
  327. j = itr[1]
  328. return i, j, self.__kernel_do_naive(G_plist[i], G_plist[j])
  329. def __find_all_path_as_trie(self, G):
  330. # all_path = find_all_paths_until_length(G, length, ds_attrs,
  331. # node_label=node_label,
  332. # edge_label=edge_label)
  333. # ptrie = Trie()
  334. # for path in all_path:
  335. # ptrie.insertWord(path)
  336. # ptrie = Trie()
  337. # path_l = [[n] for n in G.nodes] # paths of length l
  338. # path_l_str = paths2labelseqs(path_l, G, ds_attrs, node_label, edge_label)
  339. # for p in path_l_str:
  340. # ptrie.insertWord(p)
  341. # for l in range(1, length + 1):
  342. # path_lplus1 = []
  343. # for path in path_l:
  344. # for neighbor in G[path[-1]]:
  345. # if neighbor not in path:
  346. # tmp = path + [neighbor]
  347. ## if tmp[::-1] not in path_lplus1:
  348. # path_lplus1.append(tmp)
  349. # path_l = path_lplus1[:]
  350. # # consider labels
  351. # path_l_str = paths2labelseqs(path_l, G, ds_attrs, node_label, edge_label)
  352. # for p in path_l_str:
  353. # ptrie.insertWord(p)
  354. #
  355. # print(time.time() - time1)
  356. # print(ptrie.root)
  357. # print()
  358. # traverse all paths up to length h in a graph and construct a trie with
  359. # them. Deep-first search is applied. Notice the reverse of each path is
  360. # also stored to the trie.
  361. def traverseGraph(root, ptrie, G, pcurrent=[]):
  362. if len(pcurrent) < self.__depth + 1:
  363. for neighbor in G[root]:
  364. if neighbor not in pcurrent:
  365. pcurrent.append(neighbor)
  366. plstr = self.__paths2labelseqs([pcurrent], G)
  367. ptrie.insertWord(plstr[0])
  368. traverseGraph(neighbor, ptrie, G, pcurrent)
  369. del pcurrent[-1]
  370. ptrie = Trie()
  371. path_l = [[n] for n in G.nodes] # paths of length l
  372. path_l_str = self.__paths2labelseqs(path_l, G)
  373. for p in path_l_str:
  374. ptrie.insertWord(p)
  375. for n in G.nodes:
  376. traverseGraph(n, ptrie, G, pcurrent=[n])
  377. # def traverseGraph(root, all_paths, length, G, ds_attrs, node_label, edge_label,
  378. # pcurrent=[]):
  379. # if len(pcurrent) < length + 1:
  380. # for neighbor in G[root]:
  381. # if neighbor not in pcurrent:
  382. # pcurrent.append(neighbor)
  383. # plstr = paths2labelseqs([pcurrent], G, ds_attrs,
  384. # node_label, edge_label)
  385. # all_paths.append(pcurrent[:])
  386. # traverseGraph(neighbor, all_paths, length, G, ds_attrs,
  387. # node_label, edge_label, pcurrent)
  388. # del pcurrent[-1]
  389. #
  390. #
  391. # path_l = [[n] for n in G.nodes] # paths of length l
  392. # all_paths = path_l[:]
  393. # path_l_str = paths2labelseqs(path_l, G, ds_attrs, node_label, edge_label)
  394. ## for p in path_l_str:
  395. ## ptrie.insertWord(p)
  396. # for n in G.nodes:
  397. # traverseGraph(n, all_paths, length, G, ds_attrs, node_label, edge_label,
  398. # pcurrent=[n])
  399. # print(ptrie.root)
  400. return ptrie
  401. def _wrapper_find_all_path_as_trie(self, itr_item):
  402. g = itr_item[0]
  403. i = itr_item[1]
  404. return i, self.__find_all_path_as_trie(g)
  405. # @todo: (can be removed maybe) this method find paths repetively, it could be faster.
  406. def __find_all_paths_until_length(self, G, tolabelseqs=True):
  407. """Find all paths no longer than a certain maximum length in a graph. A
  408. recursive depth first search is applied.
  409. Parameters
  410. ----------
  411. G : NetworkX graphs
  412. The graph in which paths are searched.
  413. length : integer
  414. The maximum length of paths.
  415. ds_attrs: dict
  416. Dataset attributes.
  417. node_label : string
  418. Node attribute used as label. The default node label is atom.
  419. edge_label : string
  420. Edge attribute used as label. The default edge label is bond_type.
  421. Return
  422. ------
  423. path : list
  424. List of paths retrieved, where for unlabeled graphs, each path is
  425. represented by a list of nodes; while for labeled graphs, each path is
  426. represented by a list of strings consists of labels of nodes and/or
  427. edges on that path.
  428. """
  429. # path_l = [tuple([n]) for n in G.nodes] # paths of length l
  430. # all_paths = path_l[:]
  431. # for l in range(1, self.__depth + 1):
  432. # path_l_new = []
  433. # for path in path_l:
  434. # for neighbor in G[path[-1]]:
  435. # if len(path) < 2 or neighbor != path[-2]:
  436. # tmp = path + (neighbor, )
  437. # if tuple(tmp[::-1]) not in path_l_new:
  438. # path_l_new.append(tuple(tmp))
  439. # all_paths += path_l_new
  440. # path_l = path_l_new[:]
  441. path_l = [[n] for n in G.nodes] # paths of length l
  442. all_paths = [p.copy() for p in path_l]
  443. for l in range(1, self.__depth + 1):
  444. path_lplus1 = []
  445. for path in path_l:
  446. for neighbor in G[path[-1]]:
  447. if neighbor not in path:
  448. tmp = path + [neighbor]
  449. # if tmp[::-1] not in path_lplus1:
  450. path_lplus1.append(tmp)
  451. all_paths += path_lplus1
  452. path_l = [p.copy() for p in path_lplus1]
  453. # for i in range(0, self.__depth + 1):
  454. # new_paths = find_all_paths(G, i)
  455. # if new_paths == []:
  456. # break
  457. # all_paths.extend(new_paths)
  458. # consider labels
  459. # print(paths2labelseqs(all_paths, G, ds_attrs, node_label, edge_label))
  460. # print()
  461. return (self.__paths2labelseqs(all_paths, G) if tolabelseqs else all_paths)
  462. def _wrapper_find_all_paths_until_length(self, tolabelseqs, itr_item):
  463. g = itr_item[0]
  464. i = itr_item[1]
  465. return i, self.__find_all_paths_until_length(g, tolabelseqs=tolabelseqs)
  466. def __paths2labelseqs(self, plist, G):
  467. if len(self.__node_labels) > 0:
  468. if len(self.__edge_labels) > 0:
  469. path_strs = []
  470. for path in plist:
  471. pths_tmp = []
  472. for idx, node in enumerate(path[:-1]):
  473. pths_tmp.append(tuple(G.nodes[node][nl] for nl in self.__node_labels))
  474. pths_tmp.append(tuple(G[node][path[idx + 1]][el] for el in self.__edge_labels))
  475. pths_tmp.append(tuple(G.nodes[path[-1]][nl] for nl in self.__node_labels))
  476. path_strs.append(tuple(pths_tmp))
  477. else:
  478. path_strs = []
  479. for path in plist:
  480. pths_tmp = []
  481. for node in path:
  482. pths_tmp.append(tuple(G.nodes[node][nl] for nl in self.__node_labels))
  483. path_strs.append(tuple(pths_tmp))
  484. return path_strs
  485. else:
  486. if len(self.__edge_labels) > 0:
  487. path_strs = []
  488. for path in plist:
  489. if len(path) == 1:
  490. path_strs.append(tuple())
  491. else:
  492. pths_tmp = []
  493. for idx, node in enumerate(path[:-1]):
  494. pths_tmp.append(tuple(G[node][path[idx + 1]][el] for el in self.__edge_labels))
  495. path_strs.append(tuple(pths_tmp))
  496. return path_strs
  497. else:
  498. return [tuple(['0' for node in path]) for path in plist]
  499. # return [tuple([len(path)]) for path in all_paths]
  500. def __add_dummy_labels(self, Gn):
  501. if self.__k_func is not None:
  502. if len(self.__node_labels) == 0:
  503. for G in Gn:
  504. nx.set_node_attributes(G, '0', 'dummy')
  505. self.__node_labels.append('dummy')
  506. if len(self.__edge_labels) == 0:
  507. for G in Gn:
  508. nx.set_edge_attributes(G, '0', 'dummy')
  509. self.__edge_labels.append('dummy')

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