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.

structuralspKernel.py 16 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. Created on Thu Sep 27 10:56:23 2018
  5. @author: linlin
  6. @references: Suard F, Rakotomamonjy A, Bensrhair A. Kernel on Bag of Paths For
  7. Measuring Similarity of Shapes. InESANN 2007 Apr 25 (pp. 355-360).
  8. """
  9. import sys
  10. import time
  11. from itertools import combinations, combinations_with_replacement, product
  12. from functools import partial
  13. from joblib import Parallel, delayed
  14. from multiprocessing import Pool
  15. from tqdm import tqdm
  16. import networkx as nx
  17. import numpy as np
  18. from pygraph.utils.graphdataset import get_dataset_attributes
  19. sys.path.insert(0, "../")
  20. def structuralspkernel(*args,
  21. node_label='atom',
  22. edge_weight=None,
  23. edge_label='bond_type',
  24. node_kernels=None,
  25. edge_kernels=None,
  26. n_jobs=None):
  27. """Calculate mean average structural shortest path kernels between graphs.
  28. Parameters
  29. ----------
  30. Gn : List of NetworkX graph
  31. List of graphs between which the kernels are calculated.
  32. /
  33. G1, G2 : NetworkX graphs
  34. 2 graphs between which the kernel is calculated.
  35. node_label : string
  36. node attribute used as label. The default node label is atom.
  37. edge_weight : string
  38. Edge attribute name corresponding to the edge weight.
  39. edge_label : string
  40. edge attribute used as label. The default edge label is bond_type.
  41. node_kernels: dict
  42. A dictionary of kernel functions for nodes, including 3 items: 'symb'
  43. for symbolic node labels, 'nsymb' for non-symbolic node labels, 'mix'
  44. for both labels. The first 2 functions take two node labels as
  45. parameters, and the 'mix' function takes 4 parameters, a symbolic and a
  46. non-symbolic label for each the two nodes. Each label is in form of 2-D
  47. dimension array (n_samples, n_features). Each function returns a number
  48. as the kernel value. Ignored when nodes are unlabeled.
  49. edge_kernels: dict
  50. A dictionary of kernel functions for edges, including 3 items: 'symb'
  51. for symbolic edge labels, 'nsymb' for non-symbolic edge labels, 'mix'
  52. for both labels. The first 2 functions take two edge labels as
  53. parameters, and the 'mix' function takes 4 parameters, a symbolic and a
  54. non-symbolic label for each the two edges. Each label is in form of 2-D
  55. dimension array (n_samples, n_features). Each function returns a number
  56. as the kernel value. Ignored when edges are unlabeled.
  57. Return
  58. ------
  59. Kmatrix : Numpy matrix
  60. Kernel matrix, each element of which is the mean average structural
  61. shortest path kernel between 2 praphs.
  62. """
  63. # pre-process
  64. Gn = args[0] if len(args) == 1 else [args[0], args[1]]
  65. weight = None
  66. if edge_weight is None:
  67. print('\n None edge weight specified. Set all weight to 1.\n')
  68. else:
  69. try:
  70. some_weight = list(
  71. nx.get_edge_attributes(Gn[0], edge_weight).values())[0]
  72. if isinstance(some_weight, (float, int)):
  73. weight = edge_weight
  74. else:
  75. print(
  76. '\n Edge weight with name %s is not float or integer. Set all weight to 1.\n'
  77. % edge_weight)
  78. except:
  79. print(
  80. '\n Edge weight with name "%s" is not found in the edge attributes. Set all weight to 1.\n'
  81. % edge_weight)
  82. ds_attrs = get_dataset_attributes(
  83. Gn,
  84. attr_names=['node_labeled', 'node_attr_dim', 'edge_labeled',
  85. 'edge_attr_dim', 'is_directed'],
  86. node_label=node_label, edge_label=edge_label)
  87. start_time = time.time()
  88. # get shortest paths of each graph in Gn
  89. splist = [[] for _ in range(len(Gn))]
  90. pool = Pool(n_jobs)
  91. # get shortest path graphs of Gn
  92. getsp_partial = partial(wrap_getSP, Gn, weight, ds_attrs['is_directed'])
  93. if len(Gn) < 1000 * n_jobs:
  94. # # use default chunksize as pool.map when iterable is less than 100
  95. # chunksize, extra = divmod(len(Gn), n_jobs * 4)
  96. # if extra:
  97. # chunksize += 1
  98. chunksize = int(len(Gn) / n_jobs) + 1
  99. else:
  100. chunksize = 1000
  101. # chunksize = 300 # int(len(list(itr)) / n_jobs)
  102. for i, sp in tqdm(
  103. pool.imap_unordered(getsp_partial, range(0, len(Gn)), chunksize),
  104. desc='getting shortest paths',
  105. file=sys.stdout):
  106. splist[i] = sp
  107. pool.close()
  108. pool.join()
  109. # # ---- use pool.map to parallel ----
  110. # result_sp = pool.map(getsp_partial, range(0, len(Gn)))
  111. # for i in result_sp:
  112. # Gn[i[0]] = i[1]
  113. # or
  114. # getsp_partial = partial(wrap_getSP, Gn, weight)
  115. # for i, g in tqdm(
  116. # pool.map(getsp_partial, range(0, len(Gn))),
  117. # desc='getting sp graphs',
  118. # file=sys.stdout):
  119. # Gn[i] = g
  120. # # ---- only for the Fast Computation of Shortest Path Kernel (FCSP)
  121. # sp_ml = [0] * len(Gn) # shortest path matrices
  122. # for i in result_sp:
  123. # sp_ml[i[0]] = i[1]
  124. # edge_x_g = [[] for i in range(len(sp_ml))]
  125. # edge_y_g = [[] for i in range(len(sp_ml))]
  126. # edge_w_g = [[] for i in range(len(sp_ml))]
  127. # for idx, item in enumerate(sp_ml):
  128. # for i1 in range(len(item)):
  129. # for i2 in range(i1 + 1, len(item)):
  130. # if item[i1, i2] != np.inf:
  131. # edge_x_g[idx].append(i1)
  132. # edge_y_g[idx].append(i2)
  133. # edge_w_g[idx].append(item[i1, i2])
  134. # print(len(edge_x_g[0]))
  135. # print(len(edge_y_g[0]))
  136. # print(len(edge_w_g[0]))
  137. Kmatrix = np.zeros((len(Gn), len(Gn)))
  138. # ---- use pool.imap_unordered to parallel and track progress. ----
  139. pool = Pool(n_jobs)
  140. do_partial = partial(structuralspkernel_do, Gn, splist, ds_attrs,
  141. node_label, edge_label, node_kernels, edge_kernels)
  142. itr = combinations_with_replacement(range(0, len(Gn)), 2)
  143. len_itr = int(len(Gn) * (len(Gn) + 1) / 2)
  144. if len_itr < 1000 * n_jobs:
  145. chunksize = int(len_itr / n_jobs) + 1
  146. else:
  147. chunksize = 1000
  148. for i, j, kernel in tqdm(
  149. pool.imap_unordered(do_partial, itr, chunksize),
  150. desc='calculating kernels',
  151. file=sys.stdout):
  152. Kmatrix[i][j] = kernel
  153. Kmatrix[j][i] = kernel
  154. pool.close()
  155. pool.join()
  156. # # ---- use pool.map to parallel. ----
  157. # # result_perf = pool.map(do_partial, itr)
  158. # do_partial = partial(spkernel_do, Gn, ds_attrs, node_label, node_kernels)
  159. # itr = combinations_with_replacement(range(0, len(Gn)), 2)
  160. # for i, j, kernel in tqdm(
  161. # pool.map(do_partial, itr), desc='calculating kernels',
  162. # file=sys.stdout):
  163. # Kmatrix[i][j] = kernel
  164. # Kmatrix[j][i] = kernel
  165. # pool.close()
  166. # pool.join()
  167. # # ---- use joblib.Parallel to parallel and track progress. ----
  168. # result_perf = Parallel(
  169. # n_jobs=n_jobs, verbose=10)(
  170. # delayed(do_partial)(ij)
  171. # for ij in combinations_with_replacement(range(0, len(Gn)), 2))
  172. # result_perf = [
  173. # do_partial(ij)
  174. # for ij in combinations_with_replacement(range(0, len(Gn)), 2)
  175. # ]
  176. # for i in result_perf:
  177. # Kmatrix[i[0]][i[1]] = i[2]
  178. # Kmatrix[i[1]][i[0]] = i[2]
  179. # # ---- direct running, normally use single CPU core. ----
  180. # itr = combinations_with_replacement(range(0, len(Gn)), 2)
  181. # for gs in tqdm(itr, desc='calculating kernels', file=sys.stdout):
  182. # i, j, kernel = structuralspkernel_do(Gn, splist, ds_attrs,
  183. # node_label, edge_label, node_kernels, edge_kernels, gs)
  184. # Kmatrix[i][j] = kernel
  185. # Kmatrix[j][i] = kernel
  186. run_time = time.time() - start_time
  187. print(
  188. "\n --- shortest path kernel matrix of size %d built in %s seconds ---"
  189. % (len(Gn), run_time))
  190. return Kmatrix, run_time
  191. def structuralspkernel_do(Gn, splist, ds_attrs, node_label, edge_label,
  192. node_kernels, edge_kernels, ij):
  193. iglobal = ij[0]
  194. jglobal = ij[1]
  195. g1 = Gn[iglobal]
  196. g2 = Gn[jglobal]
  197. spl1 = splist[iglobal]
  198. spl2 = splist[jglobal]
  199. kernel = 0
  200. try:
  201. # First, compute shortest path matrices, method borrowed from FCSP.
  202. if ds_attrs['node_labeled']:
  203. # node symb and non-synb labeled
  204. if ds_attrs['node_attr_dim'] > 0:
  205. kn = node_kernels['mix']
  206. vk_dict = {} # shortest path matrices dict
  207. for n1, n2 in product(
  208. g1.nodes(data=True), g2.nodes(data=True)):
  209. vk_dict[(n1[0], n2[0])] = kn(
  210. n1[1][node_label], n2[1][node_label],
  211. [n1[1]['attributes']], [n2[1]['attributes']])
  212. # node symb labeled
  213. else:
  214. kn = node_kernels['symb']
  215. vk_dict = {} # shortest path matrices dict
  216. for n1 in g1.nodes(data=True):
  217. for n2 in g2.nodes(data=True):
  218. vk_dict[(n1[0], n2[0])] = kn(n1[1][node_label],
  219. n2[1][node_label])
  220. else:
  221. # node non-synb labeled
  222. if ds_attrs['node_attr_dim'] > 0:
  223. kn = node_kernels['nsymb']
  224. vk_dict = {} # shortest path matrices dict
  225. for n1 in g1.nodes(data=True):
  226. for n2 in g2.nodes(data=True):
  227. vk_dict[(n1[0], n2[0])] = kn([n1[1]['attributes']],
  228. [n2[1]['attributes']])
  229. # node unlabeled
  230. else:
  231. vk_dict = {}
  232. # Then, compute kernels between all pairs of edges, which idea is an
  233. # extension of FCSP. It suits sparse graphs, which is the most case we
  234. # went though. For dense graphs, it would be slow.
  235. if ds_attrs['edge_labeled']:
  236. # edge symb and non-synb labeled
  237. if ds_attrs['edge_attr_dim'] > 0:
  238. ke = edge_kernels['mix']
  239. ek_dict = {} # dict of edge kernels
  240. for e1, e2 in product(
  241. g1.edges(data=True), g2.edges(data=True)):
  242. ek_dict[((e1[0], e1[1]), (e2[0], e2[1]))] = ke(
  243. e1[2][edge_label], e2[2][edge_label],
  244. [e1[2]['attributes']], [e2[2]['attributes']])
  245. # edge symb labeled
  246. else:
  247. ke = edge_kernels['symb']
  248. ek_dict = {}
  249. for e1 in g1.edges(data=True):
  250. for e2 in g2.edges(data=True):
  251. ek_dict[((e1[0], e1[1]), (e2[0], e2[1]))] = ke(
  252. e1[2][edge_label], e2[2][edge_label])
  253. else:
  254. # edge non-synb labeled
  255. if ds_attrs['edge_attr_dim'] > 0:
  256. ke = edge_kernels['nsymb']
  257. ek_dict = {}
  258. for e1 in g1.edges(data=True):
  259. for e2 in g2.edges(data=True):
  260. ek_dict[((e1[0], e1[1]), (e2[0], e2[1]))] = kn(
  261. [e1[2]['attributes']], [e2[2]['attributes']])
  262. # edge unlabeled
  263. else:
  264. ek_dict = {}
  265. # compute graph kernels
  266. if vk_dict:
  267. if ek_dict:
  268. for p1, p2 in product(spl1, spl2):
  269. if len(p1) == len(p2):
  270. kpath = vk_dict[(p1[0], p2[0])]
  271. if kpath:
  272. for idx in range(1, len(p1)):
  273. kpath *= vk_dict[(p1[idx], p2[idx])] * \
  274. ek_dict[((p1[idx-1], p1[idx]),
  275. (p2[idx-1], p2[idx]))]
  276. if not kpath:
  277. break
  278. kernel += kpath # add up kernels of all paths
  279. else:
  280. for p1, p2 in product(spl1, spl2):
  281. if len(p1) == len(p2):
  282. kpath = vk_dict[(p1[0], p2[0])]
  283. if kpath:
  284. for idx in range(1, len(p1)):
  285. kpath *= vk_dict[(p1[idx], p2[idx])]
  286. if not kpath:
  287. break
  288. kernel += kpath # add up kernels of all paths
  289. else:
  290. if ek_dict:
  291. for p1, p2 in product(spl1, spl2):
  292. if len(p1) == len(p2):
  293. if len(p1) == 0:
  294. kernel += 1
  295. else:
  296. kpath = 1
  297. for idx in range(0, len(p1) - 1):
  298. kpath *= ek_dict[((p1[idx], p1[idx+1]),
  299. (p2[idx], p2[idx+1]))]
  300. if not kpath:
  301. break
  302. kernel += kpath # add up kernels of all paths
  303. else:
  304. for p1, p2 in product(spl1, spl2):
  305. if len(p1) == len(p2):
  306. kernel += 1
  307. kernel = kernel / (len(spl1) * len(spl2)) # calculate mean average
  308. # # ---- exact implementation of the Fast Computation of Shortest Path Kernel (FCSP), reference [2], sadly it is slower than the current implementation
  309. # # compute vertex kernel matrix
  310. # try:
  311. # vk_mat = np.zeros((nx.number_of_nodes(g1),
  312. # nx.number_of_nodes(g2)))
  313. # g1nl = enumerate(g1.nodes(data=True))
  314. # g2nl = enumerate(g2.nodes(data=True))
  315. # for i1, n1 in g1nl:
  316. # for i2, n2 in g2nl:
  317. # vk_mat[i1][i2] = kn(
  318. # n1[1][node_label], n2[1][node_label],
  319. # [n1[1]['attributes']], [n2[1]['attributes']])
  320. # range1 = range(0, len(edge_w_g[i]))
  321. # range2 = range(0, len(edge_w_g[j]))
  322. # for i1 in range1:
  323. # x1 = edge_x_g[i][i1]
  324. # y1 = edge_y_g[i][i1]
  325. # w1 = edge_w_g[i][i1]
  326. # for i2 in range2:
  327. # x2 = edge_x_g[j][i2]
  328. # y2 = edge_y_g[j][i2]
  329. # w2 = edge_w_g[j][i2]
  330. # ke = (w1 == w2)
  331. # if ke > 0:
  332. # kn1 = vk_mat[x1][x2] * vk_mat[y1][y2]
  333. # kn2 = vk_mat[x1][y2] * vk_mat[y1][x2]
  334. # Kmatrix += kn1 + kn2
  335. except KeyError: # missing labels or attributes
  336. pass
  337. return iglobal, jglobal, kernel
  338. def get_shortest_paths(G, weight, directed):
  339. """Get all shortest paths of a graph.
  340. Parameters
  341. ----------
  342. G : NetworkX graphs
  343. The graphs whose paths are calculated.
  344. weight : string/None
  345. edge attribute used as weight to calculate the shortest path.
  346. directed: boolean
  347. Whether graph is directed.
  348. Return
  349. ------
  350. sp : list of list
  351. List of shortest paths of the graph, where each path is represented by a list of nodes.
  352. """
  353. sp = []
  354. for n1, n2 in combinations(G.nodes(), 2):
  355. try:
  356. spltemp = list(nx.all_shortest_paths(G, n1, n2, weight=weight))
  357. sp += spltemp
  358. # each edge walk is counted twice, starting from both its extreme nodes.
  359. if not directed:
  360. sp += [sptemp[::-1] for sptemp in spltemp]
  361. except nx.NetworkXNoPath: # nodes not connected
  362. # sp.append([])
  363. pass
  364. # add single nodes as length 0 paths.
  365. sp += [[n] for n in G.nodes()]
  366. return sp
  367. def wrap_getSP(Gn, weight, directed, i):
  368. return i, get_shortest_paths(Gn[i], weight, directed)

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