patternMatching.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  1. # coding: utf-8
  2. """
  3. Author: Sten Vercamman
  4. Univeristy of Antwerp
  5. Example code for paper: Efficient model transformations for novices
  6. url: http://msdl.cs.mcgill.ca/people/hv/teaching/MSBDesign/projects/Sten.Vercammen
  7. The main goal of this code is to give an overview, and an understandable
  8. implementation, of known techniques for pattern matching and solving the
  9. sub-graph homomorphism problem. The presented techniques do not include
  10. performance adaptations/optimizations. It is not optimized to be efficient
  11. but rather for the ease of understanding the workings of the algorithms.
  12. The paper does list some possible extensions/optimizations.
  13. It is intended as a guideline, even for novices, and provides an in-depth look
  14. at the workings behind various techniques for efficient pattern matching.
  15. """
  16. import collections
  17. import itertools
  18. class PatternMatching(object):
  19. """
  20. Returns an occurrence of a given pattern from the given Graph
  21. """
  22. def __init__(self, optimize=True):
  23. self.optimize = optimize
  24. def matchNaive(self, pattern, vertices, edges, pattern_vertices=None):
  25. """
  26. Try to find an occurrence of the pattern in the Graph naively.
  27. """
  28. # print('matchNaive...')
  29. # print('pattern.vertices:', pattern.vertices)
  30. # print('pattern.edges:', pattern.edges)
  31. # print('vertices:', vertices)
  32. # print('edges:', edges)
  33. # print('pattern_vertices:', pattern_vertices)
  34. # allow call with specific arguments
  35. if pattern_vertices == None:
  36. pattern_vertices = pattern.vertices
  37. def visitEdge(pattern_vertices, p_edge, inc, g_edges, visited_p_vertices, visited_p_edges, visited_g_vertices, visited_g_edges, vertices, edges):
  38. # print('visitEdge')
  39. """
  40. Visit a pattern edge, and try to bind it to a graph edge.
  41. (If the first fails, try the second, and so on...)
  42. """
  43. for g_edge in g_edges:
  44. # only reckon the edge if its in edges and not visited
  45. # (as the graph might be a subgraph of a more complex graph)
  46. if g_edge not in edges.get(g_edge.type, []) or g_edge in visited_g_edges:
  47. continue
  48. if g_edge.type == p_edge.type and g_edge not in visited_g_edges:
  49. visited_p_edges[p_edge] = g_edge
  50. visited_g_edges.add(g_edge)
  51. if inc:
  52. p_vertex = p_edge.src
  53. else:
  54. p_vertex = p_edge.tgt
  55. if visitVertices(pattern_vertices, p_vertex, visited_p_vertices, visited_p_edges, visited_g_vertices, visited_g_edges, vertices, edges):
  56. return True
  57. # remove added edges if they lead to no match, retry with others
  58. del visited_p_edges[p_edge]
  59. visited_g_edges.remove(g_edge)
  60. # no edge leads to a possitive match
  61. return False
  62. def visitEdges(pattern_vertices, p_edges, inc, g_edges, visited_p_vertices, visited_p_edges, visited_g_vertices, visited_g_edges, vertices, edges):
  63. # print('visitEdges')
  64. """
  65. Visit all edges of the pattern vertex (edges given as argument).
  66. We need to try visiting them for all its permutations, as matching
  67. v -e1-> first and v -e2-> second and v -e3-> third, might not result
  68. in a matching an occurrence of the pattern, but matching v -e2->
  69. first and v -e3-> second and v -e1-> third might.
  70. """
  71. def removePrevEdge(visitedEdges, visited_p_edges, visited_g_edges):
  72. """
  73. Undo the binding of the brevious edge, (the current bindinds do
  74. not lead to an occurrence of the pattern in the graph).
  75. """
  76. for wrong_edge in visitedEdges:
  77. # remove binding (pattern edge to graph edge)
  78. wrong_g_edge = visited_p_edges.get(wrong_edge)
  79. del visited_p_edges[wrong_edge]
  80. # remove visited graph edge
  81. visited_g_edges.remove(wrong_g_edge)
  82. for it in itertools.permutations(p_edges):
  83. visitedEdges = []
  84. foundallEdges = True
  85. for edge in it:
  86. if visited_p_edges.get(edge) == None:
  87. if not visitEdge(pattern_vertices, edge, inc, g_edges, visited_p_vertices, visited_p_edges, visited_g_vertices, visited_g_edges, vertices, edges):
  88. # this did not work, so we have to undo all added edges
  89. # (the current edge is not added, as it failed)
  90. # we then can try a different permutation
  91. removePrevEdge(visitedEdges, visited_p_edges, visited_g_edges)
  92. foundallEdges = False
  93. break # try other order
  94. # add good visited (we know it succeeded)
  95. visitedEdges.append(edge)
  96. else:
  97. # we visited this pattern edge, and have the coressponding graph edge
  98. # if it is an incoming pattern edge, we need to make sure that
  99. # the graph target that is map from the pattern target
  100. # (of this incoming pattern edge, which has to be bound at this point)
  101. # has the graph adge as an incoming edge,
  102. # otherwise the graph is not properly connected
  103. if inc:
  104. if not visited_p_edges[edge] in visited_p_vertices[edge.tgt].incoming_edges:
  105. # did not work
  106. removePrevEdge(visitedEdges, visited_p_edges, visited_g_edges)
  107. foundallEdges = False
  108. break # try other order
  109. else:
  110. # analog for an outgoing edge
  111. if not visited_p_edges[edge] in visited_p_vertices[edge.src].outgoing_edges:
  112. # did not work
  113. removePrevEdge(visitedEdges, visited_p_edges, visited_g_edges)
  114. foundallEdges = False
  115. break # try other order
  116. # all edges are good, look no further
  117. if foundallEdges:
  118. break
  119. return foundallEdges
  120. def visitVertex(pattern_vertices, p_vertex, g_vertex, visited_p_vertices, visited_p_edges, visited_g_vertices, visited_g_edges, vertices, edges):
  121. # print('visitVertex')
  122. """
  123. Visit a pattern vertex, and try to bind it to the graph vertex
  124. (both are given as argument). A binding is successful if all the
  125. pattern vertex his incoming and outgoing edges can be bound
  126. (to the graph vertex).
  127. """
  128. if g_vertex in visited_g_vertices:
  129. return False
  130. # save visited graph vertex
  131. visited_g_vertices.add(g_vertex)
  132. # map pattern vertex to visited graph vertex
  133. visited_p_vertices[p_vertex] = g_vertex
  134. if visitEdges(pattern_vertices, p_vertex.incoming_edges, True, g_vertex.incoming_edges, visited_p_vertices, visited_p_edges, visited_g_vertices, visited_g_edges, vertices, edges):
  135. if visitEdges(pattern_vertices, p_vertex.outgoing_edges, False, g_vertex.outgoing_edges, visited_p_vertices, visited_p_edges, visited_g_vertices, visited_g_edges, vertices, edges):
  136. return True
  137. # cleanup, remove from visited as this does not lead to
  138. # an occurrence of the pttern in the graph
  139. visited_g_vertices.remove(g_vertex)
  140. del visited_p_vertices[p_vertex]
  141. return False
  142. def visitVertices(pattern_vertices, p_vertex, visited_p_vertices, visited_p_edges, visited_g_vertices, visited_g_edges, vertices, edges):
  143. # print('visitVertices')
  144. """
  145. Visit a pattern vertex and try to bind a graph vertex to it.
  146. """
  147. # if already matched or if it is a vertex not in the pattern_vertices
  148. # (second is for when you want to match the pattern partionally)
  149. if visited_p_vertices.get(p_vertex) != None or p_vertex not in pattern_vertices.get(p_vertex.type, set()):
  150. return True
  151. # try visiting graph vertices of same type as pattern vertex
  152. for g_vertex in vertices.get(p_vertex.type, []):
  153. if g_vertex not in visited_g_vertices:
  154. if visitVertex(pattern_vertices, p_vertex, g_vertex, visited_p_vertices, visited_p_edges, visited_g_vertices, visited_g_edges, vertices, edges):
  155. return True
  156. return False
  157. visited_p_vertices = {}
  158. visited_p_edges = {}
  159. visited_g_vertices = set()
  160. visited_g_edges = set()
  161. # for loop is need for when pattern consists of multiple not connected structures
  162. allVertices = []
  163. for _, p_vertices in pattern_vertices.items():
  164. allVertices.extend(p_vertices)
  165. foundIt = False
  166. for it_p_vertices in itertools.permutations(allVertices):
  167. foundIt = True
  168. for p_vertex in it_p_vertices:
  169. if not visitVertices(pattern_vertices, p_vertex, visited_p_vertices, visited_p_edges, visited_g_vertices, visited_g_edges, vertices, edges):
  170. foundIt = False
  171. # reset visited
  172. visited_p_vertices = {}
  173. visited_p_edges = {}
  174. visited_g_vertices = set()
  175. visited_g_edges = set()
  176. break
  177. if foundIt:
  178. break
  179. if foundIt:
  180. return (visited_p_vertices, visited_p_edges)
  181. else:
  182. return None
  183. def createAdjacencyMatrixMap(self, graph, pattern):
  184. """
  185. Return adjacency matrix and the order of the vertices.
  186. """
  187. # print('createAdjacencyMatrixMap...')
  188. # print('graph:', graph)
  189. # print('pattern:', pattern)
  190. matrix = collections.OrderedDict() # { vertex, (index, [has edge from index to pos?]) }
  191. # contains all vertices we'll use for the AdjacencyMatrix
  192. allVertices = []
  193. if self.optimize:
  194. # insert only the vertices from the graph which have a type
  195. # that is present in the pattern
  196. for vertex_type, _ in pattern.vertices.items():
  197. graph_vertices = graph.vertices.get(vertex_type)
  198. if graph_vertices != None:
  199. allVertices.extend(graph_vertices)
  200. else:
  201. # we will not be able to find the pattern
  202. # as the pattern contains a vertex of a certain type
  203. # that is not present in the host graph
  204. return False
  205. else:
  206. # insert all vertices from the graph
  207. for _, vertices in graph.vertices.items():
  208. allVertices.extend(vertices)
  209. # create squared zero matrix
  210. index = 0
  211. for vertex in allVertices:
  212. matrix[vertex] = (index, [False] * len(allVertices))
  213. index += 1
  214. for _, edges in graph.edges.items():
  215. for edge in edges:
  216. if self.optimize:
  217. if edge.tgt not in matrix or edge.src not in matrix:
  218. # skip adding edge if the target or source type
  219. # is not present in the pattern
  220. # (and therefor not added to the matrix)
  221. continue
  222. index = matrix[edge.tgt][0]
  223. matrix[edge.src][1][index] = True
  224. AM = []
  225. vertices_order = []
  226. for vertex, row in matrix.items():
  227. AM.append(row[1])
  228. vertices_order.append(vertex)
  229. return AM, vertices_order
  230. def matchVF2(self, pattern, graph):
  231. # print('matchVF2...')
  232. # print('pattern:', pattern)
  233. # print('graph:', graph)
  234. class VF2_Obj(object):
  235. """
  236. Structor for keeping the VF2 data.
  237. """
  238. def __init__(self, len_graph_vertices, len_pattern_vertices):
  239. # represents if n-the element (h[n] or p[n]) matched
  240. self.host_vtx_is_matched = [False]*len_graph_vertices
  241. self.pattern_vtx_is_matched = [False]*len_pattern_vertices
  242. # save mapping from pattern to graph
  243. self.mapping = {}
  244. self.edge_mapping = {}
  245. # preference lvl 1
  246. # ordered set of vertices adjecent to M_graph connected via an outgoing edge
  247. self.N_out_graph = [-1]*len_graph_vertices
  248. # ordered set of vertices adjecent to M_pattern connected via an outgoing edge
  249. self.N_out_pattern = [-1]*len_pattern_vertices
  250. # preference lvl 2
  251. # ordered set of vertices adjecent to M_graph connected via an incoming edge
  252. self.N_inc_graph = [-1]*len_graph_vertices
  253. # ordered set of vertices adjecent to M_pattern connected via an incoming edge
  254. self.N_inc_pattern = [-1]*len_pattern_vertices
  255. # preference lvl 3
  256. # not in the above
  257. def findM(H, P, h, p, VF2_obj, index_M=0):
  258. """
  259. Find an isomorphic mapping for the vertices of P to H.
  260. This mapping is represented by a matrix M if,
  261. and only if M(MH)^T = P^T.
  262. This operates in a simular way as Ullmann. Ullmann has a predefind
  263. order for matching (sorted on most edges first). VF2's order is to
  264. first try to match the adjacency vertices connected via outgoing
  265. edges, then thos connected via incoming edges and then those that
  266. not connected to the currently mathed vertices.
  267. """
  268. def addOutNeighbours(neighbours, N, index_M):
  269. """
  270. Given outgoing neighbours (a row from an adjacency matrix),
  271. label them as added by saving when they got added (index_M
  272. represents this, otherwise it is -1)
  273. """
  274. for neighbour_index in range(0, len(neighbours)):
  275. if neighbours[neighbour_index]:
  276. if N[neighbour_index] == -1:
  277. N[neighbour_index] = index_M
  278. def addIncNeighbours(G, j, N, index_M):
  279. """
  280. Given the adjacency matrix, and the colum j, representing that
  281. we want to add the incoming edges to vertex j,
  282. label them as added by saving when they got added (index_M
  283. represents this, otherwise it is -1)
  284. """
  285. for i in range(0, len(G)):
  286. if G[i][j]:
  287. if N[i] == -1:
  288. N[i] = index_M
  289. def delNeighbours(N, index_M):
  290. """
  291. Remove neighbours that where added at index_M.
  292. If we call this function, we are backtracking and we want to
  293. remove the added neighbours from the just tried matching (n, m)
  294. pair (whiched failed).
  295. """
  296. for n in range(0, len(N)):
  297. if N[n] == index_M:
  298. N[n] = -1
  299. def feasibilityTest(H, P, h, p, VF2_obj, n, m):
  300. """
  301. Examine all the nodes connected to n and m; if such nodes are
  302. in the current partial mapping, check if each branch from or to
  303. n has a corresponding branch from or to m and vice versa.
  304. If the nodes and the branches of the graphs being matched also
  305. carry semantic attributes, another condition must also hold for
  306. F(s, n, m) to be true; namely the attributes of the nodes and of
  307. the branches being paired must be compatible.
  308. Another pruning step is to check if the nr of ext_edges between
  309. the matched_vertices from the pattern and its adjecent vertices
  310. are less than or equal to the nr of ext_edges between
  311. matched_vertices from the graph and its adjecent vertices.
  312. And if the nr of ext_edges between those adjecent vertices from
  313. the pattern and the not connected vertices are less than or
  314. equal to the nr of ext_edges between those adjecent vertices from
  315. the graph and its adjecent vertices.
  316. """
  317. # Get all neighbours from graph node n and pattern node m
  318. # (including n and m)
  319. neighbours_graph = {}
  320. neighbours_graph[h[n].type] = set([h[n]])
  321. neighbours_pattern = {}
  322. neighbours_pattern[p[m].type] = set([p[m]])
  323. # add all neihgbours of pattern vertex m
  324. for i in range(0, len(P)): # P is a nxn-matrix
  325. if (P[m][i] or P[i][m]) and VF2_obj.pattern_vtx_is_matched[i]:
  326. neighbours_pattern.setdefault(p[i].type, set()).add(p[i])
  327. # add all neihgbours of graph vertex n
  328. for i in range(0, len(H)): # P is a nxn-matrix
  329. if (H[n][i] or H[i][n]) and VF2_obj.host_vtx_is_matched[i]:
  330. neighbours_graph.setdefault(h[i].type, set()).add(h[i])
  331. # take a coding shortcut,
  332. # use self.matchNaive function to see if it is feasable.
  333. # this way, we immidiatly test the semantic attributes
  334. # print('pattern.vertices', pattern.vertices)
  335. matched = self.matchNaive(pattern, pattern_vertices=neighbours_pattern, vertices=neighbours_graph, edges=graph.edges)
  336. if matched == None:
  337. return False
  338. # count ext_edges from host_vtx_is_matched to a adjecent vertices and
  339. # cuotn ext_edges for adjecent vertices and not matched vertices
  340. # connected via the ext_edges
  341. ext_edges_graph_ca = 0
  342. ext_edges_graph_an = 0
  343. # for all core vertices
  344. for x in range(0, len(VF2_obj.host_vtx_is_matched)):
  345. # for all its neighbours
  346. for y in range(0, len(H)):
  347. if H[x][y]:
  348. # if it is a neighbor and not yet matched
  349. if (VF2_obj.N_out_graph[y] != -1 or VF2_obj.N_inc_graph[y] != -1) and VF2_obj.host_vtx_is_matched[y]:
  350. # if we matched it
  351. if VF2_obj.host_vtx_is_matched[x] != -1:
  352. ext_edges_graph_ca += 1
  353. else:
  354. ext_edges_graph_an += 1
  355. # count ext_edges from pattern_vtx_is_matched to a adjecent vertices
  356. # connected via the ext_edges
  357. ext_edges_pattern_ca = 0
  358. ext_edges_pattern_an = 0
  359. # for all core vertices
  360. for x in range(0, len(VF2_obj.pattern_vtx_is_matched)):
  361. # for all its neighbours
  362. for y in range(0, len(P)):
  363. if P[x][y]:
  364. # if it is a neighbor and not yet matched
  365. if (VF2_obj.N_out_pattern[y] != -1 or VF2_obj.N_inc_pattern[y] != -1) and VF2_obj.pattern_vtx_is_matched[y]:
  366. # if we matched it
  367. if VF2_obj.pattern_vtx_is_matched[x] != -1:
  368. ext_edges_pattern_ca += 1
  369. else:
  370. ext_edges_pattern_an += 1
  371. # The nr of ext_edges between matched_vertices from the pattern
  372. # and its adjecent vertices must be less than or equal to the nr
  373. # of ext_edges between matched_vertices from the graph and its
  374. # adjecent vertices, otherwise we wont find an occurrence
  375. if ext_edges_pattern_ca > ext_edges_graph_ca:
  376. return False
  377. # The nr of ext_edges between those adjancent vertices from the
  378. # pattern and its not connected vertices must be less than or
  379. # equal to the nr of ext_edges between those adjacent vertices
  380. # from the graph and its not connected vertices,
  381. # otherwise we wont find an occurrence
  382. if ext_edges_pattern_an > ext_edges_graph_an:
  383. return False
  384. return matched
  385. def matchPhase(index_M, VF2_obj, n, m):
  386. """
  387. The matching fase of the VF2 algorithm. If the chosen n, m pair
  388. passes the feasibilityTest, the pair gets added and we start
  389. to search for the next matching pair.
  390. """
  391. # all candidate pair (n, m) represent graph x pattern
  392. candidate = frozenset(itertools.chain(
  393. ((i, j) for i,j in VF2_obj.mapping.items()),
  394. # ((self.reverseMapH[i], self.reverseMapP[j]) for i,j in VF2_obj.mapping.items()),
  395. [(h[n],p[m])],
  396. ))
  397. if candidate in self.alreadyVisited:
  398. # print(self.indent*" ", "candidate:", candidate)
  399. # for match in self.alreadyVisited.get(index_M, []):
  400. # if match == candidate:
  401. return False # already visited this (partial) match -> skip
  402. matched = feasibilityTest(H, P, h, p, VF2_obj, n, m)
  403. if matched != False:
  404. # print(self.indent*" ","adding to match:", n, "->", m)
  405. # adapt VF2_obj
  406. VF2_obj.host_vtx_is_matched[n] = True
  407. VF2_obj.pattern_vtx_is_matched[m] = True
  408. VF2_obj.mapping[h[n]] = p[m]
  409. # VF2_obj.edge_mapping
  410. addOutNeighbours(H[n], VF2_obj.N_out_graph, index_M)
  411. addIncNeighbours(H, n, VF2_obj.N_inc_graph, index_M)
  412. addOutNeighbours(P[m], VF2_obj.N_out_pattern, index_M)
  413. addIncNeighbours(P, m, VF2_obj.N_inc_pattern, index_M)
  414. if index_M > 0:
  415. # remember our partial match (shallow copy) so we don't visit it again
  416. self.alreadyVisited.add(frozenset([ (i, j) for i,j in VF2_obj.mapping.items()]))
  417. # self.alreadyVisited.setdefault(index_M, set()).add(frozenset([ (self.reverseMapH[i], self.reverseMapP[j]) for i,j in VF2_obj.mapping.items()]))
  418. # print(self.alreadyVisited)
  419. self.indent += 1
  420. matched = yield from findM(H, P, h, p, VF2_obj, index_M + 1)
  421. if matched:
  422. # return True
  423. # print(self.indent*" ","found match", len(self.results), ", continuing...")
  424. pass
  425. self.indent -= 1
  426. if True:
  427. # else:
  428. # print(self.indent*" ","backtracking... remove", n, "->", m)
  429. # else, backtrack, adapt VF2_obj
  430. VF2_obj.host_vtx_is_matched[n] = False
  431. VF2_obj.pattern_vtx_is_matched[m] = False
  432. del VF2_obj.mapping[h[n]]
  433. delNeighbours(VF2_obj.N_out_graph, index_M)
  434. delNeighbours(VF2_obj.N_inc_graph, index_M)
  435. delNeighbours(VF2_obj.N_out_pattern, index_M)
  436. delNeighbours(VF2_obj.N_inc_pattern, index_M)
  437. return False
  438. def preferred(index_M, VF2_obj, N_graph, N_pattern):
  439. """
  440. Try to match the adjacency vertices connected via outgoing
  441. or incoming edges. (Depending on what is given for N_graph and
  442. N_pattern.)
  443. """
  444. for n in range(0, len(N_graph)):
  445. # skip graph vertices that are not in VF2_obj.N_out_graph
  446. # (or already matched)
  447. if N_graph[n] == -1 or VF2_obj.host_vtx_is_matched[n]:
  448. # print(self.indent*" "," skipping")
  449. continue
  450. # print(self.indent*" "," n:", n)
  451. for m in range(0, len(N_pattern)):
  452. # skip graph vertices that are not in VF2_obj.N_out_pattern
  453. # (or already matched)
  454. if N_pattern[m] == -1 or VF2_obj.pattern_vtx_is_matched[m]:
  455. continue
  456. # print(self.indent*" "," m:", m)
  457. matched = yield from matchPhase(index_M, VF2_obj, n, m)
  458. if matched:
  459. return True
  460. return False
  461. def leastPreferred(index_M, VF2_obj):
  462. """
  463. Try to match the vertices that are not connected to the curretly
  464. matched vertices.
  465. """
  466. for n in range(0, len(VF2_obj.N_out_graph)):
  467. # skip vertices that are connected to the graph
  468. # (or already matched)
  469. if not (VF2_obj.N_out_graph[n] == -1 and VF2_obj.N_inc_graph[n] == -1) or VF2_obj.host_vtx_is_matched[n]:
  470. # print(self.indent*" "," skipping")
  471. continue
  472. # print(" n:", n)
  473. for m in range(0, len(VF2_obj.N_out_pattern)):
  474. # skip vertices that are connected to the graph
  475. # (or already matched)
  476. if not (VF2_obj.N_out_pattern[m] == -1 and VF2_obj.N_inc_pattern[m] == -1) or VF2_obj.pattern_vtx_is_matched[m]:
  477. # print(self.indent*" "," skipping")
  478. continue
  479. # print(self.indent*" "," m:", m)
  480. matched = yield from matchPhase(index_M, VF2_obj, n, m)
  481. if matched:
  482. return True
  483. return False
  484. # print(self.indent*" ","index_M:", index_M)
  485. # We are at the end, we found an candidate.
  486. if index_M == len(p):
  487. # print(self.indent*" ","end...")
  488. bound_graph_vertices = {}
  489. for vertex_bound, _ in VF2_obj.mapping.items():
  490. bound_graph_vertices.setdefault(vertex_bound.type, set()).add(vertex_bound)
  491. result = self.matchNaive(pattern, vertices=bound_graph_vertices, edges=graph.edges)
  492. if result != None:
  493. yield result
  494. return result != None
  495. if index_M > 0:
  496. # try the candidates is the preffered order
  497. # first try the adjacent vertices connected via the outgoing edges.
  498. # print(self.indent*" ","preferred L1")
  499. matched = yield from preferred(index_M, VF2_obj, VF2_obj.N_out_graph, VF2_obj.N_out_pattern)
  500. if matched:
  501. return True
  502. # print(self.indent*" ","preferred L2")
  503. # then try the adjacent vertices connected via the incoming edges.
  504. matched = yield from preferred(index_M, VF2_obj, VF2_obj.N_inc_graph, VF2_obj.N_inc_pattern)
  505. if matched:
  506. return True
  507. # print(self.indent*" ","leastPreferred")
  508. # and lastly, try the vertices not connected to the currently matched vertices
  509. matched = yield from leastPreferred(index_M, VF2_obj)
  510. if matched:
  511. return True
  512. return False
  513. # create adjacency matrix of the graph
  514. H, h = self.createAdjacencyMatrixMap(graph, pattern)
  515. # create adjacency matrix of the pattern
  516. P, p = self.createAdjacencyMatrixMap(pattern, pattern)
  517. VF2_obj = VF2_Obj(len(h), len(p))
  518. # Only for debugging:
  519. self.indent = 0
  520. self.reverseMapH = { h[i] : i for i in range(len(h))}
  521. self.reverseMapP = { p[i] : i for i in range(len(p))}
  522. # Set of partial matches already explored - prevents us from producing the same match multiple times
  523. # Encoded as a mapping from match size to the partial match
  524. self.alreadyVisited = set()
  525. yield from findM(H, P, h, p, VF2_obj)