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

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

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